Programs & Examples On #Partial functions

no module named zlib

My objective was to create a new Django project from the command line in Ubuntu, like so:

django-admin.py startproject mysite

I have python2.7.5 installed. I got this error:

ImportError: No module named zlib

For hours I could not find a solution, until now!

Here is a link to the solution -

http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian

I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text 

Find the last time table was updated

If you want to see data updates you could use this technique with required permissions:

SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DATABASE')
AND OBJECT_ID=OBJECT_ID('TABLE')

How to detect if a string contains at least a number?

DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'

IF PATINDEX('%[0-9]%', @str) > 0
   PRINT 'YES, The string has numbers'
ELSE
   PRINT 'NO, The string does not have numbers' 

How to import the class within the same directory or sub directory?

If you have filename.py in the same folder, you can easily import it like this:

import filename

I am using python3.7

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

How do I compute derivative using Numpy?

Assuming you want to use numpy, you can numerically compute the derivative of a function at any point using the Rigorous definition:

def d_fun(x):
    h = 1e-5 #in theory h is an infinitesimal
    return (fun(x+h)-fun(x))/h

You can also use the Symmetric derivative for better results:

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Using your example, the full code should look something like:

def fun(x):
    return x**2 + 1

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Now, you can numerically find the derivative at x=5:

In [1]: d_fun(5)
Out[1]: 9.999999999621423

How to put Google Maps V2 on a Fragment using ViewPager

public class DemoFragment extends Fragment {


MapView mapView;
GoogleMap map;
LatLng CENTER = null;

public LocationManager locationManager;

double longitudeDouble;
double latitudeDouble;

String snippet;
String title;
Location location;
String myAddress;

String LocationId;
String CityName;
String imageURL;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater
                .inflate(R.layout.fragment_layout, container, false);

    mapView = (MapView) view.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

  setMapView();


 }

 private void setMapView() {
    try {
        MapsInitializer.initialize(getActivity());

        switch (GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getActivity())) {
        case ConnectionResult.SUCCESS:
            // Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
            // .show();

            // Gets to GoogleMap from the MapView and does initialization
            // stuff
            if (mapView != null) {

                locationManager = ((LocationManager) getActivity()
                        .getSystemService(Context.LOCATION_SERVICE));

                Boolean localBoolean = Boolean.valueOf(locationManager
                        .isProviderEnabled("network"));

                if (localBoolean.booleanValue()) {

                    CENTER = new LatLng(latitude, longitude);

                } else {

                }
                map = mapView.getMap();
                if (map == null) {

                    Log.d("", "Map Fragment Not Found or no Map in it!!");

                }

                map.clear();
                try {
                    map.addMarker(new MarkerOptions().position(CENTER)
                            .title(CityName).snippet(""));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                map.setIndoorEnabled(true);
                map.setMyLocationEnabled(true);
                map.moveCamera(CameraUpdateFactory.zoomTo(5));
                if (CENTER != null) {
                    map.animateCamera(
                            CameraUpdateFactory.newLatLng(CENTER), 1750,
                            null);
                }
                // add circle
                CircleOptions circle = new CircleOptions();
                circle.center(CENTER).fillColor(Color.BLUE).radius(10);
                map.addCircle(circle);
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

            }
            break;
        case ConnectionResult.SERVICE_MISSING:

            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:

            break;
        default:

        }
    } catch (Exception e) {

    }

}

in fragment_layout

<com.google.android.gms.maps.MapView
                android:id="@+id/mapView"
                android:layout_width="match_parent"
                android:layout_height="160dp"                    
                android:layout_marginRight="10dp" />

Split (explode) pandas dataframe string entry to separate rows

I have come up with the following solution to this problem:

def iter_var1(d):
    for _, row in d.iterrows():
        for v in row["var1"].split(","):
            yield (v, row["var2"])

new_a = DataFrame.from_records([i for i in iter_var1(a)],
        columns=["var1", "var2"])

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]

How to lose margin/padding in UITextView?

In case you want to set a HTML string and avoid the bottom padding, please make sure that you are not using block tags i.e. div, p.

In my case this was the reason. You can easily test it out by replacing occurrences of block tags with i.e. span tag.

Should I test private methods or only public ones?

Yes I do test private functions, because although they are tested by your public methods, it is nice in TDD (Test Driven Design) to test the smallest part of the application. But private functions are not accessible when you are in your test unit class. Here's what we do to test our private methods.

Why do we have private methods?

Private functions mainly exists in our class because we want to create readable code in our public methods. We do not want the user of this class to call these methods directly, but through our public methods. Also, we do not want change their behavior when extending the class (in case of protected), hence it's a private.

When we code, we use test-driven-design (TDD). This means that sometimes we stumble on a piece of functionality that is private and want to test. Private functions are not testable in phpUnit, because we cannot access them in the Test class (they are private).

We think here are 3 solutions:

1. You can test your privates through your public methods

Advantages

  • Straightforward unit testing (no 'hacks' needed)

Disadvantages

  • Programmer needs to understand the public method, while he only wants to test the private method
  • You are not testing the smallest testable part of the application

2. If the private is so important, then maybe it is a codesmell to create a new separate class for it

Advantages

  • You can refactor this to a new class, because if it is that important, other classes may need it too
  • The testable unit is now a public method, so testable

Disadvantages

  • You dont want to create a class if it is not needed, and only used by the class where the method is coming from
  • Potential performance loss because of added overhead

3. Change the access modifier to (final) protected

Advantages

  • You are testing the smallest testable part of the application. When using final protected, the function will not be overridable (just like a private)
  • No performance loss
  • No extra overhead

Disadvantages

  • You are changing a private access to protected, which means it's accessible by it's children
  • You still need a Mock class in your test class to use it

Example

class Detective {
  public function investigate() {}
  private function sleepWithSuspect($suspect) {}
}
Altered version:
class Detective {
  public function investigate() {}
  final protected function sleepWithSuspect($suspect) {}
}
In Test class:
class Mock_Detective extends Detective {

  public test_sleepWithSuspect($suspect) 
  {
    //this is now accessible, but still not overridable!
    $this->sleepWithSuspect($suspect);
  }
}

So our test unit can now call test_sleepWithSuspect to test our former private function.

Regex for string not ending with given suffix

Use the not (^) symbol:

.*[^a]$

If you put the ^ symbol at the beginning of brackets, it means "everything except the things in the brackets." $ is simply an anchor to the end.

For multiple characters, just put them all in their own character set:

.*[^a][^b]$

How to change the icon of .bat file programmatically?

You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon. Hope this help.

To set an icon of a shortcut programmatically, see this article using SetIconLocation:

How Can I Change the Icon for an Existing Shortcut?:

https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/

Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save

Selecting a row of pandas series/dataframe by integer index

The primary purpose of the DataFrame indexing operator, [] is to select columns.

When the indexing operator is passed a string or integer, it attempts to find a column with that particular name and return it as a Series.

So, in the question above: df[2] searches for a column name matching the integer value 2. This column does not exist and a KeyError is raised.


The DataFrame indexing operator completely changes behavior to select rows when slice notation is used

Strangely, when given a slice, the DataFrame indexing operator selects rows and can do so by integer location or by index label.

df[2:3]

This will slice beginning from the row with integer location 2 up to 3, exclusive of the last element. So, just a single row. The following selects rows beginning at integer location 6 up to but not including 20 by every third row.

df[6:20:3]

You can also use slices consisting of string labels if your DataFrame index has strings in it. For more details, see this solution on .iloc vs .loc.

I almost never use this slice notation with the indexing operator as its not explicit and hardly ever used. When slicing by rows, stick with .loc/.iloc.

A process crashed in windows .. Crash dump location

a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).

If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP

How do I get my Python program to sleep for 50 milliseconds?

You can also use pyautogui as:

import pyautogui
pyautogui._autoPause(0.05, False)

If the first argument is not None, then it will pause for first argument's seconds, in this example: 0.05 seconds

If the first argument is None, and the second argument is True, then it will sleep for the global pause setting which is set with:

pyautogui.PAUSE = int

If you are wondering about the reason, see the source code:

def _autoPause(pause, _pause):
    """If `pause` is not `None`, then sleep for `pause` seconds.
    If `_pause` is `True`, then sleep for `PAUSE` seconds (the global pause setting).

    This function is called at the end of all of PyAutoGUI's mouse and keyboard functions. Normally, `_pause`
    is set to `True` to add a short sleep so that the user can engage the failsafe. By default, this sleep
    is as long as `PAUSE` settings. However, this can be override by setting `pause`, in which case the sleep
    is as long as `pause` seconds.
    """
    if pause is not None:
        time.sleep(pause)
    elif _pause:
        assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
        time.sleep(PAUSE)

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

Open Google Chrome from VBA/Excel

You can use the following vba code and input them into standard module in excel. A list of websites can be entered and should be entered like this on cell A1 in Excel - www.stackoverflow.com

ActiveSheet.Cells(1,2).Value merely takes the number of website links that you have on cell B1 in Excel and will loop the code again and again based on number of website links you have placed on the sheet. Therefore Chrome will open up a new tab for each website link.

I hope this helps with the dynamic website you have got.

