Programs & Examples On #Cocoahttpserver

CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications.

How to avoid precompiled headers

You can always disable the use of pre-compiled headers in the project settings.

Instructions for VS 2010 (should be similar for other versions of VS):

Select your project, use the "Project -> Properties" menu and go to the "Configuration Properties -> C/C++ -> Precompiled Headers" section, then change the "Precompiled Header" setting to "Not Using Precompiled Headers" option.


If you are only trying to setup a minimal Visual Studio project for simple C++ command-line programs (such as those developed in introductory C++ programming classes), you can create an empty C++ project.

How to make an autocomplete TextBox in ASP.NET?

aspx Page Coding

<form id="form1" runat="server">
       <input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
                    required="">
       <datalist id="datalist1" runat="server">

       </datalist>
 </form>

.cs Page Coding

protected void Page_Load(object sender, EventArgs e)
{
     autocomplete();
}
protected void autocomplete()
{
    Database p = new Database();
    DataSet ds = new DataSet();
    ds = p.sqlcall("select [name] from [stu_reg]");
    int row = ds.Tables[0].Rows.Count;
    string abc="";
    for (int i = 0; i < row;i++ )
        abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
    datalist1.InnerHtml = abc;
}

Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();
        MessageBox.Show(sResult);
    }

And you're done. enter image description here

sql server invalid object name - but tables are listed in SSMS tables list

Even after installing SP3 to SQL Server 2008 Enterprise this is still an "issue." Ctrl+Shift+R like everyone has been saying solved this problem for me.

Generating random number between 1 and 10 in Bash Shell Script

To generate in the range: {0,..,9}

r=$(( $RANDOM % 10 )); echo $r

To generate in the range: {40,..,49}

r=$(( $RANDOM % 10 + 40 )); echo $r

Removing duplicates from a String in Java

String str1[] ="Hi helloo helloo  oooo this".split(" "); 

Set<String> charSet = new LinkedHashSet<String>();
for (String c: str1) 
{
       charSet.add(c); 
}
StringBuilder sb = new StringBuilder(); 
for (String character : charSet) 
{
       sb.append(character); 
}

System.out.println(sb.toString());

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

Delete everything in a MongoDB database

  1. List out all available dbs show dbs
  2. Choose the necessary db use
  3. Drop the database db.dropDatabase() //Few additional commands
  4. List all collections available in a db show collections
  5. Remove a specification collection db.collection.drop()

Hope that helps

How do I check if a string is valid JSON in Python?

I came up with an generic, interesting solution to this problem:

class SafeInvocator(object):
    def __init__(self, module):
        self._module = module

    def _safe(self, func):
        def inner(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                return None

        return inner

    def __getattr__(self, item):
        obj = getattr(self.module, item)
        return self._safe(obj) if hasattr(obj, '__call__') else obj

and you can use it like so:

safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
    # do something

FileProvider - IllegalArgumentException: Failed to find configured root

I am sure I am late to the party but below worked for me.

<paths>
    <root-path name="root" path="." />
</paths>

How do I select an element that has a certain class?

The CSS :first-child selector allows you to target an element that is the first child element within its parent.

element:first-child { style_properties }
table:first-child { style_properties }

What is the iPhone 4 user-agent?

You can use:

http://whatsmyuseragent.com/

To find your user agent (Google: "What is my user agent" gives this answer)

Eclipse will not open due to environment variables

You should install both 32bit & 64bit java (At least JRE), that in case you're using 64bit OS.

Defining a variable with or without export

Although not explicitly mentioned in the discussion, it is NOT necessary to use export when spawning a subshell from inside bash since all the variables are copied into the child process.

How to calculate mean, median, mode and range from a set of numbers

If you only care about unimodal distributions, consider sth. like this.

public static Optional<Integer> mode(Stream<Integer> stream) {
    Map<Integer, Long> frequencies = stream
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    return frequencies.entrySet().stream()
        .max(Comparator.comparingLong(Map.Entry::getValue))
        .map(Map.Entry::getKey);
}

How to allow user to pick the image with Swift?

Just answering here to mention: info[UIImagePickerControllerEditedImage] is probably the one you want to use in most cases.

Other than that, the answers here are comprehensive.

How to access SVG elements with Javascript

In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {

    //alert("Document loaded, including graphics and embedded documents (like SVG)");
    var a = document.getElementById("alphasvg");

    //get the inner DOM of alpha.svg
    var svgDoc = a.contentDocument;

    //get the inner element by id
    var delta = svgDoc.getElementById("delta");
    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});

iterating through json object javascript

You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:

var obj = {a: 1, b: 2};
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}

Or if you need recursion to walk through all the properties:

var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      var val = obj[key];
      console.log(val);
      walk(val);
    }
  }
}
walk(obj);

End-line characters from lines read from text file, using Python

You may also consider using line.rstrip() to remove the whitespaces at the end of your line.

Which loop is faster, while or for?

I used a for and while loop on a solid test machine (no non-standard 3rd party background processes running). I ran a for loop vs while loop as it relates to changing the style property of 10,000 <button> nodes.

The test is was run consecutively 10 times, with 1 run timed out for 1500 milliseconds before execution:

Here is the very simple javascript I made for this purpose

function runPerfTest() {
    "use strict";

    function perfTest(fn, ns) {
        console.time(ns);
        fn();
        console.timeEnd(ns);
    }

    var target = document.getElementsByTagName('button');

    function whileDisplayNone() {
        var x = 0;
        while (target.length > x) {
            target[x].style.display = 'none';
            x++;
        }
    }

    function forLoopDisplayNone() {
        for (var i = 0; i < target.length; i++) {
            target[i].style.display = 'none';
        }
    }

    function reset() {
        for (var i = 0; i < target.length; i++) {
            target[i].style.display = 'inline-block';
        }
    }

    perfTest(function() {
        whileDisplayNone();
    }, 'whileDisplayNone');

    reset();

    perfTest(function() {
        forLoopDisplayNone();
    }, 'forLoopDisplayNone');

    reset();
};

$(function(){
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    setTimeout(function(){
        console.log('cool run');
        runPerfTest();
    }, 1500);
});

Here are the results I got

pen.js:8 whileDisplayNone: 36.987ms
pen.js:8 forLoopDisplayNone: 20.825ms

pen.js:8 whileDisplayNone: 19.072ms
pen.js:8 forLoopDisplayNone: 25.701ms

pen.js:8 whileDisplayNone: 21.534ms
pen.js:8 forLoopDisplayNone: 22.570ms

pen.js:8 whileDisplayNone: 16.339ms
pen.js:8 forLoopDisplayNone: 21.083ms

pen.js:8 whileDisplayNone: 16.971ms
pen.js:8 forLoopDisplayNone: 16.394ms

pen.js:8 whileDisplayNone: 15.734ms
pen.js:8 forLoopDisplayNone: 21.363ms

pen.js:8 whileDisplayNone: 18.682ms
pen.js:8 forLoopDisplayNone: 18.206ms

pen.js:8 whileDisplayNone: 19.371ms
pen.js:8 forLoopDisplayNone: 17.401ms

pen.js:8 whileDisplayNone: 26.123ms
pen.js:8 forLoopDisplayNone: 19.004ms

pen.js:61 cool run
pen.js:8 whileDisplayNone: 20.315ms
pen.js:8 forLoopDisplayNone: 17.462ms

Here is the demo link

Update

A separate test I have conducted is located below, which implements 2 differently written factorial algorithms, 1 using a for loop, the other using a while loop.

Here is the code:

function runPerfTest() {
    "use strict";

    function perfTest(fn, ns) {
        console.time(ns);
        fn();
        console.timeEnd(ns);
    }

    function whileFactorial(num) {
        if (num < 0) {
            return -1;
        }
        else if (num === 0) {
            return 1;
        }
        var factl = num;
        while (num-- > 2) {
            factl *= num;
        }
        return factl;
    }

    function forFactorial(num) {
        var factl = 1;
        for (var cur = 1; cur <= num; cur++) {
            factl *= cur;
        }
        return factl;
    }

    perfTest(function(){
        console.log('Result (100000):'+forFactorial(80));
    }, 'forFactorial100');

    perfTest(function(){
        console.log('Result (100000):'+whileFactorial(80));
    }, 'whileFactorial100');
};

(function(){
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    runPerfTest();
    console.log('cold run @1500ms timeout:');
    setTimeout(runPerfTest, 1500);
})();

And the results for the factorial benchmark:

pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.280ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.241ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.254ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.254ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.285ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.294ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.181ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.172ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.195ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.279ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.185ms
pen.js:55 cold run @1500ms timeout:
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.404ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.314ms

Conclusion: No matter the sample size or specific task type tested, there is no clear winner in terms of performance between a while and for loop. Testing done on a MacAir with OS X Mavericks on Chrome evergreen.

How to remove a variable from a PHP session array

Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:

$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?> 

So, unset has no effect to internal array counter!!!

http://us.php.net/unset

jQuery Validate Required Select

use min rule

set first option value to 0

'selectName':{min:1}

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Change color when hover a font awesome icon?

use - !important - to override default black

