DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    <?php
$sql = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($a_db, $sql);

$m = new MongoClient($dbName);
$db = $m->$a_mongo_db;
$cols = $db->getCollectionNames();


// WATCH OUT!!!! Drops existing tables from MySql, 
foreach ($cols as $k => $v)
{
$drop = "DROP TABLE IF EXISTS $v";
$reply = mysql_query($drop, $sql);
}


foreach ($cols as $k => $v)
{
$c = $db->$v;
$r = $c->find();
$fields = array();
$fieldTypes = array();
foreach ($r as $rec)
{
foreach ($rec as $fname => $field)
{
$ftype = tgetType($field);
if ($fname == "synonyms")
{

}
else if ($ftype == "array")
{
foreach ($field as $subName => $sub_val)
if ($sub_val != null)
{
if ($subName == 'date')
{
$f2type = 'DATE';
}
else
$f2type = tgetType($sub_val);
if ($f2type == 'DATE')
$fieldTypes[$fname . '_' . $subName] = 'DATETIME';
else if ($f2type == "OBJECT")
$fieldTypes[$fname . '_' . $subName] = 'VARCHAR(255)';
else if ($f2type != "array")
$fieldTypes[$fname . '_' . $subName] = $f2type;
}
}
else if ($ftype == "OBJECT")
{
$fieldTypes[$fname] = 'VARCHAR(255)';
$fields[$fname] = true;
}
else if ($field != null)
{
$fieldTypes[$fname] = $ftype;
$fields[$fname] = true;
}
}
}
// create MySql tables
$createCmd = "create table $v (";
foreach ($fieldTypes as $name => $type)
{
$createCmd.="$name $type";
if ($name == '_id')
$createCmd.=" PRIMARY KEY,";
else
$createCmd.=',';
}
$createCmd = trim($createCmd, ',');
$createCmd.=")";
$out = mysql_query($createCmd);
if ($out == false)
echo $createCmd . "\n";

// inserting data
$r = $c->find();
foreach ($r as $rec)
{
$cmd = "insert into $v set ";
foreach ($rec as $fname => $field)
{
$ftype = tgetType($field);
if ($fname == "synonyms")
{

}
else if ($ftype == "array")
{
foreach ($field as $subName => $sub_val)
if ($sub_val != null)
{
if ($subName == 'date')
$f2type = 'DATE';
else
$f2type = tgetType($sub_val);

if ($f2type == "DATE")
{
$cmd.=$fname . "_$subName='$sub_val' ";
$cmd.=',';
}
else if ($f2type == "OBJECT")
{
$val = $sub_val->__toString();
$cmd.=$fname . "_$subName='$val' ";
$cmd.=',';
}
else if ($f2type != "array")
{
if ($f2type == "BIT" || $f2type == "INT")
$cmd.=$fname . "_$subName=$sub_val ";
else
{
$sub_val = remLetters($sub_val);
$cmd.=$fname . "_$subName='$sub_val' ";
}
$cmd.=',';
}
}
}
else if ($ftype == "OBJECT")
{
$val = $field->__toString();
$cmd.="$fname='$val' ";
$cmd.=',';
}
else if ($field != null)
{
if ($ftype == "BIT" || $ftype == "INT")
$cmd.="$fname=$field ";
else
{
$field = remLetters($field);
$cmd.="$fname='$field' ";
}
$cmd.=',';
}
}
$cmd = trim($cmd, ',');
$out = mysql_query($cmd);
if ($out == false)
echo 'SQL error:' . $cmd . "\n";
}
}


// Mapping from Mongo types to MySql types, feel free to change
function tgetType($field)
{
if (is_string($field))
return "TEXT";
else if (is_object($field))
return "OBJECT";
else if (is_bool($field))
return "BIT";
else if (is_int($field))
return "INT";
else if (is_object($field))
return "VARCHAR(255)";
else if (is_array($field))
{
return "array";
}
}

// this is done to avoid SQL errors, but it changes the strings, removing quotes and double quotes
function remLetters($s)
{
$remove[] = "'";
$remove[] = '"';

$out = str_replace($remove, " ", $s);
return $out;
}

                
                    -(IBAction)saveClick:(id)sender
{
    [self setViewEnabled:NO];
    
    [_loading startAnimating];
    [_animationTimer invalidate];
    
    [self animationResetValues];
    [self updateFaceElements];
    
    [_images removeAllObjects];
    [self getImage];
}                
                    //Code for Joining Multiple Documents Together

[C#]
 
// The document that the other documents will be appended to.
Document doc = new Document();
// We should call this method to clear this document of any existing content.
doc.RemoveAllChildren();

int recordCount = 5;
for (int i = 1; i <= recordCount; i++)
{
    // Open the document to join.
    Document srcDoc = new Document(@"C:\DetailsList.doc");

    // Append the source document at the end of the destination document.
    doc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles);

    // In automation you were required to insert a new section break at this point, however in Aspose.Words we
    // don't need to do anything here as the appended document is imported as separate sectons already.

    // If this is the second document or above being appended then unlink all headers footers in this section
    // from the headers and footers of the previous section.
    if (i > 1)
        doc.Sections[i].HeadersFooters.LinkToPrevious(false);
} 
 
