View more - Model self-reference using Mongoid ORM
Posted by layonman98 on Sun Dec 05 03:36:35 UTC 2010.
Language ruby
class User
include Mongoid::Document
identity :type => String
field :name
references_many :fans, :stored_as => :array, :class_name => 'User'
end
# Examples
View more - Cleaning hacked PHP scripts
Posted by andphe on Fri Dec 03 14:31:08 UTC 2010.
Language bash
grep -irl base64_encode * | xargs -I {} sed -i -e 's/^error_reporting.*base64_encode.*?>$/?>/' {}
View more - Crear una string "aleatoria" de 8 carácteres
Posted by mefistofeles87 on Tue Oct 19 22:02:35 UTC 2010.
Language bash
</dev/urandom tr -dc A-Za-z0-9 | head -c8
View more - Eliminar el último commit del repositorio hecho por uno, después de haber hecho push
Posted by layonman98 on Tue Oct 05 21:17:51 UTC 2010.
Language bash
git push -f origin HEAD^:master
View more - Eliminar el último commit del repositorio hecho por uno, después de haber hecho push
Posted by layonman98 on Tue Oct 05 21:17:51 UTC 2010.
Language bash
git push -f origin HEAD^:master
View more - Lista de remitentes rechazados por falta de registro SPF en Qmail/Plesk
Posted by andphe on Tue Oct 05 15:37:45 UTC 2010.
Language bash
!/bin/bash
for message in $(grep "SPF status: REJECT" /usr/local/psa/var/log/maillog | grep -oP "(\d+)(?=\])" )
do
grep "\[$message\].*from=" /usr/local/psa/var/log/maillog
done
View more -
Posted by kof.tekken3 on Sun Oct 03 03:57:08 UTC 2010.
Language as3
$conexion= mysql_connect($hostname, $usuario, $password)
or die("No se pudo conectar con el servidor");
$bd= mysql_select_db($basededatos, $conexion)
or die("No se pudo seleccionar la base de datos DEMO");
$consulta ="SELECT * FROM empresa ORDER BY nombre ASC";
$resultado = mysql_query($consulta)
or die("No se pudo ejecutar la consulta");
$numero_filas = mysql_num_rows($resultado); /*Nos guarda en la variable numero_filas
* el numero de filas existentes en la base de datos.
View more -
Posted by callo90 on Thu Aug 05 20:34:24 UTC 2010.
Language ruby
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="screen.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrapper">
<p>
<span><input type="submit" name="Submit" value="" /></span>
</p>
View more - reording array keys from zero
Posted by andphe on Tue Jul 27 16:17:19 UTC 2010.
Language php
<?php
//If you have a array that need to re-key from zero
//can use $thearray = array_merge((array),$thearray);
//Example:
$array = array(4 => 'four', 3 => 'Three', 2 => 'Two', 1 => 'One');
var_dump($array);
$array = array_merge(array(),$array);
var_dump($array);
View more - Centering the content of a page
Posted by andphe on Fri May 14 21:48:37 UTC 2010.
Language css
body {text-align: center;}
#wrapper {width:960px;margin: 0 auto;text-align:left;}
<body>
<div id="wrapper">
... blah blah blah
</div>
</body>
View more - Basic data retrieval using MongoDB C# Driver
Posted by layonman98 on Wed Apr 28 07:20:16 UTC 2010.
Language csharp
using MongoDB.Driver;
class Program
{
public static void Main()
{
var database = "test";
var collection = "users";
var server = new Mongo();
// Try to connect to localhost through the default port
View more - Múltiples proveedores de datos en una clase única usando DbFactory
Posted by layonman98 on Thu Apr 08 20:52:31 UTC 2010.
Language csharp
/* Enumeración y clase que permite realizar conexiones a distintos motores de bases de datos
* haciendo uso de distintos drivers intercalables en tiempo de ejecución y sin necesidad
* de recompilación.
* Las referencias ya deben están agregadas al proyecto, y las Connection Strings son
* obtenidas desde el archivo app.config
*/
using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
View more - Cambiar o Restaurar Autonumerico SQL Server
Posted by totho44 on Tue Mar 30 22:13:17 UTC 2010.
Language sql
DBCC CHECKIDENT ([tabla], RESEED, <num>)
--RESEED:Constante
--<num>: numero al cual queremos restaurar autonumerico
View more - simple map/reduce concept
Posted by krawek on Thu Mar 25 22:16:46 UTC 2010.
Language ruby
[1,2,3,4].reduce { |v, a| a+=v }
View more - Botón con efecto hover usando un A y que funciona en todos los navegadores
Posted by andphe on Thu Mar 25 22:04:11 UTC 2010.
Language css
/*
* Notas:
*
* - Es mejor usar un texto para el enlace porque es mas semántico
* - En el ejemplo la imagen tiene 48px de lado
*/
<a href="destinodelenlace.html" id="boton">Texto del enlace</a>
#boton{
View more - Consulta Oracle SQL (para DBA) que muestra en detalle los DataFiles y los Tablespaces creados (tamaño, espacio ocupado, espacio libre, etc)
Posted by procesoft on Fri Mar 12 21:30:58 UTC 2010.
Language sql
Select t.tablespace_name “Tablespace”, t.status “Estado”,
ROUND(MAX(d.bytes)/1024/1024,2) “MB Tamaño”,
ROUND((MAX(d.bytes)/1024/1024) -
(SUM(decode(f.bytes, NULL,0, f.bytes))/1024/1024),2) “MB Usados”,
ROUND(SUM(decode(f.bytes, NULL,0, f.bytes))/1024/1024,2) “MB Libres”,
t.pct_increase “% incremento”,
SUBSTR(d.file_name,1,80) “Fichero de datos”
FROM DBA_FREE_SPACE f, DBA_DATA_FILES d, DBA_TABLESPACES t
WHERE t.tablespace_name = d.tablespace_name AND
f.tablespace_name(+) = d.tablespace_name
View more - Consulta Oracle SQL para conocer espacio ocupado por los objetos de la Base de Datos
Posted by procesoft on Fri Mar 12 21:25:23 UTC 2010.
Language sql
SELECT SEGMENT_NAME, SUM(BYTES)/1024/1024 MB
FROM DBA_EXTENTS MB
group by SEGMENT_NAME
order by 2 desc;
View more - Final Image class
Posted by layonman98 on Thu Mar 11 14:13:56 UTC 2010.
Language csharp
public class PhotoHelper
{
internal static Image ResizeWithoutLosingProportion(Image img, int MaxWidth, int MaxHeight)
{
Image nImg = null;
if (img.Width > MaxWidth || img.Height > MaxHeight)
{
// Si la imágen NO es cuadrada
if (img.Width != img.Height)
View more - Redimensionar una imagen guardando las proporciones dadas para los valores máximos que pueda adoptar
Posted by layonman98 on Mon Mar 08 20:35:17 UTC 2010.
Language csharp
Bitmap ResizeWithoutLosingProportion( Image img, int MaxWidth, int MaxHeight )
{
Image nImg = null;
// Si la imágen sobrepasa el tamaño máximo
if ( img.Width > MaxWidth || img.Height > MaxHeight )
{
// Si la imágen NO es cuadrada
if ( img.Width != img.Height )
{
// Si la imágen es 'a lo alto'
View more - Usos de Linq en C#, Usando un Arreglo.
Posted by mijaelbenmanuel on Mon Mar 08 02:08:48 UTC 2010.
Language csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQ_prueba
{
class Program
{
static void Main(string[] args)
View more - Validar campos ( TextBox ) vacíos en un Windows Form
Posted by layonman98 on Sun Mar 07 15:55:36 UTC 2010.
Language csharp
using System.Windows.Forms;
using System.Drawing;
public static bool HasEmptyFields( Control.ControlCollection container )
{
var filledFiels = 0;
var textboxCount = 0;
foreach( Control c in container )
{
if( typeof( TextBox ) == c.GetType() )
View more - Acceder a Twitter por NetworkCredentials
Posted by efrrojas on Mon Mar 01 17:08:00 UTC 2010.
Language csharp
public static Usuario ValidarUsuario(string User, string Pass)
{
Usuario userActual = new Usuario();
try
{
NetworkCredential credencial = new NetworkCredential
{
UserName = User,
Password = Pass
};
View more - Métodos para convertir imágenes en arreglos de bytes y viceversa ( arreglo de bytes a imágenes )
Posted by layonman98 on Mon Mar 01 03:32:37 UTC 2010.
Language csharp
/* Con esta clase y sus métodos estáticos se pueden convertir imágenes
* en arreglos de bytes ( byte[] ) y viceversa.
* Excelente recurso a la hora de guardar y recuperar imágenes en bases de datos
*/
using System.Drawing;
using System.Drawing.Imagin;
using System.IO;
public class PhotoHelper
View more - Procedimiento Almacenado en PostgreSQL que retorna un resultset
Posted by layonman98 on Mon Mar 01 03:24:37 UTC 2010.
Language sql
-- Ejemplo de procedimiento que recupera un registro de la tabla User
-- CREATE FUNCTION schema.func_name( params ) RETURNS type AS $$ ...
CREATE OR REPLACE FUNCTION public.user_read( IN_user_id INTEGER ) RETURNS SETOF public.user AS
$$
BEGIN
RETURN QUERY
SELECT user_id, name, age
FROM public.user
WHERE user_id = IN_user_id;
View more - metodos publicos de un objeto js
Posted by kuadrosxx on Fri Feb 26 18:46:56 UTC 2010.
Language ruby
for (property in object) { console.log(property) }
View more - Mini OOP wrapper for Mysql PHP functions
Posted by nebiros on Fri Feb 26 16:51:47 UTC 2010.
Language php
<?php
class App_Db_Adapter_Mysql
{
protected $_options = array(
"host" => "localhost",
"username" => "root",
"password" => "",
"dbname" => ""
);
View more - Ejemplo de una clase genérica ( Generics ) con DAO
Posted by layonman98 on Fri Feb 26 15:01:21 UTC 2010.
Language csharp
using System.Collections.Generic;
// Model
public class User
{
public string Name { get; set; }
pubilc int Age { get; set; }
public User( string name, int age )
{
View more -
Posted by nebiros on Fri Feb 26 14:23:17 UTC 2010.
Language php
<?php
if ( false === empty( $_FILES ) )
{
$extExplode = explode( ".", $_FILES["image"]["name"] );
$ext = strtolower( array_pop( $extExplode ) );
$uniqId = md5( uniqid( rand(), true ) );
$imageFilename = "{$uniqId}.{$ext}";
if ( false === move_uploaded_file( $_FILES["image"]["tmp_name"], APPLICATION_PATH. "/images/{$imageFilename}" ) )
View more - Centering vertically a span within a label
Posted by andphe on Wed Feb 24 21:40:34 UTC 2010.
Language css
/*This css contains hacks for IE, you could put the styles that begins with * under his own stylesheet for IE.
this centers vertically a span within a label <label for="foo"><span>foo</span></label>, tested in Chrome, Firefox 3.6, IE6, IE7, IE8
*/
label {
display: table;
*display: block;
*position: relative;
width:105px;
View more - Función para convertir una imágen a un arreglo de tipo byte y viceversa
Posted by layonman98 on Tue Feb 23 17:51:17 UTC 2010.
Language java
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class MainClass {
public static void main(String[] args){
try {
byteArrayToImage(imageToByteArray("E:\\c0.png"));
} catch (Exception e) {
View more - Reducir tamaño de imágen usando la clase System.Drawing.Graphics
Posted by layonman98 on Mon Feb 22 17:59:22 UTC 2010.
Language csharp
/* Función ReduceImg:
* Retorna un objeto de tipo Bitmap con al imágen enviada a través
* del parámetro img reducida al tamaño dado por los valores de
* los parámetros nWidth y nHeight.
*/
//using System;
//using System.Drawing;
View more - A Simple String to Date parser
Posted by xphree on Mon Feb 22 14:41:12 UTC 2010.
Language scala
class DateConverter(str:String) {
import java.util.Date
import java.text.SimpleDateFormat
def toDate() : Date = {
val sdf = new SimpleDateFormat("yyyyMMdd")
sdf.parse(str)
}
}
View more - Hello world
Posted by layonman98 on Sun Feb 21 00:24:57 UTC 2010.
Language csharp
using System;
public class Example{
public static void Main( string[] args ){
Console.WriteLine( "Hello, world!" );
}
}
View more - Generar archivos para MS Excel en CakePHP usando PHPExcel
Posted by andphe on Sat Feb 20 01:05:10 UTC 2010.
Language php
<?php
/**
* Esta vista genera al vuelo un archivo en formato MS Excel 2007
* restringiendo los valores que las columnas de los atributos
* pueden tomar.
*
* Requiere http://phpexcel.codeplex.com/ instalado la carpeta
* app/vendors
*
*/
View more - A static main
Posted by xphree on Fri Feb 19 22:22:39 UTC 2010.
Language java
class Main {
static {
System.out.println("Hello world");
}
}
View more - User entity
Posted by layonman98 on Fri Feb 19 22:20:45 UTC 2010.
Language sql
CREATE TABLE user(
user_id INT AUTO_INCREMENT,
user_name VARCHAR ( 16 ) NOT NULL,
user_age INT,
CONSTRAINT pk_user_id PRIMARY KEY ( user_id )
);