_x000D_
_x000D_
.fa-heart:hover{_x000D_
   color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
   color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
_x000D_
_x000D_

Working with dictionaries/lists in R

You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.

For both lists and vectors, an individual element can be subsetted by name:

> foo["tac"]
tac 
 22 

Or for a list:

> foo[["tac"]]
[1] 22

Detect when an image fails to load in Javascript

You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.

function testImage(URL) {
    var tester=new Image();
    tester.onload=imageFound;
    tester.onerror=imageNotFound;
    tester.src=URL;
}

function imageFound() {
    alert('That image is found and loaded');
}

function imageNotFound() {
    alert('That image was not found.');
}

testImage("http://foo.com/bar.jpg");

And my sympathies for the jQuery-resistant boss!

How to migrate GIT repository from one server to a new one

Should be as simple as:

git remote set-url origin git://new.url.here

This way you keep the name origin for your new repo - then push to the new repo the old one as detailed in the other answers. Supposing you work alone and you have a local repo you want to mirror with all your cruft in it, you might as well (from inside your local repo)

git push origin --mirror # origin points to your new repo

but see Is "git push --mirror" sufficient for backing up my repository? (in all don't use --mirror but once).

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You could create a function that reads an integer between 1 and 23 or returns 0 if non-int

e.g.

int getInt()
{
  int n = 0;
  char buffer[128];
  fgets(buffer,sizeof(buffer),stdin);
  n = atoi(buffer); 
  return ( n > 23 || n < 1 ) ? 0 : n;
}

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

Django - Did you forget to register or load this tag?

The app that contains the custom tags must be in INSTALLED_APPS. So Are you sure that your directory is in INSTALLED_APPS ?

From the documentation:

The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.

Add params to given URL in Python

In python 2.5

import cgi
import urllib
import urlparse

def add_url_param(url, **params):
    n=3
    parts = list(urlparse.urlsplit(url))
    d = dict(cgi.parse_qsl(parts[n])) # use cgi.parse_qs for list values
    d.update(params)
    parts[n]=urllib.urlencode(d)
    return urlparse.urlunsplit(parts)

url = "http://stackoverflow.com/search?q=question"
add_url_param(url, lang='en') == "http://stackoverflow.com/search?q=question&lang=en"

List of all index & index columns in SQL Server DB

based on Tim Ford code, this is the right answer:

  select tab.[name]  as [table_name],
         idx.[name]  as [index_name],
         allc.[name] as [column_name],
         idx.[type_desc],
         idx.[is_unique],
         idx.[data_space_id],
         idx.[ignore_dup_key],
         idx.[is_primary_key],
         idx.[is_unique_constraint],
         idx.[fill_factor],
         idx.[is_padded],
         idx.[is_disabled],
         idx.[is_hypothetical],
         idx.[allow_row_locks],
         idx.[allow_page_locks],
         idxc.[is_descending_key],
         idxc.[is_included_column],
         idxc.[index_column_id]

     from sys.[tables] as tab

    inner join sys.[indexes]       idx  on tab.[object_id] =  idx.[object_id]
    inner join sys.[index_columns] idxc on idx.[object_id] = idxc.[object_id] and  idx.[index_id]  = idxc.[index_id]
    inner join sys.[all_columns]   allc on tab.[object_id] = allc.[object_id] and idxc.[column_id] = allc.[column_id]

    where tab.[name] Like '%table_name%'
      and idx.[name] Like '%index_name%'
    order by tab.[name], idx.[index_id], idxc.[index_column_id]

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

How to run a task when variable is undefined in ansible?

From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:

tasks:

- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  when: foo is defined

- fail: msg="Bailing out. this play requires 'bar'"
  when: bar is not defined

So in your case, when: deployed_revision is not defined should work

What does "TypeError 'xxx' object is not callable" means?

I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:

class DOH(object):
def __init__(self, property=None):
    self.property=property

def property():
    return property

x = DOH(1)
print(x.property())

Results

$ python3 t.py
Traceback (most recent call last):
  File "t.py", line 9, in <module>
    print(x.property())
TypeError: 'int' object is not callable

The problem here of course is that the function is overwritten with a property.

How do you create a daemon in Python?

This function will transform an application to a daemon:

import sys
import os

def daemonize():
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError as err:
        sys.stderr.write('_Fork #1 failed: {0}\n'.format(err))
        sys.exit(1)
    # decouple from parent environment
    os.chdir('/')
    os.setsid()
    os.umask(0)
    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent
            sys.exit(0)
    except OSError as err:
        sys.stderr.write('_Fork #2 failed: {0}\n'.format(err))
        sys.exit(1)
    # redirect standard file descriptors
    sys.stdout.flush()
    sys.stderr.flush()
    si = open(os.devnull, 'r')
    so = open(os.devnull, 'w')
    se = open(os.devnull, 'w')
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

How to create localhost database using mysql?

removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

How to remove spaces from a string using JavaScript?

_x000D_
_x000D_
var a = b = " /var/www/site/Brand new   document.docx ";_x000D_
_x000D_
console.log( a.split(' ').join('') );_x000D_
console.log( b.replace( /\s/g, '') ); 
_x000D_
_x000D_
_x000D_

Two ways of doing this!

What does the keyword Set actually do in VBA?

set is used to assign a reference to an object. The C equivalent would be

 int i;
int* ref_i;

i = 4; // Assigning a value (in VBA: i = 4)
ref_i = &i; //assigning a reference (in VBA: set ref_i = i)

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

MAVEN_HOME, MVN_HOME or M2_HOME

Here is my Maven setup. You can use it as an example. You don't need anything else in order to use Maven.

M2_HOME is used for both Maven 2 and 3

export M2_HOME=/Users/xxx/sdk/apache-maven-3.0.5
export M2=$M2_HOME/bin
export MAVEN_OPTS="-Xmx1048m -Xms256m -XX:MaxPermSize=312M"
export PATH=$M2:$PATH

Python method for reading keypress?

See the MSDN getch docs. Specifically:

The _getch and_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

The Python function returns a character. you can use ord() to get an integer value you can test, for example keycode = ord(msvcrt.getch()).

So if you read an 0x00 or 0xE0, read it a second time to get the key code for an arrow or function key. From experimentation, 0x00 precedes F1-F10 (0x3B-0x44) and 0xE0 precedes arrow keys and Ins/Del/Home/End/PageUp/PageDown.

How to use Visual Studio Code as Default Editor for Git

Good news! At the time of writing, this feature has already been implemented in the 0.10.12-insiders release and carried out through 0.10.14-insiders. Hence we are going to have it in the upcoming version 1.0 Release of VS Code.

Implementation Ref: Implement -w/--wait command line arg

There is an error in XML document (1, 41)

In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

Retrieve only the queried element in an object array in MongoDB collection

The syntax for find in mongodb is

    db.<collection name>.find(query, projection);

and the second query that you have written, that is

    db.test.find(
    {shapes: {"$elemMatch": {color: "red"}}}, 
    {"shapes.color":1})

in this you have used the $elemMatch operator in query part, whereas if you use this operator in the projection part then you will get the desired result. You can write down your query as

     db.users.find(
     {"shapes.color":"red"},
     {_id:0, shapes: {$elemMatch : {color: "red"}}})

This will give you the desired result.

How to view file history in Git?

Use git log to view the commit history. Each commit has an associated revision specifier that is a hash key (e.g. 14b8d0982044b0c49f7a855e396206ee65c0e787 and b410ad4619d296f9d37f0db3d0ff5b9066838b39). To view the difference between two different commits, use git diff with the first few characters of the revision specifiers of both commits, like so:

# diff between commits 14b8... and b410...
git diff 14b8..b410
# only include diff of specified files
git diff 14b8..b410 path/to/file/a path/to/file/b

If you want to get an overview over all the differences that happened from commit to commit, use git log or git whatchanged with the patch option:

# include patch displays in the commit history
git log -p
git whatchanged -p
# only get history of those commits that touch specified paths
git log path/a path/b
git whatchanged path/c path/d

How to switch to another domain and get-aduser

best solution TNX to Drew Chapin and all of you too:

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

my script:

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
 Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } `  -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

In my case, I needed to deploy two Qt apps on an Ubuntu virtualbox guest. One was command-line ("app"), the other GUI_based ("app_GUI").

I used "ldd app" to find out what the required libs are, and copied them to the Ubuntu guest. While the command-line executable "app" worked ok, the GUI-based executable crashed, giving the "Failed to load platform plugin "xcb" error. I checked ldd for libxcb.so, but this too had no missing dependencies.

The problem seemed to be that while I did copy all the right libraries I accidentally had copied also libraries that were already present at the guest system.. meaning that (a) they were unnecessary to copy them in the first place and (b) worse, copying them produced incompatibilities between the install libraries. Worse still, they were undetectable by ldd like I said..

The solution? Make sure that you copy libraries shown as missing by ldd and absolutely no extra libraries.

"Object doesn't support this property or method" error in IE11

What fixed this for me was that I had a React component being rendered prior to my core.js shim being loaded.

import ReactComponent from '.'
import 'core-js/es6'

Loading the core-js prior to the ReactComponent fixed my issue

import 'core-js/es6'
import ReactComponent from '.'

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

React eslint error missing in props validation

For me, upgrading eslint-plugin-react to the latest version 7.21.5 fixed this

How to click an element in Selenium WebDriver using JavaScript

By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.

WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);

Bootstrap 3 select input form inline

Can be done with pure Bootstrap code.

_x000D_
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
  <label for="id" class="col-md-2 control-label">ID</label>_x000D_
  <div class="input-group">_x000D_
    <span class="input-group-btn">_x000D_
      <select class="form-control" name="id" id="id">_x000D_
        <option value="">_x000D_
      </select>_x000D_
    </span>_x000D_
    <span class="input-group-btn">_x000D_
      <select class="form-control" name="nr" id="nr">_x000D_
        <option value="">_x000D_
      </select>_x000D_
    </span>_x000D_
  </div> _x000D_
</div> 
_x000D_
_x000D_
_x000D_

How to display an image from a path in asp.net MVC 4 and Razor view?

Try this ,

<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>

(or)

<img src="~/Content/img/@Url.Content(model =>model.ImagePath)" style="height:50px;width:100px;"/>

MySQL set current date in a DATETIME field on insert

Since MySQL 5.6.X you can do this:

ALTER TABLE `schema`.`users` 
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;

That way your column will be updated with the current timestamp when a new row is inserted, or updated.

If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP in the DEFAULT value field, like so:

enter image description here

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

Node.js global variables

Use a global namespace like global.MYAPI = {}:

global.MYAPI._ = require('underscore')

All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.

Tip: Development Using Namespaces

What is an NP-complete in computer science?

The definitions for NP complete problems above is correct, but I thought I might wax lyrical about their philosophical importance as nobody has addressed that issue yet.

Almost all complex problems you'll come up against will be NP Complete. There's something very fundamental about this class, and which just seems to be computationally different from easily solvable problems. They sort of have their own flavour, and it's not so hard to recognise them. This basically means that any moderately complex algorithm is impossible for you to solve exactly -- scheduling, optimising, packing, covering etc.

But not all is lost if a problem you'll encounter is NP Complete. There is a vast and very technical field where people study approximation algorithms, which will give you guarantees for being close to the solution of an NP complete problem. Some of these are incredibly strong guarantees -- for example, for 3sat, you can get a 7/8 guarantee through a really obvious algorithm. Even better, in reality, there are some very strong heuristics, which excel at giving great answers (but no guarantees!) for these problems.

Note that two very famous problems -- graph isomorphism and factoring -- are not known to be P or NP.

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

List of strings to one string

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

Typescript empty object for a typed variable

Note that using const user = {} as UserType just provides intellisense but at runtime user is empty object {} and has no property inside. that means user.Email will give undefined instead of ""

type UserType = {
    Username: string;
    Email: string;
}

So, use class with constructor for actually creating objects with default properties.

type UserType = {
  Username: string;
  Email: string;
};

class User implements UserType {
  constructor() {
    this.Username = "";
    this.Email = "";
  }

  Username: string;
  Email: string;
}

const myUser = new User();
console.log(myUser); // output: {Username: "", Email: ""}
console.log("val: "+myUser.Email); // output: ""

You can also use interface instead of type

interface UserType {
  Username: string;
  Email: string;
};

...and rest of code remains same.


Actually, you can even skip the constructor part and use it like this:

class User implements UserType {
      Username = ""; // will be added to new obj
      Email: string; // will not be added
}

const myUser = new User();
console.log(myUser); // output: {Username: ""}

tmux set -g mouse-mode on doesn't work

Just a quick heads-up to anyone else who is losing their mind right now:

https://github.com/tmux/tmux/blob/310f0a960ca64fa3809545badc629c0c166c6cd2/CHANGES#L12

so that's just

 :setw -g mouse

Make EditText ReadOnly

This worked for me, taking several of the suggestions above into account. Makes the TextEdit focusable, but if user clicks or focuses, we show a list of selections in a PopupWindow. (We are replacing the wacky Spinner widget). TextEdit xml is very generic...

public void onCreate(Bundle savedInstanceState) {
    ....  
    fEditState = (EditText) findViewById(R.id.state_edit);

    fEditState.setLongClickable(false);
    fEditState.setKeyListener(null);
    fEditState.setFocusable(true);

    fEditState.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus)
        {
            if (hasFocus)
            {
               showStatesPopup();

            }
        }
    });

    fEditState.setOnClickListener(new Button.OnClickListener(){

        public void onClick(View arg0)
        {
           showStatesPopup();
        }
    });
    ....
}

private void showStatesPopup()
{
    // fPopupWindowStates instantiated in OnCreate()

    if (!fPopupWindowStates.isShowing()) {
        // show the list view as dropdown
        fPopupWindowStates.showAsDropDown(fEditState, -5, 0);
    }
}  

Android : How to read file in bytes?

Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:

byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}

NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

Source: http://msdn.microsoft.com/en-us/library/ms189499%28v=sql.110%29.aspx

Python integer incrementing with ++

Here there is an explanation: http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python

However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.

In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

Flutter Circle Design

you can use decoration like this :

   Container(
                    width: 60,
                    height: 60,
                    child: Icon(CustomIcons.option, size: 20,),
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFFe0f2f1)),
                  )

Now you have circle shape and Icon on it.

enter image description here

AngularJS passing data to $http.get request

An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.

angular.http provides an option for it called params.

$http({
    url: user.details_path, 
    method: "GET",
    params: {user_id: user.id}
 });

See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params param)

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

Code line wrapping - how to handle long lines

This is how I do it, and Google does it my way.

  • Break before the symbol for non-assignment operators.
  • Break after the symbol for = and for ,.

In your case, since you're using 120 characters, you can break it after the assignment operator resulting in

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

In Java, and for this particular case, I would give two tabs (or eight spaces) after the break, depending on whether tabs or spaces are used for indentation.

This is of course a personal preference and if your project has its own convention for line-wrapping then that is what you should follow whether you like it or not.

Error "The connection to adb is down, and a severe error has occurred."

I've deleted all my tasks from HTC task manager and now it's working.

Among $_REQUEST, $_GET and $_POST which one is the fastest?

I only ever use _GET or _POST. I prefer to have control.

What I don't like about either code fragment in the OP is that they discard the information on which HTTP method was used. And that information is important for input sanitization.

For example, if a script accepts data from a form that's going to be entered into the DB then the form had better use POST (use GET only for idempotent actions). But if the script receives the input data via the GET method then it should (normally) be rejected. For me, such a situation might warrant writing a security violation to the error log since it's a sign somebody is trying something on.

With either code fragment in the OP, this sanitization wouldn't be possible.

C# Linq Where Date Between 2 Dates

If someone interested to know how to work with 2 list and between dates

var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

Difference between string and StringBuilder in C#

Also the complexity of concatenations of String is O(N2), while for StringBuffer it is O(N).

So there might be performance problem where we use concatenations in loops as a lot of new objects are created each time.

Drop Down Menu/Text Field in one

I found this question and discussion very helpful and wanted to show the solution I ended up with. It is based on the answer given by @DevangRathod, but I used jQuery and made a couple tweaks to it, so wanted to show a fully commented sample to help anyone else working on something similar. I originally had been using the HTML5 data-list element, but was dissatisfied with that solution since it removes options from the drop down list that don't match text typed in the box. In my application, I wanted the full list to always be available.

Fully functional demo here: https://jsfiddle.net/abru77mm/

HTML:

<!-- 
Most style elements I left to the CSS file, but some are here.
Reason being that I am actually calculating my width dynamically
in my application so when I dynamically formulate this HTML, I
want the width and all the factors (such as padding and border
width and margin) that go into determining the proper widths to
be controlled by one piece of code, so those pieces are done in
the in-line style.  Otherwise I leave the styling to the CSS file.
-->
<div class="data-list-input" style="width:190px;">
  <select class="data-list-input" style="width:190px;">
    <option value="">&lt;Free Form Text&gt;</option>
    <option value="Male">Male</option>
    <option value="Female">Female</option>
    <!-- Note that though the select/option allows for a different
    display and internal value, there is no such distinction in the
    text box, so for all the options (except the "none" option) the
    value and content of the option should be identical. -->
  </select>
  <input class="data-list-input" style="width:160px;padding:4px 6px;border-width:1px;margin:0;" type="text" name="sex" required="required" value="">
</div>

JS:

jQuery(function() {
  //keep the focus on the input box so that the highlighting
  //I'm using doesn't give away the hidden select box to the user
  $('select.data-list-input').focus(function() {
    $(this).siblings('input.data-list-input').focus();
  });
  //when selecting from the select box, put the value in the input box
  $('select.data-list-input').change(function() {
    $(this).siblings('input.data-list-input').val($(this).val());
  });
  //When editing the input box, reset the select box setting to "free
  //form input". This is important to do so that you can reselect the
  //option you had selected if you want to.
  $('input.data-list-input').change(function() {
    $(this).siblings('select.data-list-input').val('');
  });
});

CSS:

div.data-list-input
{
    position: relative;
    height: 20px;
    display: inline-flex;
    padding: 5px 0 5px 0;
}
select.data-list-input
{
    position: absolute;
    top: 5px;
    left: 0px;
    height: 20px;
}
input.data-list-input
{
    position: absolute;
    top: 0px;
    left: 0px;
    height: 20px;
}

Any comments for improvement on my implementation welcome. Hope someone finds this helpful.

assignment operator overloading in c++

The second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c; resolve as expected. I can't think of any cases where I would want to return a copy from assignment.

One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...

Edit:

Here's some basic calls:

SimpleCircle x; // default constructor
SimpleCircle y(x); // copy constructor
x = y; // assignment operator

Now say we had the first version of your assignment operator:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this; // calls copy constructor SimpleCircle(*this)
     itsRadius = rhs.getRadius(); // copy member
     return *this; // calls copy constructor
}

It calls the copy constructor and passes a reference to this in order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this; // return reference to this (no copy)
    itsRadius = rhs.getRadius(); // copy member
    return *this; // return reference to this (no copy)
}

How do I programmatically change file permissions?

for Oralce Java 6:

private static int chmod(String filename, int mode) {
    try {
        Class<?> fspClass = Class.forName("java.util.prefs.FileSystemPreferences");
        Method chmodMethod = fspClass.getDeclaredMethod("chmod", String.class, Integer.TYPE);
        chmodMethod.setAccessible(true);
        return (Integer)chmodMethod.invoke(null, filename, mode);
    } catch (Throwable ex) {
        return -1;
    }
}

works under solaris/linux.

Preloading images with JavaScript

This approach is a little more elaborate. Here you store all preloaded images in a container, may be a div. And after you could show the images or move it within the DOM to the correct position.

function preloadImg(containerId, imgUrl, imageId) {
    var i = document.createElement('img'); // or new Image()
    i.id = imageId;
    i.onload = function() {
         var container = document.getElementById(containerId);
         container.appendChild(this);
    };
    i.src = imgUrl;
}

Try it here, I have also added few comments

Starting Docker as Daemon on Ubuntu

I had the same problem, and it was caused by line for insecured registry in: /etc/default/docker

How to export dataGridView data Instantly to Excel on button click?

I did not intend to steal @Jake and @Cornelius's answer, so i tried editing it. but it was rejected. Anyways, the only improvement I have to point out is about avoiding extra blank column in excel after paste. Adding one line dataGridView1.RowHeadersVisible = false; hides so called "Row Header" which appears on the left most part of DataGridView, and so it is not selected and copied to clipboard when you do dataGridView1.SelectAll();

private void copyAlltoClipboard()
    {
        //to remove the first blank column from datagridview
        dataGridView1.RowHeadersVisible = false;
        dataGridView1.SelectAll();
        DataObject dataObj = dataGridView1.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }
    private void button3_Click_1(object sender, EventArgs e)
    {
        copyAlltoClipboard();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);          
    }

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

Please set your form action attribute as below it will solve your problem.

<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">

jQuery code:

$(document).ready(function () {
    $("#addProductForm").submit(function (event) {

        //disable the default form submission
        event.preventDefault();
        //grab all form data  
        var formData = $(this).serialize();

        $.ajax({
            url: 'addProduct.php',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function () {
                alert('Form Submitted!');
            },
            error: function(){
                alert("error in ajax form submission");
            }
        });

        return false;
    });
});

Angular 2 ngfor first, last, index loop

Check out this plunkr.

When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.

<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first"> 
...

Edit: Thanks to Christopher Moore: Angular exposes the following local variables:

  • index
  • first
  • last
  • even
  • odd

Oracle date function for the previous month

I believe this would also work:

select count(distinct switch_id)   
  from [email protected]  
 where 
   dealer_name =  'XXXX'    
   and (creation_date BETWEEN add_months(trunc(sysdate,'mm'),-1) and  trunc(sysdate, 'mm'))

It has the advantage of using BETWEEN which is the way the OP used his date selection criteria.

How to check certificate name and alias in keystore files?

In a bash-like environment you can use:

keytool -list -v -keystore cacerts.jks | grep 'Alias name:' | grep -i foo

This command consist of 3 parts. As stated above, the 1st part will list all trusted certificates with all the details and that's why the 2nd part comes to filter only the alias information among those details. And finally in the 3rd part you can search for a specific alias (or part of it). The -i turns the case insensitive mode on. Thus the given command will yield all aliases containing the pattern 'foo', f.e. foo, 123_FOO, fooBar, etc. For more information man grep.

Can I open a dropdownlist using jQuery

Simple an easy way.

function down(what) {
  pos = $(what).offset();  // remember position
  $(what).css("position","absolute");
  $(what).offset(pos);   // reset position
  $(what).attr("size","10"); // open dropdown
}

function up(what) {
$(what).css("position","static");
$(what).attr("size","1");  // close dropdown
}

Now you can call your DropDown just like this

<select onfocus="down(this)" onblur="up(this)">

Works perfect for me.

Maybe better, because you have no problems with the position of the other elemts on the page.

function down(was) {
a = $(was).clone().attr('id','down_man').attr('disabled',true).insertAfter(was);
$(was).css("position","absolute").attr("size","10");
}

function up(was) {
$('#down_man').remove();
$(was).css("position","static");
$(was).attr("size","1");
}

Change the ID to a fix value mybe not smart but i hope you see the idee.

CSS @font-face not working in ie

1) Try putting an absolute link not relative link to your eot font - somehow old IE just don't know in which folder the css file is 2) make 2 extra @font-face declarations so it should look like this:

@font-face { /* for modern browsers and modern IE */
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); 
    src: url("../fonts/Futura_Medium_BT.eot?#iefix") format("embedded-opentype"), 
    url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); 
}
@font-face{ /* for old IE */
  font-family: "Futura_IE"; 
  src: url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot);
}

@font-face{ /* for old IE */
  font-family: "Futura_IE2"; 
  src:url(/wp-content/themes/my-theme/fonts/Futura_Medium_BT.eot?#iefix) 
  format("embedded-opentype");
}

.p{ font-family: "Futura", "Futura_IE", "Futura_IE2", Arial, sans-serif;

This is an example for wordpress template - absolute link should point from where your start index file is.

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

How can I output leading zeros in Ruby?

filenames = '000'.upto('100').map { |index| "file_#{index}" }

Outputs

[file_000, file_001, file_002, file_003, ..., file_098, file_099, file_100]

Relative div height

Basically, the problem lies in block12. for the block1/2 to take up the total height of the block12, it must have a defined height. This stack overflow post explains that in really good detail.

So setting a defined height for block12 will allow you to set a proper height. I have created an example on JSfiddle that will show you the the blocks can be floated next to one another if the block12 div is set to a standard height through out the page.

Here is an example including a header and block3 div with some content in for examples.

#header{
   position:absolute;
   top:0;
   left:0;
   width:100%;
   height:20%;
    }

    #block12{
    position:absolute;
    top:20%;
    width:100%;
    left:0;
    height:40%;
    }
    #block1,#block2{
    float:left;
    overflow-y: scroll;
    text-align:center;
    color:red;
    width:50%;
    height:100%;

    }
 #clear{clear:both;}
 #block3{
    position:absolute;
    bottom:0;
    color:blue;
    height:40%;

    }

List of Timezone IDs for use with FindTimeZoneById() in C#?

From MSDN

ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();
Console.WriteLine("The local system has the following {0} time zones", zones.Count);
foreach (TimeZoneInfo zone in zones)
   Console.WriteLine(zone.Id);

sql select with column name like

Blorgbeard had a great answer for SQL server. If you have a MySQL server like mine then the following will allow you to select the information from columns where the name is like some key phrase. You just have to substitute the table name, database name, and keyword.

SET @columnnames = (SELECT concat("`",GROUP_CONCAT(`COLUMN_NAME` SEPARATOR "`, `"),"`") 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='your_database' 
    AND `TABLE_NAME`='your_table'
    AND COLUMN_NAME LIKE "%keyword%");

SET @burrito = CONCAT("SELECT ",@columnnames," FROM your_table");

PREPARE result FROM @burrito;
EXECUTE result;

how to evenly distribute elements in a div next to each other?

You just need to display the div with id #menu as flex container like this:

#menu{
    width: 800px;
    display: flex;
    justify-content: space-between;
}

how to convert long date value to mm/dd/yyyy format

Refer Below code which give the date in String form.

import java.text.SimpleDateFormat;
import java.util.Date;



public class Test{

    public static void main(String[] args) {
        long val = 1346524199000l;
        Date date=new Date(val);
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        String dateText = df2.format(date);
        System.out.println(dateText);
    }
}

Default visibility for C# classes and members (fields, methods, etc.)?

By default, the access modifier for a class is internal. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.

Request string without GET arguments

Why so complicated? =)

$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];

this should really do it man ;)

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

The solution @denver_citizen provided above did not work for me, but I liked the spirit of it so I modified a few things :

  • made it a stored procedure
  • changed the way the foreign keys are populated and recreated
  • the original script truncates all referenced tables, this can cause foreign key violation error when the referenced table has other foreign key references. This script truncates only the table specified as parameter. It is up to the user, to call this stored procedure multiple times on all tables in the correct order

For the benefit of the public here is the updated script :

CREATE PROCEDURE [dbo].[truncate_non_empty_table]

  @TableToTruncate                 VARCHAR(64)

AS 

BEGIN

SET NOCOUNT ON

-- GLOBAL VARIABLES
DECLARE @i int
DECLARE @Debug bit
DECLARE @Recycle bit
DECLARE @Verbose bit
DECLARE @TableName varchar(80)
DECLARE @ColumnName varchar(80)
DECLARE @ReferencedTableName varchar(80)
DECLARE @ReferencedColumnName varchar(80)
DECLARE @ConstraintName varchar(250)

DECLARE @CreateStatement varchar(max)
DECLARE @DropStatement varchar(max)   
DECLARE @TruncateStatement varchar(max)
DECLARE @CreateStatementTemp varchar(max)
DECLARE @DropStatementTemp varchar(max)
DECLARE @TruncateStatementTemp varchar(max)
DECLARE @Statement varchar(max)

        -- 1 = Will not execute statements 
 SET @Debug = 0
        -- 0 = Will not create or truncate storage table
        -- 1 = Will create or truncate storage table
 SET @Recycle = 0
        -- 1 = Will print a message on every step
 set @Verbose = 1

 SET @i = 1
    SET @CreateStatement = 'ALTER TABLE [dbo].[<tablename>]  WITH NOCHECK ADD  CONSTRAINT [<constraintname>] FOREIGN KEY([<column>]) REFERENCES [dbo].[<reftable>] ([<refcolumn>])'
    SET @DropStatement = 'ALTER TABLE [dbo].[<tablename>] DROP CONSTRAINT [<constraintname>]'
    SET @TruncateStatement = 'TRUNCATE TABLE [<tablename>]'

-- Drop Temporary tables

IF OBJECT_ID('tempdb..#FKs') IS NOT NULL
    DROP TABLE #FKs

-- GET FKs
SELECT ROW_NUMBER() OVER (ORDER BY OBJECT_NAME(parent_object_id), clm1.name) as ID,
       OBJECT_NAME(constraint_object_id) as ConstraintName,
       OBJECT_NAME(parent_object_id) as TableName,
       clm1.name as ColumnName, 
       OBJECT_NAME(referenced_object_id) as ReferencedTableName,
       clm2.name as ReferencedColumnName
  INTO #FKs
  FROM sys.foreign_key_columns fk
       JOIN sys.columns clm1 
         ON fk.parent_column_id = clm1.column_id 
            AND fk.parent_object_id = clm1.object_id
       JOIN sys.columns clm2
         ON fk.referenced_column_id = clm2.column_id 
            AND fk.referenced_object_id= clm2.object_id
 --WHERE OBJECT_NAME(parent_object_id) not in ('//tables that you do not wont to be truncated')
 WHERE OBJECT_NAME(referenced_object_id) = @TableToTruncate
 ORDER BY OBJECT_NAME(parent_object_id)


-- Prepare Storage Table
IF Not EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'Internal_FK_Definition_Storage')
   BEGIN
        IF @Verbose = 1
     PRINT '1. Creating Process Specific Tables...'

  -- CREATE STORAGE TABLE IF IT DOES NOT EXISTS
  CREATE TABLE [Internal_FK_Definition_Storage] 
  (
   ID int not null identity(1,1) primary key,
   FK_Name varchar(250) not null,
   FK_CreationStatement varchar(max) not null,
   FK_DestructionStatement varchar(max) not null,
   Table_TruncationStatement varchar(max) not null
  ) 
   END 
ELSE
   BEGIN
        IF @Recycle = 0
            BEGIN
                IF @Verbose = 1
       PRINT '1. Truncating Process Specific Tables...'

    -- TRUNCATE TABLE IF IT ALREADY EXISTS
    TRUNCATE TABLE [Internal_FK_Definition_Storage]    
      END
      ELSE
         PRINT '1. Process specific table will be recycled from previous execution...'
   END


IF @Recycle = 0
   BEGIN

  IF @Verbose = 1
     PRINT '2. Backing up Foreign Key Definitions...'

  -- Fetch and persist FKs             
  WHILE (@i <= (SELECT MAX(ID) FROM #FKs))
   BEGIN
    SET @ConstraintName = (SELECT ConstraintName FROM #FKs WHERE ID = @i)
    SET @TableName = (SELECT TableName FROM #FKs WHERE ID = @i)
    SET @ColumnName = (SELECT ColumnName FROM #FKs WHERE ID = @i)
    SET @ReferencedTableName = (SELECT ReferencedTableName FROM #FKs WHERE ID = @i)
    SET @ReferencedColumnName = (SELECT ReferencedColumnName FROM #FKs WHERE ID = @i)

    SET @DropStatementTemp = REPLACE(REPLACE(@DropStatement,'<tablename>',@TableName),'<constraintname>',@ConstraintName)
    SET @CreateStatementTemp = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@CreateStatement,'<tablename>',@TableName),'<column>',@ColumnName),'<constraintname>',@ConstraintName),'<reftable>',@ReferencedTableName),'<refcolumn>',@ReferencedColumnName)
    SET @TruncateStatementTemp = REPLACE(@TruncateStatement,'<tablename>',@TableName) 

    INSERT INTO [Internal_FK_Definition_Storage]
                        SELECT @ConstraintName, @CreateStatementTemp, @DropStatementTemp, @TruncateStatementTemp

    SET @i = @i + 1

    IF @Verbose = 1
       PRINT '  > Backing up [' + @ConstraintName + '] from [' + @TableName + ']'

    END   
    END   
    ELSE 
       PRINT '2. Backup up was recycled from previous execution...'

       IF @Verbose = 1
     PRINT '3. Dropping Foreign Keys...'

    -- DROP FOREING KEYS
    SET @i = 1
    WHILE (@i <= (SELECT MAX(ID) FROM [Internal_FK_Definition_Storage]))
          BEGIN
             SET @ConstraintName = (SELECT FK_Name FROM [Internal_FK_Definition_Storage] WHERE ID = @i)
    SET @Statement = (SELECT FK_DestructionStatement FROM [Internal_FK_Definition_Storage] WITH (NOLOCK) WHERE ID = @i)

    IF @Debug = 1 
       PRINT @Statement
    ELSE
       EXEC(@Statement)

    SET @i = @i + 1


    IF @Verbose = 1
       PRINT '  > Dropping [' + @ConstraintName + ']'

             END     


    IF @Verbose = 1
       PRINT '4. Truncating Tables...'

    -- TRUNCATE TABLES
-- SzP: commented out as the tables to be truncated might also contain tables that has foreign keys
-- to resolve this the stored procedure should be called recursively, but I dont have the time to do it...          
 /*
    SET @i = 1
    WHILE (@i <= (SELECT MAX(ID) FROM [Internal_FK_Definition_Storage]))
          BEGIN

    SET @Statement = (SELECT Table_TruncationStatement FROM [Internal_FK_Definition_Storage] WHERE ID = @i)

    IF @Debug = 1 
       PRINT @Statement
    ELSE
       EXEC(@Statement)

    SET @i = @i + 1

    IF @Verbose = 1
       PRINT '  > ' + @Statement
          END
*/          


    IF @Verbose = 1
       PRINT '  > TRUNCATE TABLE [' + @TableToTruncate + ']'

    IF @Debug = 1 
        PRINT 'TRUNCATE TABLE [' + @TableToTruncate + ']'
    ELSE
        EXEC('TRUNCATE TABLE [' + @TableToTruncate + ']')


    IF @Verbose = 1
       PRINT '5. Re-creating Foreign Keys...'

    -- CREATE FOREING KEYS
    SET @i = 1
    WHILE (@i <= (SELECT MAX(ID) FROM [Internal_FK_Definition_Storage]))
          BEGIN
             SET @ConstraintName = (SELECT FK_Name FROM [Internal_FK_Definition_Storage] WHERE ID = @i)
    SET @Statement = (SELECT FK_CreationStatement FROM [Internal_FK_Definition_Storage] WHERE ID = @i)

    IF @Debug = 1 
       PRINT @Statement
    ELSE
       EXEC(@Statement)

    SET @i = @i + 1


    IF @Verbose = 1
       PRINT '  > Re-creating [' + @ConstraintName + ']'

          END

    IF @Verbose = 1
       PRINT '6. Process Completed'


END

Can someone explain mappedBy in JPA and Hibernate?

mappedby speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)..

If you don't do that, hibernate will map this two relation as it's not the same relation

so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.

How to access List elements

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

psql - save results of command to a file

I assume that there exist some internal psql command for this, but you could also run the script command from util-linux-ng package:

DESCRIPTION Script makes a typescript of everything printed on your terminal.

overlay two images in android to set an imageview

this is my solution:

    public Bitmap Blend(Bitmap topImage1, Bitmap bottomImage1, PorterDuff.Mode Type) {

        Bitmap workingBitmap = Bitmap.createBitmap(topImage1);
        Bitmap topImage = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);

        Bitmap workingBitmap2 = Bitmap.createBitmap(bottomImage1);
        Bitmap bottomImage = workingBitmap2.copy(Bitmap.Config.ARGB_8888, true);

        Rect dest = new Rect(0, 0, bottomImage.getWidth(), bottomImage.getHeight());
        new BitmapFactory.Options().inPreferredConfig = Bitmap.Config.ARGB_8888;
        bottomImage.setHasAlpha(true);
        Canvas canvas = new Canvas(bottomImage);
        Paint paint = new Paint();

        paint.setXfermode(new PorterDuffXfermode(Type));

        paint.setFilterBitmap(true);
        canvas.drawBitmap(topImage, null, dest, paint);
        return bottomImage;
    }

usage :

imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.SCREEN));

or

imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.OVERLAY));

and the results :

Overlay mode : Overlay mode

Screen mode: Screen mode

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

As mentioned in the comments, there cannot be a continuous scale on variable of the factor type. You could change the factor to numeric as follows, just after you define the meltDF variable.

meltDF$variable=as.numeric(levels(meltDF$variable))[meltDF$variable]

Then, execute the ggplot command

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

And you will have your chart.

Hope this helps

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How to generate XML file dynamically using PHP?

I'd use SimpleXMLElement.

<?php

$xml = new SimpleXMLElement('<xml/>');

for ($i = 1; $i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I faced the same problem and was frustrated to see as to all options i tried and none of them work,

Turns out once you have configured everything correctly including settings.xml

just clear your local repository folder and try mvn commands. That greatly helped me

Hope this helps others

ESRI : Failed to parse source map

Further to just simply turning off Source Maps in Chrome - I've done a little digging and found that using Web Essentials to create the source maps seems to be the issue.

For whatever reason, if I use an external compiler (Koala) I can successfully create working source maps in Chrome (no errors). Whereas if I use Web Essentials, the source maps fail to parse.

Hope this helps someone.

Is it possible to put a ConstraintLayout inside a ScrollView?

Since the actual ScrollView is encapsulated in a CoordinatorLayout with a Toolbar ...

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/list"/>

</android.support.design.widget.CoordinatorLayout>

... I had to define android:layout_marginTop="?attr/actionBarSize" to make the scrolling working:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="?attr/actionBarSize">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <!-- UI elements here -->

    </android.support.constraint.ConstraintLayout>

</ScrollView>

Above also works with NestedScrollView instead of ScrollView. Defining android:fillViewport="true" is not needed for me.

Is there a Python equivalent to Ruby's string interpolation?

Python's string interpolation is similar to C's printf()

If you try:

name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name

The tag %s will be replaced with the name variable. You should take a look to the print function tags: http://docs.python.org/library/functions.html

apache mod_rewrite is not working or not enabled

Please try

sudo a2enmod rewrite

or use correct apache restart command

sudo /etc/init.d/apache2 restart 

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

Removing duplicate objects with Underscore for Javascript

Implementation of Shiplu's answer.

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

var x = _.uniq( _.collect( foo, function( x ){
    return JSON.stringify( x );
}));

console.log( x ); // returns [ { "a" : "1" }, { "b" : "2" } ]

HtmlEncode from Class Library

Import System.Web Or call the System.Web.HttpUtility which contains it

You will need to add the reference to the DLL if it isn't there already

string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);

Run a Command Prompt command from Desktop Shortcut

Create A Shortcut That Opens The Command Prompt & Runs A Command:

Yes! You can create a shortcut to cmd.exe with a command specified after it. Alternatively you could create a batch script, if your goal is just to have a clickable way to run commands.

Steps:

  1. Right click on some empty space in Explorer, and in the context menu go to "New/Shortcut".

  2. When prompted to enter a location put either:

"C:\Windows\System32\cmd.exe /k your-command" This will run the command and keep (/k) the command prompt open after.

or

"C:\Windows\System32\cmd.exe /c your-command" This will run the command and the close (/c) the command prompt.

Notes:

  • Tested, and working on Windows 8 - Core X86-64 September 12 2014

  • If you want to have more than one command, place an "&" symbol in between them. For example: "C:\Windows\System32\cmd.exe /k command1 & command2".

How to load all the images from one of my folder into my web page, using Jquery/Javascript

This is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /" I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1); with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body

$ ("body"). append ($ ("<img src =" + dir + pathName + "> </ img>"));
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="jquery-1.6.3.min.js"></script>
        <script>


        var dir = "imagenes/";
        var fileextension = ".jpg";
        $.ajax({
            //This will retrieve the contents of the folder if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //Lsit all png file names in the page
                $(data).find("a:contains(" + fileextension + ")").each(function () {
                    var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
            var pathName = filename.substring(filename.lastIndexOf('/') + 1);               
                    $("body").append($("<img src=" + dir + pathName + "></img>"));
            console.log(dir+pathName);
                });
            }
        });



        </script>

  </head>
  <body>
<img src="1_1.jpg">
  </body>
</html>

How do I create a SQL table under a different schema?

Hit F4 and you'll get what you are looking for.

Cast received object to a List<object> or IEnumerable<object>

This Code worked for me

List<Object> collection = new List<Object>((IEnumerable<Object>)myObject);

Attach the Java Source Code

Answer For Eclipse 2019 With ScreenShots

  • Step 1: Window -> Preferences -> Java -> Installed JREs

Installed JREs

  • Step 2: Select Currently used JRE, now Edit option will get enabled, Click on edit option

Currently used JRE  option edit

  • Step 3: Select rt.jar from JRE systems library, click on corresponding drop down to expand

rt.jar

  • Step 4: Select Source attachment none, Click on Source Attachment Button, Source attachment configuration window will appear, Select external location

Source attachment external location

  • Step 5: Select src.zip file from jdk folder, say ok ok finish

src.zip

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

How to fix Terminal not loading ~/.bashrc on OS X Lion

I have the following in my ~/.bash_profile:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

If I had .bashrc instead of ~/.bashrc, I'd be seeing the same symptom you're seeing.

Removing multiple files from a Git repo that have already been deleted from disk

If you simply run:

git add -u

git will update its index to know that the files that you've deleted should actually be part of the next commit. Then you can run "git commit" to check in that change.

Or, if you run:

git commit -a

It will automatically take these changes (and any others) and commit them.

Update: If you only want to add deleted files, try:

git ls-files --deleted -z | xargs -0 git rm
git commit

Android Studio update -Error:Could not run build action using Gradle distribution

I had a similar issue, when I upgraded to the latest version of Android Studio 1.3.2. What seemed to work for me was removing the .gradle folder from my project directory:

rm -rf ~/project/.gradle

Difference between JPanel, JFrame, JComponent, and JApplet

You might find it useful to lookup the classes on oracle. Eg:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html

There you can see that JFrame extends JComponent and JContainer.

JComponent is a a basic object that can be drawn, JContainer extends this so that you can add components to it. JPanel and JFrame both extend JComponent as you can add things to them. JFrame provides a window, whereas JPanel is just a panel that goes inside a window. If that makes sense.

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

Heatmap in matplotlib with pcolor?

Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.

With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

And here's the output:

Matplotlib HeatMap

What is a plain English explanation of "Big O" notation?

If you have a suitable notion of infinity in your head, then there is a very brief description:

Big O notation tells you the cost of solving an infinitely large problem.

And furthermore

Constant factors are negligible

If you upgrade to a computer that can run your algorithm twice as fast, big O notation won't notice that. Constant factor improvements are too small to even be noticed in the scale that big O notation works with. Note that this is an intentional part of the design of big O notation.

Although anything "larger" than a constant factor can be detected, however.

When interested in doing computations whose size is "large" enough to be considered as approximately infinity, then big O notation is approximately the cost of solving your problem.


If the above doesn't make sense, then you don't have a compatible intuitive notion of infinity in your head, and you should probably disregard all of the above; the only way I know to make these ideas rigorous, or to explain them if they aren't already intuitively useful, is to first teach you big O notation or something similar. (although, once you well understand big O notation in the future, it may be worthwhile to revisit these ideas)

MySQL CONCAT returns NULL if any field contain NULL

To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:

SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)

Set formula to a range of cells

Range("C1:C10").Formula = "=A1+B1"

Simple as that.

It autofills (FillDown) the range with the formula.

Using sudo with Python script

sometimes require a carriage return:

os.popen("sudo -S %s"%(command), 'w').write('mypass\n')

What linux shell command returns a part of a string?

If you are looking for a shell utility to do something like that, you can use the cut command.

To take your example, try:

echo "abcdefg" | cut -c3-5

which yields

cde

Where -cN-M tells the cut command to return columns N to M, inclusive.

How to return a string value from a Bash function

You could have the function take a variable as the first arg and modify the variable with the string you want to return.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

Prints "foo bar rab oof".

Edit: added quoting in the appropriate place to allow whitespace in string to address @Luca Borrione's comment.

Edit: As a demonstration, see the following program. This is a general-purpose solution: it even allows you to receive a string into a local variable.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "$1='foo bar rab oof'"
}

return_var=''
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar=''
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This prints:

+ return_var=
+ pass_back_a_string return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local lvar=
+ pass_back_a_string lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

Edit: demonstrating that the original variable's value is available in the function, as was incorrectly criticized by @Xichen Li in a comment.

#!/bin/bash
set -x
function pass_back_a_string() {
    eval "echo in pass_back_a_string, original $1 is \$$1"
    eval "$1='foo bar rab oof'"
}

return_var='original return_var'
pass_back_a_string return_var
echo $return_var

function call_a_string_func() {
     local lvar='original lvar'
     pass_back_a_string lvar
     echo "lvar='$lvar' locally"
}

call_a_string_func
echo "lvar='$lvar' globally"

This gives output:

+ return_var='original return_var'
+ pass_back_a_string return_var
+ eval 'echo in pass_back_a_string, original return_var is $return_var'
++ echo in pass_back_a_string, original return_var is original return_var
in pass_back_a_string, original return_var is original return_var
+ eval 'return_var='\''foo bar rab oof'\'''
++ return_var='foo bar rab oof'
+ echo foo bar rab oof
foo bar rab oof
+ call_a_string_func
+ local 'lvar=original lvar'
+ pass_back_a_string lvar
+ eval 'echo in pass_back_a_string, original lvar is $lvar'
++ echo in pass_back_a_string, original lvar is original lvar
in pass_back_a_string, original lvar is original lvar
+ eval 'lvar='\''foo bar rab oof'\'''
++ lvar='foo bar rab oof'
+ echo 'lvar='\''foo bar rab oof'\'' locally'
lvar='foo bar rab oof' locally
+ echo 'lvar='\'''\'' globally'
lvar='' globally

How do I create a shortcut via command-line in Windows?

I would like to propose different solution which wasn't mentioned here which is using .URL files:

set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%

Notes:

  • By default .url files are intended to open web pages but they are working fine for any properly constructed URI
  • Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
  • IconFile and IconIndex are optional
  • For reference you can check An Unofficial Guide to the URL File Format of Edward Blake

Delete item from array and shrink array

No use of any pre defined function as well as efficient: --- >>

public static void Delete(int d , int[] array )
{       
    Scanner in = new Scanner (System.in);

    int i , size = array.length;

    System.out.println("ENTER THE VALUE TO DELETE? ");

     d = in.nextInt();

        for ( i=0;i< size;i++)
        {
                if (array[i] == d)
                        {


                            int[] arr3 =new int[size-1];
                            int[] arr4 = new int[i];
                            int[] arr5 = new int[size-i-1];

                                    for (int a =0 ;a<i;a++)
                                    {
                                        arr4[a]=array[a];
                                        arr3[a] = arr4[a];
                                    }
                                     for (int a =i ;a<size-1;a++)
                                     {
                                         arr5[a-i] = array[a+1];
                                         arr3[a] = arr5[a-i];

                                     }


                System.out.println(Arrays.toString(arr3));

                        }
                else System.out.println("************");    


        }

}

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

In My Aws Windows I Solved it and steps are

  1. Open "C:\ProgramData\MySQL\MySQL Server 8.0"
  2. Open My.ini
  3. Find "[mysql]"
  4. After "no-beep=" Brake Line and insert "default-character-set=utf8"
  5. Find "[mysqld]"
  6. Insert "collation-server = utf8_unicode_ci"
  7. Insert "character-set-server = utf8"

example

...
# socket=MYSQL

port=3306

[mysql]
no-beep=
default-character-set=utf8
# default-character-set=

# SERVER SECTION
# ----------------------------------------------------------------------
# 
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.=
# 
# server_type=2
[mysqld]

collation-server = utf8_unicode_ci
character-set-server = utf8
# The next three options are mutually exclusive to SERVER_PORT below.
# skip-networking=
# enable-named-pipe=
# shared-memory=
...

mysql screenshot

How to compare two lists in python?

You could always do just:

a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]

a==b    #returns False
a==c    #returns False
a==d    #returns True

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")

Convert all strings in a list to int

Use a list comprehension:

results = [int(i) for i in results]

e.g.

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

How do you share code between projects/solutions in Visual Studio?

Extract the common code into a class library project and add that class library project to your solutions. Then you can add a reference to the common code from other projects by adding a project reference to that class library. The advantage of having a project reference as opposed to a binary/assembly reference is that if you change your build configuration to debug, release, custom, etc, the common class library project will be built based on that configuration as well.

Cast to generic type in C#

I struggled to solve a similar problem around data table classes instead of messages. The root issue mentioned above of casting a non-generic version of the class to a derived generic version was the same.

In order to allow injection into a portable class library which did not support database libraries, I introduced a set of interface classes, with the intent that I could pass a type and get a matching generic. It ended up needing to implement a generic method.

// Interface for injection
public interface IDatabase
{
    // Original, non-functional signature:
    IDatatable<object> GetDataTable(Type dataType);

    // Functional method using a generic method:
    IDatatable<T> GetDataTable<T>();
}

And this the whole implementation using the generic method above.

The generic class that will be cast from a dictionary.

// Non-generic base class allows listing tables together
abstract class Datatable
{
    Datatable(Type storedClass)
    {
      StoredClass = storedClass;
    }

    Type StoredClass { get; private set; }
}

// Generic inheriting class
abstract class Datatable<T>: Datatable, IDatatable<T>
{
    protected Datatable()
        :base(typeof(T))
    {
    }
}

This is the class that stores the generic class and casts it to satisfy the generic method in the interface

class Database
{
    // Dictionary storing the classes using the non-generic base class
    private Dictionary<Type, Datatable> _tableDictionary;

    protected Database(List<Datatable> tables)
    {
        _tableDictionary = new Dictionary<Type, Datatable>();
        foreach (var table in tables)
        {
            _tableDictionary.Add(table.StoredClass, table);
        }
    }

    // Interface implementation, casts the generic
    public IDatatable<T> GetDataTable<T>()
    {
        Datatable table = null;

        _tableDictionary.TryGetValue(typeof(T), out table);

        return table as IDatatable<T>;
    }
}

And finally the calling of the interface method.

IDatatable<CustomerAccount> table = _database.GetDataTable<CustomerAccount>();

Download file through an ajax call php

@joe : Many thanks, this was a good heads up!

I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

So that's how I did it (using JQuery to handle the AJAX request):

  1. Initial post request:

    var parameters = {
         pid     : "mypid",
       "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
    }

    var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

 //Code to create the zip file
 //......
 //Id of the file
 $zipid = "myzipfile.zip"
 //Download Link - it can be prettier
 $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
 //JSON response to be handled on the client side
 $result = '{"success":1,"path":"'.$dlink.'","error":null}';
 header('Content-type: application/json;');
 echo $result;

The "request/download" can perform some security checks, if needed, and generate the file transfer:

$fn = $_GET['file'];
if ($fn) {
  //Perform security checks
  //.....check user session/role/whatever
  $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
  if (file_exists($result)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename='.basename($result));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($result));
    ob_clean();
    flush();
    readfile($result);
    @unlink($result);
  }

}

MySQL ORDER BY multiple column ASC and DESC

@DRapp is a genius. I never understood how he coded his SQL,so I tried coding it in my own understanding.


    SELECT 
      f.username,
      f.point,
      f.avg_time
    FROM
      (
      SELECT
        userscores.username,
        userscores.point,
        userscores.avg_time
      FROM
        (
        SELECT
          users.username,
          scores.point,
          scores.avg_time
        FROM
          scores
        JOIN users
        ON scores.user_id = users.id
        ORDER BY scores.point DESC
        ) userscores
      ORDER BY
        point DESC,
        avg_time
      ) f
    GROUP BY f.username
    ORDER BY point DESC

It yields the same result by using GROUP BY instead of the user @variables.

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

Select specific row from mysql table

SQL tables are not ordered by default, and asking for the n-th row from a non ordered set of rows has no meaning as it could potentially return a different row each time unless you specify an ORDER BY:

select * from customer order by id where row_number() = 3

(sometimes MySQL tables are shown with an internal order but you cannot rely on this behaviour). Then you can use LIMIT offset, row_count, with a 0-based offset so row number 3 becomes offset 2:

select * from customer order by id
limit 2, 1

or you can use LIMIT row_count OFFSET offset:

select * from customer order by id
limit 1 offset 2

How to add new elements to an array?

Adding new items to String array.

String[] myArray = new String[] {"x", "y"};

// Convert array to list
List<String> listFromArray = Arrays.asList(myArray);

// Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
List<String> tempList = new ArrayList<String>(listFromArray);
tempList.add("z");

//Convert list back to array
String[] tempArray = new String[tempList.size()];
myArray = tempList.toArray(tempArray);

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Hiding the address bar of a browser (popup)

You could make the webpage scroll down to a position where you can't see the address bar, and if the user scrolls, the page should return to your set position. In that way, Mobile browsers when scrolled down , will try to guve you full-screen experience. So it will hide the address bar. I don't know the code, someone else might put up the code.

How to access SOAP services from iPhone

Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).

Could not extract response: no suitable HttpMessageConverter found for response type

Here is a simple solution

try adding this dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.3</version>
</dependency>

Loading a .json file into c# program

See Microsofts JavaScriptSerializer

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

Namespace: System.Web.Script.Serialization

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

Increase days to php current Date()

If you need this code in several places then I'd suggest that you add a short function to keep your code simpler and easier to test.

function add_days( $days, $from_date = null ) {
    if ( is_numeric( $from_date ) ) { 
        $new_date = $from_date; 
    } else { 
        $new_date = time();
    }

    // Timestamp is the number of seconds since an event in the past
    // To increate the value by one day we have to add 86400 seconds to the value
    // 86400 = 24h * 60m * 60s
    $new_date += $days * 86400;

    return $new_date;
}

Then you can use it anywhere like this:

$today       = add_days( 0 );
$tomorrow    = add_days( 1 );
$yesterday   = add_days( -1 );
$in_36_hours = add_days( 1.5 );

$first_reminder  = add_days( 10 );
$second_reminder = add_days( 5, $first_reminder );
$last_reminder   = add_days( 3, $second_reminder );

How to add image for button in android?

   <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="News Feed"
        android:icon="@drawable/newsfeed" />

newsfeed is image in the drawable folder

How to detect IE11?

Try This:

var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
alert("IE")
}else{
alert("Other")
}

Decimal separator comma (',') with numberDecimal inputType in EditText

A variation on the 'digit' solutions offered here:

char separator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + separator));

Taking into account the locale separator.

Prevent wrapping of span or div

Try this:

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
    white-space: nowrap;_x000D_
}_x000D_
.slide {_x000D_
    display: inline-block;_x000D_
    width: 600px;_x000D_
    white-space: normal;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <span class="slide">Some content</span>_x000D_
    <span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
    <span class="slide">Even more content!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you can omit .slideContainer { overflow-x: scroll; } (which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.

The key here is display: inline-block. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

Comparing two integer arrays in Java

Even though there is something easy like .equals, I'd like to point out TWO mistakes you made in your code. The first: when you go through the arrays, you say b is true or false. Then you start again to check, because of the for-loop. But each time you are giving b a value. So, no matter what happens, the value b gets set to is always the value of the LAST for-loop. Next time, set boolean b = true, if equal = true, do nothing, if equal = false, b=false.

Secondly, you are now checking each value in array1 with each value in array2. If I understand correctly, you only need to check the values at the same location in the array, meaning you should have deleted the second for-loop and check like this: if (array2[i] == array1[i]). Then your code should function as well.

Your code would work like this:

public static void compareArrays(int[] array1, int[] array2) {
    boolean b = true;
    for (int i = 0; i < array2.length; i++) {
        if (array2[i] == array1[i]) {
            System.out.println("true");
        } else {
            b = false;
            System.out.println("False");
        }
    } 
    return b;

}

But as said by other, easier would be: Arrays.equals(ary1,ary2);

What is the functionality of setSoTimeout and how it works?

This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT time! if it does not get any signal it throw exception! It means that time expired!

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class SocketTest extends Thread {
  private ServerSocket serverSocket;

  public SocketTest() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }

  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();

        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new SocketTest();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

What is the best way to call a script from another script?

If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like:

test1.py

def main():
    print "I am a test"
    print "see! I do nothing productive."

if __name__ == "__main__":
    main()

service.py

import test1
# lots of stuff here
test1.main() # do whatever is in test1.py

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

if you are using XAMPP and WAMP together in the same machine add sql server port number

<connection>
                <host><![CDATA[localhost:3390]]></host>
                <username><![CDATA[root]]></username>
                <password><![CDATA[]]></password>
                <dbname><![CDATA[sritoss_1910]]></dbname>
                <initStatements><![CDATA[SET NAMES utf8]]></initStatements>
                <model><![CDATA[mysql4]]></model>
                <type><![CDATA[pdo_mysql]]></type>
                <pdoType><![CDATA[]]></pdoType>
                <active>1</active>
</connection>

GetElementByID - Multiple IDs

Dunno if something like this works in js, in PHP and Python which i use quite often it is possible. Maybe just use for loop like:

function doStuff(){
    for(i=1; i<=4; i++){
        var i = document.getElementById("myCiricle"+i);
    }
}

How to process POST data in Node.js?

Here is how you can do it if you use node-formidable:

var formidable = require("formidable");

var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
    console.log(fields.parameter1);
    console.log(fields.parameter2);
    // ...
});

Is there a way to make a DIV unselectable?

Use

onselectstart="return false"

it prevents copying your content.

Adding Http Headers to HttpClient

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

How to run batch file from network share without "UNC path are not supported" message?

Editing Windows registries is not worth it and not safe, use Map network drive and load the network share as if it's loaded from one of your local drives.

enter image description here

how to upload a file to my server using html

You need enctype="multipart/form-data" otherwise you will load only the file name and not the data.

java.util.zip.ZipException: error in opening zip file

I've seen this exception before when whatever the JVM considers to be a temp directory is not accessible due to not being there or not having permission to write.

How to empty a list?

it turns out that with python 2.5.2, del l[:] is slightly slower than l[:] = [] by 1.1 usec.

$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2

How to implement a binary search tree in Python?

its easy to implement a BST using two classes, 1. Node and 2. Tree Tree class will be just for user interface, and actual methods will be implemented in Node class.

class Node():

    def __init__(self,val):
        self.value = val
        self.left = None
        self.right = None


    def _insert(self,data):
        if data == self.value:
            return False
        elif data < self.value:
            if self.left:
                return self.left._insert(data)
            else:
                self.left = Node(data)
                return True
        else:
            if self.right:
                return self.right._insert(data)
            else:
                self.right = Node(data)
                return True

    def _inorder(self):
        if self:
            if self.left:
                self.left._inorder()
            print(self.value)
            if self.right:
                self.right._inorder()



class Tree():

    def __init__(self):
        self.root = None

    def insert(self,data):
        if self.root:
            return self.root._insert(data)
        else:
            self.root = Node(data)
            return True
    def inorder(self):
        if self.root is not None:
            return self.root._inorder()
        else:
            return False




if __name__=="__main__":
    a = Tree()
    a.insert(16)
    a.insert(8)
    a.insert(24)
    a.insert(6)
    a.insert(12)
    a.insert(19)
    a.insert(29)
    a.inorder()

Inorder function for checking whether BST is properly implemented.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

Error "initializer element is not constant" when trying to initialize variable with const

I had this error in code that looked like this:

int A = 1;
int B = A;

The fix is to change it to this

int A = 1;
#define B A

The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.

What does character set and collation mean exactly?

A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.

The collation is how to compare characters, in latin9, there are letters as e é è ê f, if sorted by their binary representation, it will go e f é ê è but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê are equal, and then f.

How to make node.js require absolute? (instead of relative)

IMHO, the easiest way is to define your own function as part of GLOBAL object. Create projRequire.js in the root of you project with the following contents:

var projectDir = __dirname;

module.exports = GLOBAL.projRequire = function(module) {
  return require(projectDir + module);
}

In your main file before requireing any of project-specific modules:

// init projRequire
require('./projRequire');

After that following works for me:

// main file
projRequire('/lib/lol');

// index.js at projectDir/lib/lol/index.js
console.log('Ok');


@Totty, I've comed up with another solution, which could work for case you described in comments. Description gonna be tl;dr, so I better show a picture with structure of my test project.

How to solve SyntaxError on autogenerated manage.py?

It seems you have more than one version of Python on your computer. Try and remove one and leave the only version you used to develop your application.

If need be, you can upgrade your version, but ensure you have only one version of Python on your computer.

I hope this helps.

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

Catch KeyError in Python

Try print(e.message) this should be able to print your exception.

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print(e.message)

What is managed or unmanaged code in programming?

  • Managed Code: code written in .NET language like C#, VB.NET.
  • UnManaged Code: code not written in .NET language and MSIL does not understand what it is and can not run under CLR; like third-party controls we used in our .NET applications which is not created in .NET languages.

jQuery animate scroll

There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.

JavaScript: how to change form action attribute value based on selection?

$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

Python 3 ImportError: No module named 'ConfigParser'

I run kali linux- Rolling and I came across this problem ,when I tried running cupp.py in the terminal, after updating to python 3.6.0. After some research and trial I found that changing ConfigParser to configparser worked for me but then I came across another issue.

config = configparser.configparser() AttributeError: module 'configparser' has no attribute 'configparser'

After a bit more research I realised that for python 3 ConfigParser is changed to configparser but note that it has an attribute ConfigParser().

HTML - Arabic Support

Won't you need the ensure the area where you display the Arabic is Right-to-Left orientated also?

e.g.

<p dir="rtl">

How to list files and folder in a dir (PHP)

use this function http://www.codingforums.com/showthread.php?t=71882

function getDirectory( $path = '.', $level = 0 ){

$ignore = array( 'cgi-bin', '.', '..' ); 
// Directories to ignore when listing output. Many hosts 
// will deny PHP access to the cgi-bin. 

$dh = @opendir( $path ); 
// Open the directory to the handle $dh 

while( false !== ( $file = readdir( $dh ) ) ){ 
// Loop through the directory 

    if( !in_array( $file, $ignore ) ){ 
    // Check that this file is not to be ignored 

        $spaces = str_repeat( '&nbsp;', ( $level * 4 ) ); 
        // Just to add spacing to the list, to better 
        // show the directory tree. 

        if( is_dir( "$path/$file" ) ){ 
        // Its a directory, so we need to keep reading down... 

            echo "<strong>$spaces $file</strong><br />"; 
            getDirectory( "$path/$file", ($level+1) ); 
            // Re-call this same function but on a new directory. 
            // this is what makes function recursive. 

        } else { 

            echo "$spaces $file<br />"; 
            // Just print out the filename 

        } 

    } 

} 

closedir( $dh ); 
// Close the directory handle 
}

and call the function like that

getDirectory( "." ); 
// Get the current directory 

getDirectory( "./files/includes" ); 
// Get contents of the "files/includes" folder 

How do I make a list of data frames?

This isn't related to your question, but you want to use = and not <- within the function call. If you use <-, you'll end up creating variables y1 and y2 in whatever environment you're working in:

d1 <- data.frame(y1 <- c(1, 2, 3), y2 <- c(4, 5, 6))
y1
# [1] 1 2 3
y2
# [1] 4 5 6

This won't have the seemingly desired effect of creating column names in the data frame:

d1
#   y1....c.1..2..3. y2....c.4..5..6.
# 1                1                4
# 2                2                5
# 3                3                6

The = operator, on the other hand, will associate your vectors with arguments to data.frame.

As for your question, making a list of data frames is easy:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
my.list <- list(d1, d2)

You access the data frames just like you would access any other list element:

my.list[[1]]
#   y1 y2
# 1  1  4
# 2  2  5
# 3  3  6

How do I find an element that contains specific text in Selenium WebDriver (Python)?

//* will be looking for any HTML tag. Where if some text is common for Button and div tag and if //* is categories it will not work as expected. If you need to select any specific then You can get it by declaring HTML Element tag. Like:

driver.find_element_by_xpath("//div[contains(text(),'Add User')]")
driver.find_element_by_xpath("//button[contains(text(),'Add User')]")

How to cast a double to an int in Java by rounding it down?

(int)99.99999

It will be 99. Casting a double to an int does not round, it'll discard the fraction part.

updating table rows in postgres using subquery

Postgres allows:

UPDATE dummy
SET customer=subquery.customer,
    address=subquery.address,
    partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
      FROM  /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;

This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.

Is there a Google Chrome-only CSS hack?

To work only chrome or safari, try it:

@media screen and (-webkit-min-device-pixel-ratio:0) { 
/* Safari and Chrome */
.myClass {
 color:red;
}

/* Safari only override */
::i-block-chrome,.myClass {
 color:blue;
}}

What is a Python equivalent of PHP's var_dump()?

print

For your own classes, just def a __str__ method

Converting dd/mm/yyyy formatted string to Datetime

You can use "dd/MM/yyyy" format for using it in DateTime.ParseExact.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Here is a DEMO.

For more informations, check out Custom Date and Time Format Strings

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

Rails: How can I set default values in ActiveRecord?

# db/schema.rb
create_table :store_listings, force: true do |t|
  t.string :my_string, default: "original default"
end

StoreListing.new.my_string # => "original default"

# app/models/store_listing.rb
class StoreListing < ActiveRecord::Base
  attribute :my_string, :string, default: "new default"
end

StoreListing.new.my_string # => "new default"

class Product < ActiveRecord::Base
  attribute :my_default_proc, :datetime, default: -> { Time.now }
end

Product.new.my_default_proc # => 2015-05-30 11:04:48 -0600
sleep 1
Product.new.my_default_proc # => 2015-05-30 11:04:49 -0600

Is unsigned integer subtraction defined behavior?

Well, the first interpretation is correct. However, your reasoning about the "signed semantics" in this context is wrong.

Again, your first interpretation is correct. Unsigned arithmetic follow the rules of modulo arithmetic, meaning that 0x0000 - 0x0001 evaluates to 0xFFFF for 32-bit unsigned types.

However, the second interpretation (the one based on "signed semantics") is also required to produce the same result. I.e. even if you evaluate 0 - 1 in the domain of signed type and obtain -1 as the intermediate result, this -1 is still required to produce 0xFFFF when later it gets converted to unsigned type. Even if some platform uses an exotic representation for signed integers (1's complement, signed magnitude), this platform is still required to apply rules of modulo arithmetic when converting signed integer values to unsigned ones.

For example, this evaluation

signed int a = 0, b = 1;
unsigned int c = a - b;

is still guaranteed to produce UINT_MAX in c, even if the platform is using an exotic representation for signed integers.

In Python, how do I iterate over a dictionary in sorted key order?

A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.

sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but it is not in anyway a dict!

foo = {
    'a':    1,
    'b':    2,
    'c':    3,
    }

print foo
>>> {'a': 1, 'c': 3, 'b': 2}

print foo.items()
>>> [('a', 1), ('c', 3), ('b', 2)]

print sorted(foo.items())
>>> [('a', 1), ('b', 2), ('c', 3)]

The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:

for k,v in sorted(foo.items()):
    print k, v

Roughly equivalent to:

for k in sorted(foo.keys()):
    print k, foo[k]

How do you parse and process HTML/XML in PHP?

Yes you can use simple_html_dom for the purpose. However I have worked quite a lot with the simple_html_dom, particularly for web scraping and have found it to be too vulnerable. It does the basic job but I won't recommend it anyways.

I have never used curl for the purpose but what I have learned is that curl can do the job much more efficiently and is much more solid.

Kindly check out this link:scraping-websites-with-curl

How do I clone a generic list in C#?

You can use an extension method.

static class Extensions
{
    public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
    {
        return listToClone.Select(item => (T)item.Clone()).ToList();
    }
}