[VB.NET]
 

' The document that the other documents will be appended to.
Dim doc As New Document()
' We should call this method to clear this document of any existing content.
doc.RemoveAllChildren()

Dim recordCount As Integer = 5
For i As Integer = 1 To recordCount
    ' Open the document to join.
    Dim srcDoc As New Document("C:\DetailsList.doc")

    ' Append the source document at the end of the destination document.
    doc.AppendDocument(srcDoc, ImportFormatMode.UseDestinationStyles)

    ' In automation you were required to insert a new section break at this point, however in Aspose.Words we
    ' don't need to do anything here as the appended document is imported as separate sectons already.

    ' If this is the second document or above being appended then unlink all headers footers in this section
    ' from the headers and footers of the previous section.
    If i > 1 Then
        doc.Sections(i).HeadersFooters.LinkToPrevious(False)
    End If
Next i
                
                    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
        <link type="text/css" rel="stylesheet" href="../themes/primefaces-bluesky/theme.css"/>
        <script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script> 
</h:head>
<h:body>
<p:gmap center="31.521118, 74.349375" zoom="15" type="terrain" style="width:600px;height:400px" />
</h:body>
</html>                
                       public function __construct()
  {
    $this->db = Zend_Db_Table::getDefaultAdapter();
    $this->db->getProfiler()->setEnabled(TRUE);
  }
  public function __destruct(){
    Zend_Debug::dump($this->db->getProfiler()->getQueryProfiles());
  }                
                    var def = function(functions, parent) {
 return function() {
    var types = [];
    var args = [];
    eachArg(arguments, function(i, elem) {
        args.push(elem);
        types.push(whatis(elem));
    });
    if(functions.hasOwnProperty(types.join())) {
        return functions[types.join()].apply(parent, args);
    } else {
        if (typeof functions === 'function')
            return functions.apply(parent, args);
        if (functions.hasOwnProperty('default'))
            return functions['default'].apply(parent, args);        
    }
  };
};

var eachArg = function(args, fn) {
 var i = 0;
 while (args.hasOwnProperty(i)) {
    if(fn !== undefined)
        fn(i, args[i]);
    i++;
 }
 return i-1;
};

var whatis = function(val) {

 if(val === undefined)
    return 'undefined';
 if(val === null)
    return 'null';

 var type = typeof val;

 if(type === 'object') {
    if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
        return 'array';
    if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
        return 'date';
    if(val.hasOwnProperty('toExponential'))
        type = 'number';
    if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
        return 'string';
 }

 if(type === 'number') {
    if(val.toString().indexOf('.') > 0)
        return 'float';
    else
        return 'int';
 }

 return type;
};

var out = def({
    'int': function(a) {
        alert('Here is int '+a);
    },

    'float': function(a) {
        alert('Here is float '+a);
    },

    'string': function(a) {
        alert('Here is string '+a);
    },

    'int,string': function(a, b) {
        alert('Here is an int '+a+' and a string '+b);
    },
    'default': function(obj) {
        alert('Here is some other value '+ obj);
    }

});

out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);                
                     private WebAuthorizer auth;
        private TwitterContext twitterCtx;

        protected void Page_Load(object sender, EventArgs e)
        {
            IOAuthCredentials credentials = new SessionStateCredentials();

            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
            {
                credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
                credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
            }

            auth = new WebAuthorizer
            {
                Credentials = credentials,
                PerformRedirect = authUrl => Response.Redirect(authUrl)
            };

            if (!Page.IsPostBack && Request.QueryString["oauth_token"] != null)
            {
                auth.CompleteAuthorization(Request.Url);
            }

            if (string.IsNullOrWhiteSpace(credentials.ConsumerKey) ||
                string.IsNullOrWhiteSpace(credentials.ConsumerSecret))
            {
             //Do nothing
            }
            else if (auth.IsAuthorized)
            {
             //Do nothing
            }
            else
            {
                auth.BeginAuthorization(Request.Url);

                if (!auth.IsAuthorized)
                {
                    Uri specialUri = new Uri(Request.Url.ToString());
                    auth.BeginAuthorization(specialUri);
                }
            }

            if (auth.IsAuthorized)
            {
                twitterCtx = new TwitterContext(auth);

               #region Search Text
                var searchResult =
                    (from srch in twitterCtx.Search
                     where srch.Type == SearchType.Search &&
                           srch.Query == "Brian Adams"
                     select srch)
                    .SingleOrDefault();
                gvTweetView.DataSource = searchResult.Statuses;
                gvTweetView.DataBind();
	            #endregion

                #region UserInfo
                var users =
                               (from user in twitterCtx.User
                                where user.Type == UserType.Lookup &&
                                      user.ScreenName == "prosarfraz"
                                select user);

                string strHtml = string.Empty;


                foreach (User objUser in users)
                {

                    strHtml += "<TR>";
                    strHtml += "<TD> Screen Name </TD>";
                    strHtml += "<TD>" + objUser.ScreenName + "</TD>";
                    strHtml += "<TD> Favorites Count </TD>";
                    strHtml += "<TD>" + objUser.FavoritesCount + "</TD>";
                    strHtml += "<TD> Followers </TD>";
                    strHtml += "<TD>" + objUser.FollowersCount + "</TD>";
                    strHtml += "<TD> Description </TD>";
                    strHtml += "<TD>" + objUser.Description + "</TD>";
                    strHtml += "</TR>";

                }
                ulsrc.InnerHtml = "<Table border ='1'>" + strHtml + "</Table>"; 
                #endregion
         
            }
        }                
                    Hello.