Sub multiplechrome()

    Dim WebUrl As String
    Dim i As Integer

    For i = 1 To ActiveSheet.Cells(1, 2).Value
        WebUrl = "http://" & Cells(i, 1).Value & """"
        Shell ("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -url " & WebUrl)

    Next
End Sub

curl POST format for CURLOPT_POSTFIELDS

It depends on the content-type

url-encoded or multipart/form-data

To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

JSON encoding

Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.

In such cases, content must be explicitely encoded as JSON :

CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),

When communicating in JSON, we also usually set accept and content-type headers accordingly:

CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]

How to set up fixed width for <td>?

use .something without td or th

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title> _x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  _x000D_
  <style>_x000D_
    .something {_x000D_
      width: 90px;_x000D_
      background: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Fixed width column</h2>            _x000D_
  <table class="table table-bordered">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th class="something">Firstname</th>_x000D_
        <th>Lastname</th>_x000D_
        <th>Email</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>John</td>_x000D_
        <td>Doe</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Mary</td>_x000D_
        <td>Moe</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>July</td>_x000D_
        <td>Dooley</td>_x000D_
        <td>[email protected]</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Counting the number of option tags in a select tag in jQuery

The best form is this

$('#example option').length

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

View's getWidth() and getHeight() returns 0

One liner if you are using RxJava & RxBindings. Similar approach without the boilerplate. This also solves the hack to suppress warnings as in the answer by Tim Autin.

RxView.layoutChanges(yourView).take(1)
      .subscribe(aVoid -> {
           // width and height have been calculated here
      });

This is it. No need to be unsubscribe, even if never called.

android get real path by Uri.getPath()

Note This is an improvement in @user3516549 answer and I have check it on Moto G3 with Android 6.0.1
I have this issue so I have tried answer of @user3516549 but in some cases it was not working properly. I have found that in Android 6.0(or above) when we start gallery image pick intent then a screen will open that shows recent images when user select image from this list we will get uri as

content://com.android.providers.media.documents/document/image%3A52530

while if user select gallery from sliding drawer instead of recent then we will get uri as

content://media/external/images/media/52530

So I have handle it in getRealPathFromURI_API19()

public static String getRealPathFromURI_API19(Context context, Uri uri) {
        String filePath = "";
        if (uri.getHost().contains("com.android.providers.media")) {
            // Image pick from recent 
            String wholeID = DocumentsContract.getDocumentId(uri);

            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];

            String[] column = {MediaStore.Images.Media.DATA};

            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";

            Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[]{id}, null);

            int columnIndex = cursor.getColumnIndex(column[0]);

            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }
            cursor.close();
            return filePath;
        } else {
            // image pick from gallery 
           return  getRealPathFromURI_BelowAPI11(context,uri)
        }

    }

EDIT1 : if you are trying to get image path of file in external sdcard in higher version then check my question

EDIT2 Here is complete code with handling virtual files and host other than com.android.providers I have tested this method with content://com.adobe.scan.android.documents/document/

Could not resolve all dependencies for configuration ':classpath'

I got the same problem. Just use File->INVALIDATE CACHES AND RESTART

Should I use scipy.pi, numpy.pi, or math.pi?

>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True

So it doesn't matter, they are all the same value.

The only reason all three modules provide a pi value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.

How do you get the file size in C#?

MSDN FileInfo.Length says that it is "the size of the current file in bytes."

My typical Google search for something like this is: msdn FileInfo

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

MongoError: connect ECONNREFUSED 127.0.0.1:27017

I had the same issue on Windows.

Ctrl+C to close mongod, and start mongod again.

Am not sure, but it seems that initially mongod was working opening and closing connections. Then, it was not able to close some earlier connections and reached limit for opened ones. After restarting mongod, it works again.

Python 3 sort a dict by its values

itemgetter (see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.get wins. And it does not require an extra import.

>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
...     k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)

Note that alternatively you can set d.__getitem__ as key function which may provide a small performance boost over d.get.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Insert picture into Excel cell

While my recommendation is to take advantage of the automation available from Doality.com specifically Picture Manager for Excel

The following vba code should meet your criteria. Good Luck!

Add a Button Control to your Excel Workbook and then double click on the button in order to get to the VBA Code -->

Sub Button1_Click()
    Dim filePathCell As Range
    Dim imageLocationCell As Range
    Dim filePath As String

    Set filePathCell = Application.InputBox(Prompt:= _
        "Please select the cell that contains the reference path to your image file", _
            Title:="Specify File Path", Type:=8)

     Set imageLocationCell = Application.InputBox(Prompt:= _
        "Please select the cell where you would like your image to be inserted.", _
            Title:="Image Cell", Type:=8)

    If filePathCell Is Nothing Then
       MsgBox ("Please make a selection for file path")
       Exit Sub
    Else
      If filePathCell.Cells.Count > 1 Then
        MsgBox ("Please select only a single cell that contains the file location")
        Exit Sub
      Else
        filePath = Cells(filePathCell.Row, filePathCell.Column).Value
      End If
    End If

    If imageLocationCell Is Nothing Then
       MsgBox ("Please make a selection for image location")
       Exit Sub
    Else
      If imageLocationCell.Cells.Count > 1 Then
        MsgBox ("Please select only a single cell where you want the image to be populated")
        Exit Sub
      Else
        InsertPic filePath, imageLocationCell
        Exit Sub
      End If
    End If
End Sub

Then create your Insert Method as follows:

Private Sub InsertPic(filePath As String, ByVal insertCell As Range)
    Dim xlShapes As Shapes
    Dim xlPic As Shape
    Dim xlWorksheet As Worksheet

    If IsEmpty(filePath) Or Len(Dir(filePath)) = 0 Then
        MsgBox ("File Path invalid")
        Exit Sub
    End If

    Set xlWorksheet = ActiveSheet

    Set xlPic = xlWorksheet.Shapes.AddPicture(filePath, msoFalse, msoCTrue, insertCell.top, insertCell.left, insertCell.width, insertCell.height)
    xlPic.LockAspectRatio = msoCTrue
End Sub

jQuery - Detect value change on hidden input field

Although this thread is 3 years old, here is my solution:

$(function ()
{
    keep_fields_uptodate();
});

function keep_fields_uptodate()
{
    // Keep all fields up to date!
    var $inputDate = $("input[type='date']");
    $inputDate.blur(function(event)
    {
        $("input").trigger("change");
    });
}

How to clear all <div>sā€™ contents inside a parent <div>?

try them if it help.

$('.div_parent .div_child').empty();

$('#div_parent #div_child').empty();

How to check if a string array contains one string in JavaScript?

This will do it for you:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle)
            return true;
    }
    return false;
}

I found it in Stack Overflow question JavaScript equivalent of PHP's in_array().

scikit-learn random state in splitting dataset

random_state is None by default which means every time when you run your program you will get different output because of splitting between train and test varies within.

random_state = any int value means every time when you run your program you will get tehe same output because of splitting between train and test does not varies within.

Permanently add a directory to PYTHONPATH?

If you're using bash (on a Mac or GNU/Linux distro), add this to your ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

Declare a const array

If you declare an array behind an IReadOnlyList interface you get a constant array with constant values that is declared at runtime:

public readonly IReadOnlyList<string> Titles = new [] {"German", "Spanish", "Corrects", "Wrongs" };

Available in .NET 4.5 and higher.

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Try this to get value from select element by Element Name

$("select[name=elementnamehere]").val();

What do .c and .h file extensions mean to C?

Of course, there is nothing that says the extension of a header file must be .h and the extension of a C source file must be .c. These are useful conventions.

E:\Temp> type my.interface
#ifndef MY_INTERFACE_INCLUDED
#define MYBUFFERSIZE 8
#define MY_INTERFACE_INCLUDED
#endif

E:\Temp> type my.source
#include <stdio.h>

#include "my.interface"

int main(void) {
    char x[MYBUFFERSIZE] = {0};
    x[0] = 'a';
    puts(x);
    return 0;
}

E:\Temp> gcc -x c my.source -o my.exe

E:\Temp> my
a

DIV table colspan: how?

In order to get "colspan" functionality out of div based tabular layout, you need to abandon the use of the display:table | display:row styles. Especially in cases where each data item spans more than one row and you need different sized "cells" in each row.

How to pass parameters on onChange of html select

You can try bellow code

<select onchange="myfunction($(this).val())" id="myId">
    </select>

Using DataContractSerializer to serialize, but can't deserialize back

Here is how I've always done it:

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

It could be related with your Java version. Go ahead and download the Database version which includes Java.

However, if you are configuring a local development workstation I recommend you to download the Express Edition.

Here is the link: http://www.oracle.com/technetwork/products/express-edition/downloads/index-083047.html

or google this: OracleXE112_Win64

Good luck!

C# MessageBox dialog result

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)

Call to undefined function App\Http\Controllers\ [ function name ]

say you define the static getFactorial function inside a CodeController

then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.

CodeController::getFactorial($index);

----------------UPDATE----------------

To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.

to do that

create a folder inside app directory and name it as lib (you can put a name you like).

this folder to needs to be autoload to do that add app/lib to composer.json as below. and run the composer dumpautoload command.

"autoload": {
    "classmap": [
                "app/commands",
                "app/controllers",
                ............
                "app/lib"
    ]
},

then files inside lib will autoloaded.

then create a file inside lib, i name it helperFunctions.php

inside that define the function.

if ( ! function_exists('getFactorial'))
{

    /**
     * return the factorial of a number
     *
     * @param $number
     * @return string
     */
    function getFactorial($date)
    {
        $fact = 1;

        for($i = 1; $i <= $num ;$i++)
            $fact = $fact * $i;

        return $fact;

     }
}

and call it anywhere within the app as

$fatorial_value = getFactorial(225);

PHP - Merging two arrays into one array (also Remove Duplicates)

The best solution above faces a problem when using the same associative keys, array_merge() will merge array elements together when they have the same NON-NUMBER key, so it is not suitable for the following case

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("c"=>"red","d"=>"black","e"=>"green");

If you are able output your value to the keys of your arrays instead (e.g ->pluck('name', 'id')->toArray() in Eloquent), you can use the following merge method instead

array_keys(array_merge($a1, $a2))

Basically what the code does is it utilized the behavior of array_merge() to get rid of duplicated keys and return you a new array with keys as array elements, hope it helps

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

The total number of locks exceeds the lock table size

First, you can use sql command show global variables like 'innodb_buffer%'; to check the buffer size.

Solution is find your my.cnf file and add,

_x000D_
_x000D_
[mysqld]_x000D_
innodb_buffer_pool_size=1G # depends on your data and machine
_x000D_
_x000D_
_x000D_

DO NOT forget to add [mysqld], otherwise, it won't work.

In my case, ubuntu 16.04, my.cnf is located under the folder /etc/mysql/.

Insert Data Into Temp Table with Query

This is possible. Try this way:

Create Global Temporary Table 
BossaDoSamba 
On Commit Preserve Rows 
As 
select ArtistName, sum(Songs) As NumberOfSongs 
 from Spotfy 
    where ArtistName = 'BossaDoSamba'
 group by ArtistName;

How to view the dependency tree of a given npm module?

To get it as a list:

% npx npm-remote-ls --flatten dugite -d false -o false
[
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '@szmarczak/[email protected]',
  '[email protected]',
  '@sindresorhus/[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]'
]

How to link home brew python version and set it as default

If you used

brew install python

before 'unlink' you got

brew info python
/usr/local/Cellar/python/2.7.11

python -V
Python 2.7.10

so do

brew unlink python && brew link python

and open a new terminal shell

python -V
Python 2.7.11

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

Set a button group's width to 100% and make buttons equal width?

There's no need for extra css the .btn-group-justified class does this.

You have to add this to the parent element and then wrap each btn element in a div with .btn-group like this

    <div class="form-group">

            <div class="btn-group btn-group-justified">
                <div class="btn-group">
                    <button type="submit" id="like" class="btn btn-lg btn-success ">Like</button>
                </div>
                <div class="btn-group">
                    <button type="submit" id="nope" class="btn btn-lg btn-danger ">Nope</button>
                </div>
            </div>

        </div>

Why java.security.NoSuchProviderException No such provider: BC?

Im not very familiar with the Android sdk, but it seems that the android-sdk comes with the BouncyCastle provider already added to the security.

What you will have to do in the PC environment is just add it manually,

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

if you have access to the policy file, just add an entry like:

security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider 

Notice the .5 it is equal to a sequential number of the already added providers.

How do you get a list of the names of all files present in a directory in Node.js?

Here's an asynchronous recursive version.

    function ( path, callback){
     // the callback gets ( err, files) where files is an array of file names
     if( typeof callback !== 'function' ) return
     var
      result = []
      , files = [ path.replace( /\/\s*$/, '' ) ]
     function traverseFiles (){
      if( files.length ) {
       var name = files.shift()
       fs.stat(name, function( err, stats){
        if( err ){
         if( err.errno == 34 ) traverseFiles()
    // in case there's broken symbolic links or a bad path
    // skip file instead of sending error
         else callback(err)
        }
        else if ( stats.isDirectory() ) fs.readdir( name, function( err, files2 ){
         if( err ) callback(err)
         else {
          files = files2
           .map( function( file ){ return name + '/' + file } )
           .concat( files )
          traverseFiles()
         }
        })
        else{
         result.push(name)
         traverseFiles()
        }
       })
      }
      else callback( null, result )
     }
     traverseFiles()
    }

Should I always use a parallel stream when possible?

A parallel stream has a much higher overhead compared to a sequential one. Coordinating the threads takes a significant amount of time. I would use sequential streams by default and only consider parallel ones if

  • I have a massive amount of items to process (or the processing of each item takes time and is parallelizable)

  • I have a performance problem in the first place

  • I don't already run the process in a multi-thread environment (for example: in a web container, if I already have many requests to process in parallel, adding an additional layer of parallelism inside each request could have more negative than positive effects)

In your example, the performance will anyway be driven by the synchronized access to System.out.println(), and making this process parallel will have no effect, or even a negative one.

Moreover, remember that parallel streams don't magically solve all the synchronization problems. If a shared resource is used by the predicates and functions used in the process, you'll have to make sure that everything is thread-safe. In particular, side effects are things you really have to worry about if you go parallel.

In any case, measure, don't guess! Only a measurement will tell you if the parallelism is worth it or not.

How to pass multiple parameters in a querystring

~mypage.aspx?strID=x&strName=y&strDate=z

Get DOM content of cross-domain iframe

There's a workaround to achieve it.

  1. First, bind your iframe to a target page with relative url. The browsers will treat the site in iframe the same domain with your website.

  2. In your web server, using a rewrite module to redirect request from the relative url to absolute url. If you use IIS, I recommend you check on IIRF module.

What is the max size of localStorage values?

Find the maximum length of a single string that can be stored in localStorage

This snippet will find the maximum length of a String that can be stored in localStorage per domain.

//Clear localStorage
for (var item in localStorage) delete localStorage[item];

window.result = window.result || document.getElementById('result');

result.textContent = 'Test runningā€¦';

//Start test
//Defer running so DOM can be updated with "test running" message
setTimeout(function () {

    //Variables
    var low = 0,
        high = 2e9,
        half;

    //Two billion may be a little low as a starting point, so increase if necessary
    while (canStore(high)) high *= 2;


    //Keep refining until low and high are equal
    while (low !== high) {
        half = Math.floor((high - low) / 2 + low);

        //Check if we can't scale down any further
        if (low === half || high === half) {
            console.info(low, high, half);
            //Set low to the maximum possible amount that can be stored 
            low = canStore(high) ? high : low;
            high = low;
            break;
        }


        //Check if the maximum storage is no higher than half
        if (storageMaxBetween(low, half)) {
            high = half;
            //The only other possibility is that it's higher than half but not higher than "high"
        } else {
            low = half + 1;
        }

    }

    //Show the result we found!
    result.innerHTML = 'The maximum length of a string that can be stored in localStorage is <strong>' + low + '</strong> characters.';

    //Functions
    function canStore(strLen) {
        try {
            delete localStorage.foo;
            localStorage.foo = Array(strLen + 1).join('A');
            return true;
        } catch (ex) {
            return false;
        }
    }


    function storageMaxBetween(low, high) {
        return canStore(low) && !canStore(high);
    }

}, 0);
<h1>LocalStorage single value max length test</h1>

<div id='result'>Please enable JavaScript</div>

Note that the length of a string is limited in JavaScript; if you want to view the maximum amount of data that can be stored in localStorage when not limited to a single string, you can use the code in this answer.

Edit: Stack Snippets don't support localStorage, so here is a link to JSFiddle.

Results

Chrome (45.0.2454.101): 5242878 characters
Firefox (40.0.1): 5242883 characters
Internet Explorer (11.0.9600.18036): 16386 122066 122070 characters

I get different results on each run in Internet Explorer.

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

called_from must be null. Add a test against that condition like

if (called_from != null && called_from.equalsIgnoreCase("add")) {

or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)

if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null

How can I deploy an iPhone application from Xcode to a real iPhone device?

Solution posted by Cawas works perfectly with XCode4, too. However, there are some changes to IDE's UI, so you need to make some research to find Run Script :)

In the Project Navigator view click the root item of the project, then in the middle window select Target, then click Build Phases tab and at the bottom you'll see Add Build Phase button, click and select Add Run Script, then paste "codesign" script posted by Cawas.

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

Unix command to check the filesize

You can use:ls -lh, then you will get a list of file information

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

Multi-dimensional arrays in Bash

I do this using associative arrays since bash 4 and setting IFS to a value that can be defined manually.

The purpose of this approach is to have arrays as values of associative array keys.

In order to set IFS back to default just unset it.

  • unset IFS

This is an example:

#!/bin/bash

set -euo pipefail

# used as value in asscciative array
test=(
  "x3:x4:x5"
)
# associative array
declare -A wow=(
  ["1"]=$test
  ["2"]=$test
)
echo "default IFS"
for w in ${wow[@]}; do
  echo "  $w"
done

IFS=:
echo "IFS=:"
for w in ${wow[@]}; do
  for t in $w; do
    echo "  $t"
  done
done
echo -e "\n or\n"
for w in ${!wow[@]}
do
  echo "  $w"
  for t in ${wow[$w]}
  do
    echo "    $t"
  done
done

unset IFS
unset w
unset t
unset wow
unset test

The output of the script below is:

default IFS
  x3:x4:x5
  x3:x4:x5
IFS=:
  x3
  x4
  x5
  x3
  x4
  x5

 or

  1
    x3
    x4
    x5
  2
    x3
    x4
    x5

Is there a difference between PhoneGap and Cordova commands?

Late answer but I think this might be useful.

There are differences between the two cli, phonegapis a command that encapsulates cordova. In the create case the only difference is an overriden default app

In some other cases the difference is much more significant. For instance phonegap build comes with a remote build functionality while cordova build only supports local builds.

A big limitation I found to PhoneGap is that, AFAIK, you can only build a release APK using the PhoneGap Build service. On Cordova you can build with cordova build android --release.

How to run a cron job inside a docker container?

What @VonC has suggested is nice but I prefer doing all cron job configuration in one line. This would avoid cross platform issues like cronjob location and you don't need a separate cron file.

FROM ubuntu:latest

# Install cron
RUN apt-get -y install cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Setup cron job
RUN (crontab -l ; echo "* * * * * echo "Hello world" >> /var/log/cron.log") | crontab

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log

After running your docker container, you can make sure if cron service is working by:

# To check if the job is scheduled
docker exec -ti <your-container-id> bash -c "crontab -l"
# To check if the cron service is running
docker exec -ti <your-container-id> bash -c "pgrep cron"

If you prefer to have ENTRYPOINT instead of CMD, then you can substitute the CMD above with

ENTRYPOINT cron start && tail -f /var/log/cron.log

Simultaneously merge multiple data.frames in a list

Another question asked specifically how to perform multiple left joins using dplyr in R . The question was marked as a duplicate of this one so I answer here, using the 3 sample data frames below:

x <- data.frame(i = c("a","b","c"), j = 1:3, stringsAsFactors=FALSE)
y <- data.frame(i = c("b","c","d"), k = 4:6, stringsAsFactors=FALSE)
z <- data.frame(i = c("c","d","a"), l = 7:9, stringsAsFactors=FALSE)

Update June 2018: I divided the answer in three sections representing three different ways to perform the merge. You probably want to use the purrr way if you are already using the tidyverse packages. For comparison purposes below, you'll find a base R version using the same sample dataset.


1) Join them with reduce from the purrr package:

The purrr package provides a reduce function which has a concise syntax:

library(tidyverse)
list(x, y, z) %>% reduce(left_join, by = "i")
#  A tibble: 3 x 4
#  i       j     k     l
#  <chr> <int> <int> <int>
# 1 a      1    NA     9
# 2 b      2     4    NA
# 3 c      3     5     7

You can also perform other joins, such as a full_join or inner_join:

list(x, y, z) %>% reduce(full_join, by = "i")
# A tibble: 4 x 4
# i       j     k     l
# <chr> <int> <int> <int>
# 1 a     1     NA     9
# 2 b     2     4      NA
# 3 c     3     5      7
# 4 d     NA    6      8

list(x, y, z) %>% reduce(inner_join, by = "i")
# A tibble: 1 x 4
# i       j     k     l
# <chr> <int> <int> <int>
# 1 c     3     5     7

2) dplyr::left_join() with base R Reduce():

list(x,y,z) %>%
    Reduce(function(dtf1,dtf2) left_join(dtf1,dtf2,by="i"), .)

#   i j  k  l
# 1 a 1 NA  9
# 2 b 2  4 NA
# 3 c 3  5  7

3) Base R merge() with base R Reduce():

And for comparison purposes, here is a base R version of the left join based on Charles's answer.

 Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "i", all.x = TRUE),
        list(x,y,z))
#   i j  k  l
# 1 a 1 NA  9
# 2 b 2  4 NA
# 3 c 3  5  7

Regex to replace multiple spaces with a single space

Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)

_x000D_
_x000D_
var str="The dog      has a long   tail, and it     is RED!";
var rule=/\s{1,}/g;

str = str.split(rule).join(" "); 

document.write(str);
_x000D_
_x000D_
_x000D_

How to generate keyboard events?

It can be done using ctypes:

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# msdn.microsoft.com/en-us/library/dd375731
VK_TAB  = 0x09
VK_MENU = 0x12

# C struct definitions

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

# Functions

def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def AltTab():
    """Press Alt+Tab and hold Alt key for 2 seconds
    in order to see the overlay.
    """
    PressKey(VK_MENU)   # Alt
    PressKey(VK_TAB)    # Tab
    ReleaseKey(VK_TAB)  # Tab~
    time.sleep(2)
    ReleaseKey(VK_MENU) # Alt~

if __name__ == "__main__":
    AltTab()

hexKeyCode is the virtual keyboard mapping as defined by the Windows API. The list of codes is available on MSDN: Virtual-Key Codes (Windows)

Strange Characters in database text: ƃ, ƃ, Ā¢, Ć¢ā€š ā‚¬,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

How is __eq__ handled in Python and in what order?

I'm writing an updated answer for Python 3 to this question.

How is __eq__ handled in Python and in what order?

a == b

It is generally understood, but not always the case, that a == b invokes a.__eq__(b), or type(a).__eq__(a, b).

Explicitly, the order of evaluation is:

  1. if b's type is a strict subclass (not the same type) of a's type and has an __eq__, call it and return the value if the comparison is implemented,
  2. else, if a has __eq__, call it and return it if the comparison is implemented,
  3. else, see if we didn't call b's __eq__ and it has it, then call and return it if the comparison is implemented,
  4. else, finally, do the comparison for identity, the same comparison as is.

We know if a comparison isn't implemented if the method returns NotImplemented.

(In Python 2, there was a __cmp__ method that was looked for, but it was deprecated and removed in Python 3.)

Let's test the first check's behavior for ourselves by letting B subclass A, which shows that the accepted answer is wrong on this count:

class A:
    value = 3
    def __eq__(self, other):
        print('A __eq__ called')
        return self.value == other.value

class B(A):
    value = 4
    def __eq__(self, other):
        print('B __eq__ called')
        return self.value == other.value

a, b = A(), B()
a == b

which only prints B __eq__ called before returning False.

How do we know this full algorithm?

The other answers here seem incomplete and out of date, so I'm going to update the information and show you how how you could look this up for yourself.

This is handled at the C level.

We need to look at two different bits of code here - the default __eq__ for objects of class object, and the code that looks up and calls the __eq__ method regardless of whether it uses the default __eq__ or a custom one.

Default __eq__

Looking __eq__ up in the relevant C api docs shows us that __eq__ is handled by tp_richcompare - which in the "object" type definition in cpython/Objects/typeobject.c is defined in object_richcompare for case Py_EQ:.

    case Py_EQ:
        /* Return NotImplemented instead of False, so if two
           objects are compared, both get a chance at the
           comparison.  See issue #1393. */
        res = (self == other) ? Py_True : Py_NotImplemented;
        Py_INCREF(res);
        break;

So here, if self == other we return True, else we return the NotImplemented object. This is the default behavior for any subclass of object that does not implement its own __eq__ method.

How __eq__ gets called

Then we find the C API docs, the PyObject_RichCompare function, which calls do_richcompare.

Then we see that the tp_richcompare function, created for the "object" C definition is called by do_richcompare, so let's look at that a little more closely.

The first check in this function is for the conditions the objects being compared:

  • are not the same type, but
  • the second's type is a subclass of the first's type, and
  • the second's type has an __eq__ method,

then call the other's method with the arguments swapped, returning the value if implemented. If that method isn't implemented, we continue...

    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        checked_reverse_op = 1;
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Next we see if we can lookup the __eq__ method from the first type and call it. As long as the result is not NotImplemented, that is, it is implemented, we return it.

    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
        res = (*f)(v, w, op);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);

Else if we didn't try the other type's method and it's there, we then try it, and if the comparison is implemented, we return it.

    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
        res = (*f)(w, v, _Py_SwappedOp[op]);
        if (res != Py_NotImplemented)
            return res;
        Py_DECREF(res);
    }

Finally, we get a fallback in case it isn't implemented for either one's type.

The fallback checks for the identity of the object, that is, whether it is the same object at the same place in memory - this is the same check as for self is other:

    /* If neither object implements it, provide a sensible default
       for == and !=, but raise an exception for ordering. */
    switch (op) {
    case Py_EQ:
        res = (v == w) ? Py_True : Py_False;
        break;

Conclusion

In a comparison, we respect the subclass implementation of comparison first.

Then we attempt the comparison with the first object's implementation, then with the second's if it wasn't called.

Finally we use a test for identity for comparison for equality.

Convert date time string to epoch in Bash

Just be sure what timezone you want to use.

datetime="06/12/2012 07:21:22"

Most popular use takes machine timezone.

date -d "$datetime" +"%s" #depends on local timezone, my output = "1339456882"

But in case you intentionally want to pass UTC datetime and you want proper timezone you need to add -u flag. Otherwise you convert it from your local timezone.

date -u -d "$datetime" +"%s" #general output = "1339485682"

md-table - How to update the column width

I found a combination of jymdman's and Rahul Patil's answers is working best for me:

.mat-column-userId {
  flex: 0 0 75px;
}

Also, if you have one "leading" column which you want to always occupy a certain amount of space across different devices, I found the following quite handy to adopt to the available container width in a more responsive kind (this forces the remaining columns to use the remaining space evenly):

.mat-column-userName {
  flex: 0 0 60%;
}

Decimal to Hexadecimal Converter in Java

Here's mine

public static String dec2Hex(int num)
{
    String hex = "";

    while (num != 0)
    {
        if (num % 16 < 10)
            hex = Integer.toString(num % 16) + hex;
        else
            hex = (char)((num % 16)+55) + hex;
        num = num / 16;
    }

    return hex;
}

Programmatically saving image to Django ImageField

So, if you have a model with an imagefield with an upload_to attribute set, such as:

class Avatar(models.Model):
    image_file = models.ImageField(upload_to=user_directory_path_avatar)

then it is reasonably easy to change the image, at least in django 3.15.

In the view, when you process the image, you can obtain the image from:

self.request.FILES['avatar']

which is an instance of type InMemoryUploadedFile, as long as your html form has the enctype set and a field for avatar...

    <form method="post" class="avatarform" id="avatarform" action="{% url avatar_update_view' %}" enctype="multipart/form-data">
         {% csrf_token %}
         <input id="avatarUpload" class="d-none" type="file" name="avatar">
    </form>

Then, setting the new image in the view is as easy as the following (where profile is the profile model for the self.request.user)

profile.avatar.image_file.save(self.request.FILES['avatar'].name, self.request.FILES['avatar'])

There is no need to save the profile.avatar, the image_field already saves, and into the correct location because of the 'upload_to' callback function.

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Download it from here:

http://www.iis.net/downloads/microsoft/url-rewrite

or if you already have Web Platform Installer on your machine you can install it from there.

How can I change the color of my prompt in zsh (different from normal text)?

man zshall and search for PROMPT EXPANSION

After reading the existing answers here, several of them are conflicting. I've tried the various approaches on systems running zsh 4.2 and 5+ and found that the reason these answers are conflicting is that they do not say which version of ZSH they are targeted at. Different versions use different syntax for this and some of them require various autoloads.

So, the best bet is probably to man zshall and search for PROMPT EXPANSION to find out all the rules for your particular installation of zsh. Note in the comments, things like "I use Ubuntu 11.04 or 10.4 or OSX" Are not very meaningful as it's unclear which version of ZSH you are using. Ubuntu 11.04 does not imply a newer version of ZSH than ubuntu 10.04. There may be any number of reasons that an older version was installed. For that matter a newer version of ZSH does not imply which syntax to use without knowing which version of ZSH it is.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.

same example

...  ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
...  div collapse="isCollapsed"> ...

with

@media screen and (min-width: 768px) {
    .collapse{
        display: block !important;
    }
}

How to read and write xml files?

The answers only cover DOM / SAX and a copy paste implementation of a JAXB example.

However, one big area of when you are using XML is missing. In many projects / programs there is a need to store / retrieve some basic data structures. Your program has already a classes for your nice and shiny business objects / data structures, you just want a comfortable way to convert this data to a XML structure so you can do more magic on it (store, load, send, manipulate with XSLT).

This is where XStream shines. You simply annotate the classes holding your data, or if you do not want to change those classes, you configure a XStream instance for marshalling (objects -> xml) or unmarshalling (xml -> objects).

Internally XStream uses reflection, the readObject and readResolve methods of standard Java object serialization.

You get a good and speedy tutorial here:

To give a short overview of how it works, I also provide some sample code which marshalls and unmarshalls a data structure. The marshalling / unmarshalling happens all in the main method, the rest is just code to generate some test objects and populate some data to them. It is super simple to configure the xStream instance and marshalling / unmarshalling is done with one line of code each.

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class XStreamIsGreat {

  public static void main(String[] args) {
    XStream xStream = new XStream();
    xStream.alias("good", Good.class);
    xStream.alias("pRoDuCeR", Producer.class);
    xStream.alias("customer", Customer.class);

    Producer a = new Producer("Apple");
    Producer s = new Producer("Samsung");
    Customer c = new Customer("Someone").add(new Good("S4", 10, new BigDecimal(600), s))
        .add(new Good("S4 mini", 5, new BigDecimal(450), s)).add(new Good("I5S", 3, new BigDecimal(875), a));
    String xml = xStream.toXML(c); // objects -> xml
    System.out.println("Marshalled:\n" + xml);
    Customer unmarshalledCustomer = (Customer)xStream.fromXML(xml); // xml -> objects
  }

  static class Good {
    Producer producer;

    String name;

    int quantity;

    BigDecimal price;

    Good(String name, int quantity, BigDecimal price, Producer p) {
      this.producer = p;
      this.name = name;
      this.quantity = quantity;
      this.price = price;
    }

  }

  static class Producer {
    String name;

    public Producer(String name) {
      this.name = name;
    }
  }

  static class Customer {
    String name;

    public Customer(String name) {
      this.name = name;
    }

    List<Good> stock = new ArrayList<Good>();

    Customer add(Good g) {
      stock.add(g);
      return this;
    }
  }
}

How to import Maven dependency in Android Studio/IntelliJ?

As of version 0.8.9, Android Studio supports the Maven Central Repository by default. So to add an external maven dependency all you need to do is edit the module's build.gradle file and insert a line into the dependencies section like this:

dependencies {

    // Remote binary dependency
    compile 'net.schmizz:sshj:0.10.0'

}

You will see a message appear like 'Sync now...' - click it and wait for the maven repo to be downloaded along with all of its dependencies. There will be some messages in the status bar at the bottom telling you what's happening regarding the download. After it finishes this, the imported JAR file along with its dependencies will be listed in the External Repositories tree in the Project Browser window, as shown below.

enter image description here

Some further explanations here: http://developer.android.com/sdk/installing/studio-build.html

Hide div after a few seconds

jquery offers a variety of methods to hide the div in a timed manner that do not require setting up and later clearing or resetting interval timers or other event handlers. Here are a few examples.

Pure hide, one second delay

// hide in one second
$('#mydiv').delay(1000).hide(0); 

Pure hide, no delay

// hide immediately
$('#mydiv').delay(0).hide(0); 

Animated hide

// start hide in one second, take 1/2 second for animated hide effect
$('#mydiv').delay(1000).hide(500); 

fade out

// start fade out in one second, take 300ms to fade
$('#mydiv').delay(1000).fadeOut(300); 

Additionally, the methods can take a queue name or function as a second parameter (depending on method). Documentation for all the calls above and other related calls can be found here: https://api.jquery.com/category/effects/

Check whether a table contains rows or not sql server 2005

FOR the best performance, use specific column name instead of * - for example:

SELECT TOP 1 <columnName> 
FROM <tableName> 

This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.

Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.

If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.

You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.

Why does multiplication repeats the number several times?

It's the difference between strings and integers. See:

>>> "1" * 9
'111111111'

>>> 1 * 9
9

how to set width for PdfPCell in ItextSharp

try this code I think it is more optimal.

HeaderRow is used to repeat the header of the table for each new page automatically

        BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
        iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

        PdfPTable table = new PdfPTable(10) { HorizontalAlignment = Element.ALIGN_CENTER, WidthPercentage = 100, HeaderRows = 2 };
        table.SetWidths(new float[] { 2f, 6f, 6f, 3f, 5f, 8f, 5f, 5f, 5f, 5f });
        table.AddCell(new PdfPCell(new Phrase("SER.\nNO.", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("TYPE OF SHIPPING", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("ORDER NO.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("QTY.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DISCHARGE PPORT", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DESCRIPTION OF GOODS", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("LINE DOC. RECL DATE", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("CLEARANCE DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("CUSTOM PERMIT NO.", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DISPATCH DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("AWB/BL NO.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("COMPLEX NAME", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("G. W. Kgs.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DESTINATION", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("OWNER DOC. RECL DATE", times)) { GrayFill = 0.95f });

Import XXX cannot be resolved for Java SE standard classes

If by chance you have deleted JRE SYSTEM LIBRARY, then go to your JRE installation and add jars from there.

Eg:- C:\Program Files (x86)\Java\jre7\lib ---add jars from here

C:\Program Files (x86)\Java\jre7\lib\ext ---add jars from here

shift a std_logic_vector of n bit to right or left

Personally, I think the concatenation is the better solution. The generic implementation would be

entity shifter is
    generic (
        REGSIZE  : integer := 8);
    port(
        clk      : in  str_logic;
        Data_in  : in  std_logic;
        Data_out : out std_logic(REGSIZE-1 downto 0);
end shifter ;

architecture bhv of shifter is
    signal shift_reg : std_logic_vector(REGSIZE-1 downto 0) := (others<='0');
begin
    process (clk) begin
        if rising_edge(clk) then
            shift_reg <= shift_reg(REGSIZE-2 downto 0) & Data_in;
        end if;
    end process;
end bhv;
Data_out <= shift_reg;

Both will implement as shift registers. If you find yourself in need of more shift registers than you are willing to spend resources on (EG dividing 1000 numbers by 4) you might consider using a BRAM to store the values and a single shift register to contain "indices" that result in the correct shift of all the numbers.

What are static factory methods?

Java implementation contains utilities classes java.util.Arrays and java.util.Collections both of them contains static factory methods, examples of it and how to use :

Also java.lang.String class have such static factory methods:

  • String.format(...), String.valueOf(..), String.copyValueOf(...)

Exclude all transitive dependencies of a single dependency

if you need to exclude all transitive dependencies from a dependency artifact that you are going to include in an assembly, you can specify this in the descriptor for the assembly-plugin:

<assembly>
    <id>myApp</id>
    <formats>
        <format>zip</format>
    </formats>
    <dependencySets>
        <dependencySet>
            <useTransitiveDependencies>false</useTransitiveDependencies>
            <includes><include>*:struts2-spring-plugin:jar:2.1.6</include></includes>
        </dependencySet>
    </dependencySets>
</assembly>

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Detect touch press vs long press vs movement?

I think you should implement GestureDetector.OnGestureListener as described in Using GestureDetector to detect Long Touch, Double Tap, Scroll or other touch events in Android and androidsnippets and then implement tap logic in onSingleTapUp and move logic in onScroll events

AngularJS access parent scope from child controller

Some times you may need to update parent properties directly within child scope. e.g. need to save a date and time of parent control after changes by a child controller. e.g Code in JSFiddle

HTML

<div ng-app>
<div ng-controller="Parent">
    event.date = {{event.date}} <br/>
    event.time = {{event.time}} <br/>
    <div ng-controller="Child">
        event.date = {{event.date}}<br/>
        event.time = {{event.time}}<br/>
        <br>
        event.date: <input ng-model='event.date'><br>
        event.time: <input ng-model='event.time'><br>
    </div>
</div>

JS

    function Parent($scope) {
       $scope.event = {
        date: '2014/01/1',
        time: '10:01 AM'
       }
    }

    function Child($scope) {

    }

How to check if an app is installed from a web-page on an iPhone?

To further the accepted answer, you sometimes need to add extra code to handle people returning the browser after launching the app- that setTimeout function will run whenever they do. So, I do something like this:

var now = new Date().valueOf();
setTimeout(function () {
    if (new Date().valueOf() - now > 100) return;
    window.location = "https://itunes.apple.com/appdir";
}, 25);
window.location = "appname://";

That way, if there has been a freeze in code execution (i.e., app switching), it won't run.

Matlab: Running an m-file from command-line

A command like this runs the m-file successfully:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m'); exit;"

Case statement in MySQL

MySQL also has IF():

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

Create a string and append text to it

Concatenate with & operator

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.


Concatenate with String.Concat()

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

Search an Oracle database for tables with specific column names?

Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus

set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name, 
                column_name, 
                data_type || ' (' || 
                decode(data_type,'LONG',null,'LONG RAW',null,
                       'BLOB',null,'CLOB',null,'NUMBER',
                       decode(data_precision,null,to_char(data_length),
                              data_precision||','||data_scale
                             ), data_length
                      ) || ')' data_type
  from all_tab_columns
 where column_name like ('%' || upper('&colnam') || '%');
set verify on

C# Set collection?

If you're using .NET 4.0 or later:

In the case where you need sorting then use SortedSet<T>. Otherwise if you don't, then use HashSet<T> since it's O(1) for search and manipulate operations. Whereas SortedSet<T> is O(log n) for search and manipulate operations.

Why am I getting ImportError: No module named pip ' right after installing pip?

try to type pip3 instead pip. also for upgrading pip dont use pip3 in the command

python -m pip install -U pip

maybe it helps

How to get Ā° character in a string in python?

You can also use chr(176) to print the degree sign. Here is an example using python 3.6.5 interactive shell:

https://i.stack.imgur.com/spoWL.png

How can I print using JQuery

function printResult() {
    var DocumentContainer = document.getElementById('your_div_id');
    var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

nodejs module.js:340 error: cannot find module

If you are using a framework like express, you need to put the package.json file into the folder you are using and don't forget change main name.

EditText underline below text property

This works fine for old and new version of Android (works fine even on API 10!).

Define this style in your styles.xml:

<style name="EditText.Login" parent="Widget.AppCompat.EditText">
    <item name="android:textColor">@android:color/white</item>
    <item name="android:textColorHint">@android:color/darker_gray</item>
    <item name="colorAccent">@color/blue</item>
    <item name="colorControlNormal">@color/blue</item>
    <item name="colorControlActivated">@color/blue</item>
</style>

And now in your XML, set this as theme and style (style to set textColor, and theme to set all other things):

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text"
    style="@style/EditText.Login"
    android:theme="@style/EditText.Login"/>

Edit

This solution causes a tiny UI glitch on newer Android versions (Lollipop or Marshmallow onwards) that the selection handles are underlined.

This issue is discussed in this thread. (I haven't tried this solution personally)

What does O(log n) mean exactly?

But what exactly is O(log n)? For example, what does it mean to say that the height of a >complete binary tree is O(log n)?

I would rephrase this as 'height of a complete binary tree is log n'. Figuring the height of a complete binary tree would be O(log n), if you were traversing down step by step.

I cannot understand how to identify a function with a logarithmic time.

Logarithm is essentially the inverse of exponentiation. So, if each 'step' of your function is eliminating a factor of elements from the original item set, that is a logarithmic time algorithm.

For the tree example, you can easily see that stepping down a level of nodes cuts down an exponential number of elements as you continue traversing. The popular example of looking through a name-sorted phone book is essentially equivalent to traversing down a binary search tree (middle page is the root element, and you can deduce at each step whether to go left or right).

How can I get (query string) parameters from the URL in Next.js?

_x000D_
_x000D_
Post.getInitialProps = async function(context) {_x000D_
_x000D_
  const data = {}_x000D_
  try{_x000D_
    data.queryParam = queryString.parse(context.req.url.split('?')[1]);_x000D_
  }catch(err){_x000D_
    data.queryParam = queryString.parse(window.location.search);_x000D_
  }_x000D_
  return { data };_x000D_
};
_x000D_
_x000D_
_x000D_

Equal sized table cells to fill the entire width of the containing table

Just use percentage widths and fixed table layout:

<table>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

with

table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

WindowsError: [Error 126] The specified module could not be found

Also this could be that you have forgotten to set your working directory in eclipse to be the correct local for the application to run in.

Use Font Awesome Icon in Placeholder

Anyone wondering about a Font Awesome 5 implementation:

Do not specify a general "Font Awesome 5" font family, you need to specifically end with the branch of icons you're working with. Here I am using the branch "Brands" for example.

<input style="font-family:'Font Awesome 5 Brands' !important" 
       type="text" placeholder="&#xf167">

More detail Use Font Awesome (5) icon in input placeholder text

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

Sorting arrays in javascript by object key value

Use Array's sort() method, eg

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

We face this issue but had different reason, here is the reason:

In our project found multiple bean entry with same bean name. 1 in applicationcontext.xml & 1 in dispatcherServlet.xml

Example:

<bean name="dataService" class="com.app.DataServiceImpl">
<bean name="dataService" class="com.app.DataServiceController">

& we are trying to autowired by dataService name.

Solution: we changed the bean name & its solved.

How to disable back swipe gesture in UINavigationController on iOS 7

As of iOS 8 the accepted answer no longer works. I needed to stop the swipping to dismiss gesture on my main game screen so implemented this:

- (void)viewDidAppear:(BOOL)animated
{
     [super viewDidAppear:animated];

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }

}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
     return NO;
}

Insert an element at a specific index in a list and return the updated list

The cleanest approach is to copy the list and then insert the object into the copy. On Python 3 this can be done via list.copy:

new = old.copy()
new.insert(index, value)

On Python 2 copying the list can be achieved via new = old[:] (this also works on Python 3).

In terms of performance there is no difference to other proposed methods:

$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 Āµsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 Āµsec per loop

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

Java recursive Fibonacci sequence

public long getFibonacci( int number) {
    if ( number <=2) {
        return 1;
    }
    long lRet = 0;
    lRet = getFibonacci( number -1) + getFibonacci( number -2);
    return lRet;
}

CMake link to external library

I assume you want to link to a library called foo, its filename is usually something link foo.dll or libfoo.so.

1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB use

    find_library(FOO_LIB foo)

CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib, /usr/lib64 and the paths in PATH.

You already know the location of your library. Add it to the CMAKE_PREFIX_PATH when you call CMake, then CMake will look for your library in the passed paths, too.

Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html

2. Link the library From 1. you have the full library name in FOO_LIB. You use this to link the library to your target GLBall as in

  target_link_libraries(GLBall PRIVATE "${FOO_LIB}")

You should add PRIVATE, PUBLIC, or INTERFACE after the target, cf. the documentation: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

If you don't add one of these visibility specifiers, it will either behave like PRIVATE or PUBLIC, depending on the CMake version and the policies set.

3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path similar to find_library and search for a header file. Then add the include directory with target_include_directories similar to target_link_libraries.

Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html

If available for the external software, you can replace find_library and find_path by find_package.

Alternative to iFrames with HTML5

I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

Changes to the parent site are picked up every 5 minutes.

var iframeReplacement = require('node-iframe-replacement');

// add iframe replacement to express as middleware (adds res.merge method) 
app.use(iframeReplacement);

// create a regular express route 
app.get('/', function(req, res){

    // respond to this request with our fake-news content embedded within the BBC News home page 
    res.merge('fake-news', {
        // external url to fetch 
       sourceUrl: 'http://www.bbc.co.uk/news',
       // css selector to inject our content into 
       sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
       // pass a function here to intercept the source html prior to merging 
       transform: null
    });
});

The source contains a working example of injecting content into the BBC News home page.

Returning value that was passed into a method

You can use a lambda with an input parameter, like so:

.Returns((string myval) => { return myval; });

Or slightly more readable:

.Returns<string>(x => x);

How do I determine if a port is open on a Windows server?

Assuming that it's a TCP (rather than UDP) port that you're trying to use:

  1. On the server itself, use netstat -an to check to see which ports are listening.

  2. From outside, just use telnet host port (or telnet host:port on Unix systems) to see if the connection is refused, accepted, or timeouts.

On that latter test, then in general:

  • connection refused means that nothing is running on that port
  • accepted means that something is running on that port
  • timeout means that a firewall is blocking access

On Windows 7 or Windows Vista the default option 'telnet' is not recognized as an internal or external command, operable program or batch file. To solve this, just enable it: Click *Start** → Control PanelProgramsTurn Windows Features on or off. In the list, scroll down and select Telnet Client and click OK.

Undoing a git rebase

If you don't want to do a hard reset...

You can checkout the commit from the reflog, and then save it as a new branch:

git reflog

Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:

git checkout HEAD@{57}

Review the branch/commits, and if it's correct then create a new branch using this HEAD:

git checkout -b new_branch_name

Passing command line arguments in Visual Studio 2010?

Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)

Greetings mic enter image description here

Query comparing dates in SQL

please try with below query

select id,numbers_from,created_date,amount_numbers,SMS_text 
from Test_Table
where 
convert(datetime, convert(varchar(10), created_date, 102))  <= convert(datetime,'2013-04-12')

How to initialize var?

var just tells the compiler to infer the type you wanted at compile time...it cannot infer from null (though there are cases it could).

So, no you are not allowed to do this.

When you say "some empty value"...if you mean:

var s = string.Empty;
//
var s = "";

Then yes, you may do that, but not null.

How to comment lines in rails html.erb files?

This is CLEANEST, SIMPLEST ANSWER for CONTIGUOUS NON-PRINTING Ruby Code:

The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.


  1. CONTIGUOUS NON-PRINTING Ruby Code

    • This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml, etc.

    • This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>

    • DETAILS:

      Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:

        <%# if flash[:myErrors] %>
          <%# if flash[:myErrors].any? %>
            <%# if @post.id.nil? %>
              <%# if @myPost!=-1 %>
                <%# @post = @myPost %>
              <%# else %>
                <%# @post = Post.new %>
              <%# end %>
            <%# end %>
          <%# end %>
        <%# end %>
      

      YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:

        <%# 
          if flash[:myErrors] then
            if flash[:myErrors].any? then
              if @post.id.nil? then
                if @myPost!=-1 then
                  @post = @myPost 
                else 
                  @post = Post.new 
                end 
              end 
            end 
          end 
        %>
      

Add Foreign Key relationship between two Databases

You would need to manage the referential constraint across databases using a Trigger.


Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.

Example:

Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin

   If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
      -- Handle the Referential Error Here
   END

END

Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.

Write-back vs Write-Through caching?

maybe this article can help you link here

Write-through: Write is done synchronously both to the cache and to the backing store.

Write-back (or Write-behind): Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.

Write-through: When data is updated, it is written to both the cache and the back-end storage. This mode is easy for operation but is slow in data writing because data has to be written to both the cache and the storage.

Write-back: When data is updated, it is written only to the cache. The modified data is written to the back-end storage only when data is removed from the cache. This mode has fast data write speed but data will be lost if a power failure occurs before the updated data is written to the storage.

Using braces with dynamic variable names in PHP

I do this quite often on results returned from a query..

e.g.

// $MyQueryResult is an array of results from a query

foreach ($MyQueryResult as $key=>$value)
{
   ${$key}=$value;
}

Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']

Yep, it's probably lazy, but I've never had any problems.

How do I extract the contents of an rpm?

The "DECOMPRESSION" test fails on CygWin, one of the most potentiaally useful platforms for it, due to the "grep" check for "xz" being case sensitive. The result of the "COMPRESSION:" check is:

COMPRESSION='/dev/stdin: XZ compressed data'

Simply replacing 'grep -q' with 'grep -q -i' everywhere seems to resolve the issue well.

I've done a few updates, particularly adding some comments and using "case" instead of stacked "if" statements, and included that fix below

#!/bin/sh
#
# rpm2cpio.sh - extract 'cpio' contents of RPM
#
# Typical usage: rpm2cpio.sh rpmname | cpio -idmv
#

if [ "$# -ne 1" ]; then
    echo "Usage: $0 file.rpm" 1>&2
    exit 1
fi

rpm="$1"
if [ -e "$rpm" ]; then
    echo "Error: missing $rpm"
fi


leadsize=96
o=`expr $leadsize + 8`
set `od -j $o -N 8 -t u1 $rpm`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "sig il: $il dl: $dl"

sigsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $sigsize + \( 8 - \( $sigsize \% 8 \) \) \% 8 + 8`
set `od -j $o -N 8 -t u1 $rpm`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "hdr il: $il dl: $dl"

hdrsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $hdrsize`
EXTRACTOR="dd if=$rpm ibs=$o skip=1"

COMPRESSION=`($EXTRACTOR |file -) 2>/dev/null`
DECOMPRESSOR="cat"

case $COMPRESSION in
    *gzip*|*GZIP*)
        DECOMPRESSOR=gunzip
        ;;
    *bzip2*|*BZIP2*)
        DECOMPRESSOR=bunzip2
        ;;
    *xz*|*XZ*)
        DECOMPRESSOR=unxz
        ;;
    *cpio*|*cpio*)
        ;;
    *)
        # Most versions of file don't support LZMA, therefore we assume
        # anything not detected is LZMA
        DECOMPRESSOR="`which unlzma 2>/dev/null`"
        case "$DECOMPRESSOR" in
            /*)
                DECOMPRESSOR="$DECOMPRESSOR"
                ;;
            *)
                DECOMPRESSOR=`which lzmash 2>/dev/null`
                case "$DECOMPRESSOR" in
                    /* )
                        DECOMPRESSOR="lzmash -d -c"
                        ;;
                    *  )
                        echo "Warning: DECOMPRESSOR not found, assuming 'cat'" 1>&2
                        ;;
                esac
                ;;
        esac
esac

$EXTRACTOR 2>/dev/null | $DECOMPRESSOR

Killing a process using Java

Accidentally i stumbled upon another way to do a force kill on Unix (for those who use Weblogic). This is cheaper and more elegant than running /bin/kill -9 via Runtime.exec().

import weblogic.nodemanager.util.Platform;
import weblogic.nodemanager.util.ProcessControl;
...
ProcessControl pctl = Platform.getProcessControl();
pctl.killProcess(pid);

And if you struggle to get the pid, you can use reflection on java.lang.UNIXProcess, e.g.:

Process proc = Runtime.getRuntime().exec(cmdarray, envp);
if (proc instanceof UNIXProcess) {
    Field f = proc.getClass().getDeclaredField("pid");
    f.setAccessible(true);
    int pid = f.get(proc);
}

How to cast from List<Double> to double[] in Java?

High performance - every Double object wraps a single double value. If you want to store all these values into a double[] array, then you have to iterate over the collection of Double instances. A O(1) mapping is not possible, this should be the fastest you can get:

 double[] target = new double[doubles.size()];
 for (int i = 0; i < target.length; i++) {
    target[i] = doubles.get(i).doubleValue();  // java 1.4 style
    // or:
    target[i] = doubles.get(i);                // java 1.5+ style (outboxing)
 }

Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive method:

public static double[] toPrimitive(Double[] array) {
  if (array == null) {
    return null;
  } else if (array.length == 0) {
    return EMPTY_DOUBLE_ARRAY;
  }
  final double[] result = new double[array.length];
  for (int i = 0; i < array.length; i++) {
    result[i] = array[i].doubleValue();
  }
  return result;
}

(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )

By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[] from the list, then to unwrap the double values.

Why catch and rethrow an exception in C#?

A valid reason for rethrowing exceptions can be that you want to add information to the exception, or perhaps wrap the original exception in one of your own making:

public static string SerializeDTO(DTO dto) {
  try {
      XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
      StringWriter sWriter = new StringWriter();
      xmlSer.Serialize(sWriter, dto);
      return sWriter.ToString();
  }
  catch(Exception ex) {
    string message = 
      String.Format("Something went wrong serializing DTO {0}", DTO);
    throw new MyLibraryException(message, ex);
  }
}

Transferring files over SSH

You need to specify both source and destination, and if you want to copy directories you should look at the -r option.

So to recursively copy /home/user/whatever from remote server to your current directory:

scp -pr user@remoteserver:whatever .

Wildcards in jQuery selectors

When you have a more complex id string the double quotes are mandatory.

For example if you have an id like this: id="2.2", the correct way to access it is: $('input[id="2.2"]')

As much as possible use the double quotes, for safety reasons.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

In my case I had a terrible mistake. I put @Service up to the service interface.

To fix it, I put @Service on the implementation of service file and it worked for me.

Preview an image before it is uploaded

There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image.

Here's an example:

_x000D_
_x000D_
<input type="file" accept="image/*" onchange="loadFile(event)">_x000D_
<img id="output"/>_x000D_
<script>_x000D_
  var loadFile = function(event) {_x000D_
    var output = document.getElementById('output');_x000D_
    output.src = URL.createObjectURL(event.target.files[0]);_x000D_
    output.onload = function() {_x000D_
      URL.revokeObjectURL(output.src) // free memory_x000D_
    }_x000D_
  };_x000D_
</script>
_x000D_
_x000D_
_x000D_

You can also use FileReader.readAsDataURL() to parse the file from your <input>. This will create a string in memory containing a base64 representation of the image.

_x000D_
_x000D_
<input type="file" accept="image/*" onchange="loadFile(event)">_x000D_
<img id="output"/>_x000D_
<script>_x000D_
  var loadFile = function(event) {_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
      var output = document.getElementById('output');_x000D_
      output.src = reader.result;_x000D_
    };_x000D_
    reader.readAsDataURL(event.target.files[0]);_x000D_
  };_x000D_
</script>
_x000D_
_x000D_
_x000D_

UnicodeEncodeError: 'latin-1' codec can't encode character

Latin-1 (aka ISO 8859-1) is a single octet character encoding scheme, and you can't fit \u201c (ā€œ) into a byte.

Did you mean to use UTF-8 encoding?

UIButton action in table view cell

As Apple DOC

targetForAction:withSender:
Returns the target object that responds to an action.

You can't use that method to set target for UIButton.
Try addTarget(_:action:forControlEvents:) method

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

Create a day-of-week column in a Pandas dataframe using Python

In version 0.18.1 is added dt.weekday_name:

print df
    my_dates  myvals
0 2015-01-01       1
1 2015-01-02       2
2 2015-01-03       3

print df.dtypes
my_dates    datetime64[ns]
myvals               int64
dtype: object

df['day_of_week'] = df['my_dates'].dt.weekday_name
print df
    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

Another solution with assign:

print df.assign(day_of_week = df['my_dates'].dt.weekday_name)
    my_dates  myvals day_of_week
0 2015-01-01       1    Thursday
1 2015-01-02       2      Friday
2 2015-01-03       3    Saturday

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

Using a bitmask in C#

Easy Way:

[Flags]
public enum MyFlags {
    None = 0,
    Susan = 1,
    Alice = 2,
    Bob = 4,
    Eve = 8
}

To set the flags use logical "or" operator |:

MyFlags f = new MyFlags();
f = MyFlags.Alice | MyFlags.Bob;

And to check if a flag is included use HasFlag:

if(f.HasFlag(MyFlags.Alice)) { /* true */}
if(f.HasFlag(MyFlags.Eve)) { /* false */}

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val());

How to add colored border on cardview?

CardView extends FrameLayout, so it support foreground attribute. Using foreground attribute can also add border easily.

layout as follows:

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/link_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="@drawable/bg_roundrect_ripple_light_border"
    app:cardCornerRadius="23dp"
    app:cardElevation="0dp">
</androidx.cardview.widget.CardView>

bg_roundrect_ripple_light_border.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/ripple_color_light">

    <item>
        <shape android:shape="rectangle">
            <stroke
                android:width="0.5dp"
                android:color="#DDDDDD" />
            <corners android:radius="23dp" />
        </shape>
    </item>

    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <corners android:radius="23dp" />
            <solid android:color="@color/background" />
        </shape>
    </item>

</ripple>

Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

Where is the itoa function in Linux?

itoa is not a standard C function. You can implement your own. It appeared in the first edition of Kernighan and Ritchie's The C Programming Language, on page 60. The second edition of The C Programming Language ("K&R2") contains the following implementation of itoa, on page 64. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative number

 /* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
}  

The function reverse used above is implemented two pages earlier:

 #include <string.h>

 /* reverse:  reverse string s in place */
 void reverse(char s[])
 {
     int i, j;
     char c;

     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
}  

Cloning specific branch

You may try this

git clone --single-branch --branch <branchname> host:/dir.git

How to override !important?

This can help too

td[style] {height: 50px !important;}

This will override any inline style

What is the maximum recursion depth in Python, and how to increase it?

Use generators?

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fibs = fib() #seems to be the only way to get the following line to work is to
             #assign the infinite generator to a variable

f = [fibs.next() for x in xrange(1001)]

for num in f:
        print num

above fib() function adapted from: http://intermediatepythonista.com/python-generators

Browse for a directory in C#

Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.

C++ STL Vectors: Get iterator from index?

Or you can use std::advance

vector<int>::iterator i = L.begin();
advance(i, 2);

ojdbc14.jar vs. ojdbc6.jar

Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.

Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.

This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).

Read file from line 2 or skip header row

To generalize the task of reading multiple header lines and to improve readability I'd use method extraction. Suppose you wanted to tokenize the first three lines of coordinates.txt to use as header information.

Example

coordinates.txt
---------------
Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0

Then method extraction allows you to specify what you want to do with the header information (in this example we simply tokenize the header lines based on the comma and return it as a list but there's room to do much more).

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens

Output

['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']

If coordinates.txt contains another headerline, simply change numberheaderlines. Best of all, it's clear what __readheader(rh, numberheaderlines=2) is doing and we avoid the ambiguity of having to figure out or comment on why author of the the accepted answer uses next() in his code.

Creating random numbers with no duplicates

There is algorithm of card batch: you create ordered array of numbers (the "card batch") and in every iteration you select a number at random position from it (removing the selected number from the "card batch" of course).

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using WebStorm and you are on Windows i would recommend you to click settings/editor/code style/general tab and select "windows(\r\n) from the dropdown menu.These steps will also apply for Rider.

enter image description here

Google Play Services Library update and missing symbol @integer/google_play_services_version

Off the cuff, it feels like your project is connected to an older version of the Play Services library project. The recommended approach, by Google, is for you to find the library project in the SDK and make a local copy. This does mean, though, that any time you update the Play Services library project through the SDK Manager, you also need to replace your copy with a fresh copy.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

You can use plt.subplots_adjust to change the spacing between the subplots Link

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for blank space between subplots
hspace = 0.2   # the amount of height reserved for white space between subplots

How to declare empty list and then add string in scala?

Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.

What is the exact meaning of Git Bash?

git bash is a shell where:

See "Fix msysGit Portable $HOME location":

On a Windows 64:

C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"

This differs from git-cmd.bat, which provides git commands in a plain DOS command prompt.

A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)


Update April 2015:

Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:

GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.

But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2 comes with its own installer too.

The git bash is now (with the new Git For Windows):

GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.

Original answer (June 2013) More precisely, from msygit wiki:

Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.

To make the milky 'soup' of project names more clear, we say like this:

  • msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
  • MinGW - is a minimalist development environment for native Microsoft Windows applications.
    It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as a fork() call
  • MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
  • Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit

So, your two lines description about "git bash" are:

"Git bash" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.


Reminder:

msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.

msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.

See more in "Difference between msysgit and Cygwin + git?".

C++ Compare char array with string

"dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.

Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.

Evaluate expression given as a string

Not sure why no one has mentioned two Base R functions specifically to do this: str2lang() and str2expression(). These are variants of parse(), but seem to return the expression more cleanly:

eval(str2lang("5+5"))

# > 10
  
eval(str2expression("5+5"))

# > 10

Also want to push back against the posters saying that anyone trying to do this is wrong. I'm reading in R expressions stored as text in a file and trying to evaluate them. These functions are perfect for this use case.

Permission denied error on Github Push

For some reason my push and pull origin was changed to HTTPS-url in stead of SSH-url (probably a copy-paste error on my end), but trying to push would give me the following error after trying to login:

Username for 'https://github.com': xxx
Password for 'https://[email protected]': 
remote: Invalid username or password.

Updating the remote origin with the SSH url, solved the problem:

git remote set-url origin [email protected]:<username>/<repo>.git

Hope this helps!

Tools for creating Class Diagrams

I have used both Poseidon UML and Enterprise Architect and must say that I prefer Poseidon but wasn't fully satisfied with any of them.

Creating a dictionary from a CSV file

Many solutions have been posted and I'd like to contribute with mine, which works for a different number of columns in the CSV file. It creates a dictionary with one key per column, and the value for each key is a list with the elements in such column.

    input_file = csv.DictReader(open(path_to_csv_file))
    csv_dict = {elem: [] for elem in input_file.fieldnames}
    for row in input_file:
        for key in csv_dict.keys():
            csv_dict[key].append(row[key])

Get List of connected USB Devices

To see the devices I was interested in, I had replace Win32_USBHub by Win32_PnPEntity in Adel Hazzah's code, based on this post. This works for me:

namespace ConsoleApplication1
{
  using System;
  using System.Collections.Generic;
  using System.Management; // need to add System.Management to your project references.

  class Program
  {
    static void Main(string[] args)
    {
      var usbDevices = GetUSBDevices();

      foreach (var usbDevice in usbDevices)
      {
        Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
            usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
      }

      Console.Read();
    }

    static List<USBDeviceInfo> GetUSBDevices()
    {
      List<USBDeviceInfo> devices = new List<USBDeviceInfo>();

      ManagementObjectCollection collection;
      using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        collection = searcher.Get();      

      foreach (var device in collection)
      {
        devices.Add(new USBDeviceInfo(
        (string)device.GetPropertyValue("DeviceID"),
        (string)device.GetPropertyValue("PNPDeviceID"),
        (string)device.GetPropertyValue("Description")
        ));
      }

      collection.Dispose();
      return devices;
    }
  }

  class USBDeviceInfo
  {
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
    {
      this.DeviceID = deviceID;
      this.PnpDeviceID = pnpDeviceID;
      this.Description = description;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
  }
}

How to cast Object to its actual type?

Implement an interface to call your function in your method
interface IMyInterface
{
 void MyinterfaceMethod();
}

IMyInterface MyObj = obj as IMyInterface;
if ( MyObj != null)
{
MyMethod(IMyInterface MyObj );
}

Using Environment Variables with Vue.js

A problem I was running into was that I was using the webpack-simple install for VueJS which didn't seem to include an Environment variable config folder. So I wasn't able to edit the env.test,development, and production.js config files. Creating them didn't help either.

Other answers weren't detailed enough for me, so I just "fiddled" with webpack.config.js. And the following worked just fine.

So to get Environment Variables to work, the webpack.config.js should have the following at the bottom:

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

Based on the above, in production, you would be able to get the NODE_ENV variable

mounted() {
  console.log(process.env.NODE_ENV)
}

Now there may be better ways to do this, but if you want to use Environment Variables in Development you would do something like the following:

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"'
      }
    })
  ]);

} 

Now if you want to add other variables with would be as simple as:

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
        ENDPOINT: '"http://localhost:3000"',
        FOO: "'BAR'"
      }
    })
  ]);
}

I should also note that you seem to need the "''" double quotes for some reason.

So, in Development, I can now access these Environment Variables:

mounted() {
  console.log(process.env.ENDPOINT)
  console.log(process.env.FOO)
}

Here is the whole webpack.config.js just for some context:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
        ENDPOINT: '"http://localhost:3000"',
        FOO: "'BAR'"
      }
    })
  ]);

}

How can I remove a character from a string using JavaScript?

var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');

will replace /r with / using String.prototype.replace.

Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with

mystring = mystring.replace(/\/r/g, '/');

EDIT: Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:

String.prototype.removeCharAt = function (i) {
    var tmp = this.split(''); // convert to an array
    tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
    return tmp.join(''); // reconstruct the string
}

console.log("crt/r2002_2".removeCharAt(4));

Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1) instead.

Can you change what a symlink points to after it is created?

Wouldn't unlinking it and creating the new one do the same thing in the end anyway?

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

What is the difference between json.dump() and json.dumps() in python?

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

How to copy selected files from Android with adb pull

As to the short script, the following runs on my Linux host

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"

while read MYFILE ; do
    adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")

"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

Listing contents of a bucket with boto3

One way that I used to do this:

import boto3
s3 = boto3.resource('s3')
bucket=s3.Bucket("bucket_name")
contents = [_.key for _ in bucket.objects.all() if "subfolders/ifany/" in _.key]

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

How do I force a favicon refresh?

By destroying the file your browser uses to store old favicons, you can force new ones to be loaded.

  1. Close your browser. Make sure there are no longer browser processes running (e.g. check Task Manager for chrome.exe or firefox.exe).
  2. Navigate to where your browser stores user files:
  3. Delete the favicon cache.
    • For Chrome, remove Favicons and Favicons-journal
    • For Firefox, remove favicons.sqlite

This will almost definitely work. If not:

  • Possibility 1: An update to your browser has changed how the favicon cache works. Please edit this answer with new instructions.
  • Possibility 2: Your favicon problem has nothing to do with overaggressive caching. It may instead be a resource-loading problem ā€“ using Developer Tools, make sure the new favicon is downloading properly.

Installing PG gem on OS X - failure to build native extension

If you are using Ubuntu try to install following lib file

sudo apt-get install libpq-dev

and then

gem install pg

worked for me.

Split string by single spaces

If you are averse to boost, you can use regular old operator>>, along with std::noskipws:

EDIT: updates after testing.

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>

void split(const std::string& str, std::vector<std::string>& v) {
  std::stringstream ss(str);
  ss >> std::noskipws;
  std::string field;
  char ws_delim;
  while(1) {
    if( ss >> field )
      v.push_back(field);
    else if (ss.eof())
      break;
    else
      v.push_back(std::string());
    ss.clear();
    ss >> ws_delim;
  }
}

int main() {
  std::vector<std::string> v;
  split("hello world  how are   you", v);
  std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
  std::cout << "\n";
}

http://ideone.com/62McC

What's the difference between lists enclosed by square brackets and parentheses in Python?

One interesting difference :

lst=[1]
print lst          // prints [1]
print type(lst)    // prints <type 'list'>

notATuple=(1)
print notATuple        // prints 1
print type(notATuple)  // prints <type 'int'>
                                         ^^ instead of tuple(expected)

A comma must be included in a tuple even if it contains only a single value. e.g. (1,) instead of (1).

Spring Data JPA and Exists query

Spring Data JPA 1.11 now supports the exists projection in repository query derivation.

See documentation here.

In your case the following will work:

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

Mockito How to mock and assert a thrown exception?

If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionMessage() throws Exception {
    expectedException.expect(AnyException.class);
    expectedException.expectMessage("The expected message");

    given(foo.bar()).willThrow(new AnyException("The expected message"));
}

How to set encoding in .getJSON jQuery

If you want to use $.getJSON() you can add the following before the call :

$.ajaxSetup({
    scriptCharset: "utf-8",
    contentType: "application/json; charset=utf-8"
});

You can use the charset you want instead of utf-8.

The options are explained here.

contentType : When sending data to the server, use this content-type. Default is application/x-www-form-urlencoded, which is fine for most cases.

scriptCharset : Only for requests with jsonp or script dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

You may need one or both ...

How to loop through an array of objects in swift

The photos property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count property of the array):

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

Best way to display data via JSON using jQuery

Something like this:

$.getJSON("http://mywebsite.com/json/get.php?cid=15",
        function(data){
          $.each(data.products, function(i,product){
            content = '<p>' + product.product_title + '</p>';
            content += '<p>' + product.product_short_description + '</p>';
            content += '<img src="' + product.product_thumbnail_src + '"/>';
            content += '<br/>';
            $(content).appendTo("#product_list");
          });
        });

Would take a json object made from a PHP array returned with the key of products. e.g:

Array('products' => Array(0 => Array('product_title' => 'Product 1',
                                     'product_short_description' => 'Product 1 is a useful product',
                                     'product_thumbnail_src' => '/images/15/1.jpg'
                                    )
                          1 => Array('product_title' => 'Product 2',
                                     'product_short_description' => 'Product 2 is a not so useful product',
                                     'product_thumbnail_src' => '/images/15/2.jpg'
                                    )
                         )
     )

To reload the list you would simply do:

$("#product_list").empty();

And then call getJSON again with new parameters.

How to implement 2D vector array?

Just use the following methods to create a 2-D vector.

int rows, columns;        

// . . .

vector < vector < int > > Matrix(rows, vector< int >(columns,0));

OR

vector < vector < int > > Matrix;

Matrix.assign(rows, vector < int >(columns, 0));

//Do your stuff here...

This will create a Matrix of size rows * columns and initializes it with zeros because we are passing a zero(0) as a second argument in the constructor i.e vector < int > (columns, 0).

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

Look in the SDK Manager what is your highest Android SDK Build-tools version, and copy this version number in your project build.gradle file, in the android/buildToolsVersion property (for me, version was "18.1.1").

Hope it help!

Java better way to delete file if exists

Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.

File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block

How do I print the content of a .txt file in Python?

It's pretty simple

#Opening file
f= open('sample.txt')
#reading everything in file
r=f.read()
#reading at particular index
r=f.read(1)
#print
print(r)

Presenting snapshot from my visual studio IDE.

enter image description here

What are major differences between C# and Java?

Another good resource is http://www.javacamp.org/javavscsharp/ This site enumerates many examples that ilustrate almost all the differences between these two programming languages.

About the Attributes, Java has Annotations, that work almost the same way.