I need some help...
I`ve created an eight question form with radio buttoms and checkboxes, and after you`ll answer to all of these questions you should see your final result. 
Well, the first 4 question were created wuth radio buttoms and works very fine but the last 4 that are created with checkboxes didn`t work. when I has to choose more than one answer, the browser didn`t recognize me all of the options that I`ve selected from the checkboxes.

Please help me.                
                    [C#]
 
// read code39 barcode from image
string image = "code39Extended.jpg";
BarCodeReader reader = new BarCodeReader(image, BarCodeReadType.Code39Standard);
// try to recognize all possible barcodes in the image
while (reader.Read()) {
   // get the region information
    BarCodeRegion region = reader.GetRegion();
    if (region != null)
    {
        // display x and y coordinates of barcode detected
        System.Drawing.Point[] point = region.Points;
        Console.WriteLine("Top left coordinates: X = " + point[0].X + ", Y = " + point[0].Y);
        Console.WriteLine("Bottom left coordinates: X = " + point[1].X + ", Y = " + point[1].Y);
        Console.WriteLine("Bottom right coordinates: X = " + point[2].X + ", Y = " + point[2].Y);
        Console.WriteLine("Top right coordinates: X = " + point[3].X + ", Y = " + point[3].Y);
    }
    Console.WriteLine("Codetext: " + reader.GetCodeText());
}
// close reader
reader.Close();


[VB.NET]

 ' read code39 barcode from image
Dim image As String = "code39Extended.jpg"
Dim reader As New BarCodeReader(image, BarCodeReadType.Code39Standard)
' try to recognize all possible barcodes in the image
While reader.Read()
	' get the region information
	Dim region As BarCodeRegion = reader.GetRegion()
	If region IsNot Nothing Then
		' display x and y coordinates of barcode detected
		Dim point As System.Drawing.Point() = region.Points
		Console.WriteLine("Top left coordinates: X = " & point(0).X & ", Y = " & point(0).Y)
		Console.WriteLine("Bottom left coordinates: X = " & point(1).X & ", Y = " & point(1).Y)
		Console.WriteLine("Bottom right coordinates: X = " & point(2).X & ", Y = " & point(2).Y)
		Console.WriteLine("Top right coordinates: X = " & point(3).X & ", Y = " & point(3).Y)
	End If
	Console.WriteLine("Codetext: " & reader.GetCodeText())
End While
' close reader
reader.Close()
                
                    //build URI to upload file
            string fileUploadUri = "http://api.saaspose.com/v1.0/storage/file/test.jpg";
            string UploadUrl = Sign(fileUploadUri);
            // Send request to upload file
            UploadFileBinary("c:\\temp\\test.jpg", UploadUrl, "PUT");

            //build URI to read barcode
            string strURI = "http://api.saaspose.com/v1.0/barcode/test.jpg/recognize?type=AllSupportedTypes";
            // Send the request to Saaspose server
            Stream responseStream = ProcessCommand(Sign(strURI), "GET");
            StreamReader reader = new StreamReader(responseStream);
            // Read the response
            string strJSON = reader.ReadToEnd();
            //Parse the json string to JObject
            JObject parsedJSON = JObject.Parse(strJSON);
            //Deserializes the JSON to a object. 
            RecognitionResponse barcodeRecognitionResponse = JsonConvert.DeserializeObject<RecognitionResponse>(parsedJSON.ToString());
            // Display the value and type of all the recognized barcodes
            foreach (RecognizedBarCode barcode in barcodeRecognitionResponse.Barcodes)
            {
                Console.WriteLine("Codetext: " + barcode.BarCodeValue + "\nType: " + barcode.BarCodeType);
            }

	    \\Here is the RecognitionResponse class
	    public class RecognitionResponse : BaseResponse
    	    {
        	public List<RecognizedBarCode> Barcodes { get; set; }
    	    }

	    \\Here is the RecognizedBarCode class	    
	    public class RecognizedBarCode
    	    {
        	public string BarCodeType { get; set; }
        	public string BarCodeValue { get; set; }
    	    }

	    \\Here is the BaseResponse class	    
	    public class BaseResponse
    	    {
        	public BaseResponse() { }
        	public string Code { get; set; }
        	public string Status { get; set; }
    	    }