Programs & Examples On #Semantic web

Representation of database record subjects (a/k/a keys, IDs, entities), predicates (a/k/a columns, attributes), and objects (a/k/a values) as triples, where the first two are always URIs, and the third is either a URI or a literal; enabling humans and machines to more easily share, merge, and evaluate data from heterogeneous origins.

Change UITableView height dynamically

Use simple and easy code

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let myCell = tableView.dequeueReusableCellWithIdentifier("mannaCustumCell") as! CustomCell
        let heightForCell = myCell.bounds.size.height;

        return heightForCell;
    }

Is JavaScript's "new" keyword considered harmful?

Here is the briefest summary I could make of the two strongest arguments for and against using the new operator:

Argument against new

  1. Functions designed to be instantiated as objects using the new operator can have disastrous effects if they are incorrectly invoked as normal functions. A function's code in such a case will be executed in the scope where the function is called, instead of in the scope of a local object as intended. This can cause global variables and properties to get overwritten with disastrous consequences.
  2. Finally, writing function Func(), and then calling Func.prototype and adding stuff to it so that you can call new Func() to construct your object seems ugly to some programmers, who would rather use another style of object inheritance for architectural and stylistic reasons.

For more on this argument check out Douglas Crockford's great and concise book Javascript: The Good Parts. In fact check it out anyway.

Argument in favor of new

  1. Using the new operator along with prototypal assignment is fast.
  2. That stuff about accidentally running a constructor function's code in the global namespace can easily be prevented if you always include a bit of code in your constructor functions to check to see if they are being called correctly, and, in the cases where they aren't, handling the call appropriately as desired.

See John Resig's post for a simple explanation of this technique, and for a generally deeper explanation of the inheritance model he advocates.

What is the simplest and most robust way to get the user's current location on Android?

After searching for best implementation how to get best precise user location I managed to combine all the best methods and come up with following class:

/**
 * Retrieve accurate location from GPS or network services. 
 * 
 *
 * Class usage example:
 * 
 * public void onCreate(Bundle savedInstanceState) {
 *      ...
 *      my_location = new MyLocation();
 *      my_location.init(main.this, locationResult);
 * }
 * 
 * 
 * public LocationResult locationResult = new LocationResult(){
 *      @Override
 *      public void gotLocation(final Location location){
 *          // do something
 *          location.getLongitude();
 *          location.getLatitude();
 *      }
 *  };
 */
class MyLocation{

    /**
     * If GPS is enabled. 
     * Use minimal connected satellites count.
     */
    private static final int min_gps_sat_count = 5;

    /**
     * Iteration step time.
     */
    private static final int iteration_timeout_step = 500;

    LocationResult locationResult;
    private Location bestLocation = null;
    private Handler handler = new Handler();
    private LocationManager myLocationManager; 
    public Context context;

    private boolean gps_enabled = false;

    private int counts    = 0;
    private int sat_count = 0;

    private Runnable showTime = new Runnable() {

         public void run() {
            boolean stop = false;
            counts++;
            System.println("counts=" + counts);

            //if timeout (1 min) exceeded, stop tying
            if(counts > 120){
                stop = true;
            }

            //update last best location
            bestLocation = getLocation(context);

            //if location is not ready or don`t exists, try again
            if(bestLocation == null && gps_enabled){
                System.println("BestLocation not ready, continue to wait");
                handler.postDelayed(this, iteration_timeout_step);
            }else{
                //if best location is known, calculate if we need to continue to look for better location
                //if gps is enabled and min satellites count has not been connected or min check count is smaller then 4 (2 sec)  
                if(stop == false && !needToStop()){
                    System.println("Connected " + sat_count + " sattelites. continue waiting..");
                    handler.postDelayed(this, iteration_timeout_step);
                }else{
                    System.println("#########################################");
                    System.println("BestLocation finded return result to main. sat_count=" + sat_count);
                    System.println("#########################################");

                    // removing all updates and listeners
                    myLocationManager.removeUpdates(gpsLocationListener);
                    myLocationManager.removeUpdates(networkLocationListener);    
                    myLocationManager.removeGpsStatusListener(gpsStatusListener);
                    sat_count = 0;

                    // send best location to locationResult
                    locationResult.gotLocation(bestLocation);
                }
            }
         }
    };

    /**
     * Determine if continue to try to find best location
     */
    private Boolean needToStop(){

        if(!gps_enabled){
                          return true;
                     }
          else if(counts <= 4){
                return false;
            }
            if(sat_count < min_gps_sat_count){
                //if 20-25 sec and 3 satellites found then stop
                if(counts >= 40 && sat_count >= 3){
                    return true;
                }
                return false;
            }
        }
        return true;
    }

    /**
     * Best location abstract result class
     */
    public static abstract class LocationResult{
         public abstract void gotLocation(Location location);
     }

    /**
     * Initialize starting values and starting best location listeners
     * 
     * @param Context ctx
     * @param LocationResult result
     */
    public void init(Context ctx, LocationResult result){
        context = ctx;
        locationResult = result;

        myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        gps_enabled = (Boolean) myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        bestLocation = null;
        counts = 0;

        // turning on location updates
        myLocationManager.requestLocationUpdates("network", 0, 0, networkLocationListener);
        myLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);
        myLocationManager.addGpsStatusListener(gpsStatusListener);

        // starting best location finder loop
        handler.postDelayed(showTime, iteration_timeout_step);
    }

    /**
     * GpsStatus listener. OnChainged counts connected satellites count.
     */
    public final GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {

             if(event == GpsStatus.GPS_EVENT_SATELLITE_STATUS){
                try {
                    // Check number of satellites in list to determine fix state
                     GpsStatus status = myLocationManager.getGpsStatus(null);
                     Iterable<GpsSatellite>satellites = status.getSatellites();

                     sat_count = 0;

                     Iterator<GpsSatellite>satI = satellites.iterator();
                     while(satI.hasNext()) {
                         GpsSatellite satellite = satI.next();
                         System.println("Satellite: snr=" + satellite.getSnr() + ", elevation=" + satellite.getElevation());                         
                         sat_count++;
                     }
                } catch (Exception e) {
                    e.printStackTrace();
                    sat_count = min_gps_sat_count + 1;
                }

                 System.println("#### sat_count = " + sat_count);
             }
         }
    };

    /**
     * Gps location listener.
     */
    public final LocationListener gpsLocationListener = new LocationListener(){
        @Override
         public void onLocationChanged(Location location){

        }
         public void onProviderDisabled(String provider){}
         public void onProviderEnabled(String provider){}
         public void onStatusChanged(String provider, int status, Bundle extras){}
    }; 

    /**
     * Network location listener.
     */
    public final LocationListener networkLocationListener = new LocationListener(){
        @Override
         public void onLocationChanged(Location location){

        }
         public void onProviderDisabled(String provider){}
         public void onProviderEnabled(String provider){}
         public void onStatusChanged(String provider, int status, Bundle extras){}
    }; 


    /**
     * Returns best location using LocationManager.getBestProvider()
     * 
     * @param context
     * @return Location|null
     */
    public static Location getLocation(Context context){
        System.println("getLocation()");

        // fetch last known location and update it
        try {
            LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
             criteria.setAltitudeRequired(false);
             criteria.setBearingRequired(false);
             criteria.setCostAllowed(true);
             String strLocationProvider = lm.getBestProvider(criteria, true);

             System.println("strLocationProvider=" + strLocationProvider);
             Location location = lm.getLastKnownLocation(strLocationProvider);
             if(location != null){
                return location;
             }
             return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

This class tries to connect to min_gps_sat_count satellites if GPS is enabled. Else returns LocationManager.getBestProvider() location. Check the code!

Provide an image for WhatsApp link sharing

enter image description here After looking through lot of answers and yet unable to fix the issue, I finally got it working after lot of iterations. Here is the exact code I used:

In <head> tag:

<meta property="og:title" content="ABC Blabla 2020 Friday" />
<meta property="og:url" content="https://bla123.neocities.org/mp/friday.html" />
<meta property="og:description" content="Photo Album">
<meta property="og:image" itemprop="image" content="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG"/>
<meta property="og:type" content="article" />
<meta property="og:locale" content="en_GB" />

In <body> tag:

<link itemprop="thumbnailUrl" href="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG">

<span itemprop="thumbnail" itemscope itemtype="http://schema.org/ImageObject">
<link itemprop="url" href="https://bla123.neocities.org/mp/images/thumbs/IMG_327.JPG">
</span>

These 8 tags ( 6 in head , 2 in body) worked perfectly.

Tips:

1.Use the exact image location URL instead of directory format i.e. don't use images/OG_thumb.jpg

2.Case sensitive file extension: If the image extension name on your hosting provider is ".JPG" then do not use ".jpg" or ".jpeg' . I observed that based on hosting provider and browser combination error may or may not occur, so to be safe its easier to just match the case of file extension.

3.After doing above steps if the thumbnail preview is still not showing up in WhatsApp message then:

a. Force stop the mobile app ( I tried in Android) and try again

b.Use online tool to preview the OG tag eg I used : https://searchenginereports.net/open-graph-checker

c. In mobile browser paste direct link to the OG thumb and refresh the browser 4-5 times . eg https://bla123neocities.org/nmp/images/thumbs/IMG_327.JPG

Why is the <center> tag deprecated in HTML?

HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.

How do I release memory used by a pandas dataframe?

del df will not be deleted if there are any reference to the df at the time of deletion. So you need to to delete all the references to it with del df to release the memory.

So all the instances bound to df should be deleted to trigger garbage collection.

Use objgragh to check which is holding onto the objects.

How do I create a file at a specific path?

The besty practice is to use '/' and a so called 'raw string' to define file path in Python.

path = r"C:/Test.py"

However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.

Is it possible to do a sparse checkout without checking out the whole repository first?

I took this from TypeScript definitions library @types:

Let's say the repo has this structure:

types/
|_ dependency/

?? This requires minimum git version 2.27.0, which is likely newer than the default on most machines. More complicated procedures are available in older versions, but not covered by this guide.

git clone --sparse --filter=blob:none --depth=1 <forkedUrl>
git sparse-checkout add types/<type> types/<dependency type> ...

This will check out the types/identity folder to your local machine.

--sparse initializes the sparse-checkout file so the working directory starts with only the files in the root of the repository.

--filter=blob:none will exclude files, fetching them only as needed.

--depth=1 will further improve clone speed by truncating commit history, but it may cause issues as summarized here.

How do I pass a method as a parameter in Python

Not exactly what you want, but a related useful tool is getattr(), to use method's name as a parameter.

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

Efficiently test if a port is open on Linux?

nc -l 8000

Where 8000 is the port number. If the port is free, it will start a server that you can close easily. If it isn't it will throw an error:

nc: Address already in use

Counting Chars in EditText Changed Listener

little few change in your code :

TextView tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        tv.setText(String.valueOf(s.toString().length()));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

Is there a "between" function in C#?

So far, it looks like none of the answers have considered the likely possibility that dynamically, you don't know which value is the lower and upper bound. For the general case, you could create your own IsBetween method that would probably go something like:

    public bool IsBetween(double testValue, double bound1, double bound2)
    {
        return (testValue >= Math.Min(bound1,bound2) && testValue <= Math.Max(bound1,bound2));
    }

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

Turn a string into a valid filename?

You can use list comprehension together with the string methods.

>>> s
'foo-bar#baz?qux@127/\\9]'
>>> "".join(x for x in s if x.isalnum())
'foobarbazqux1279'

How to set <Text> text to upper case in react native

@Cherniv Thanks for the answer

<Text style={{}}> {'Test'.toUpperCase()} </Text>

Why does git say "Pull is not possible because you have unmerged files"?

If you dont want to merge the changes and still want to update your local then run:

git reset --hard HEAD  

This will reset your local with HEAD and then pull your remote using git pull.

If you've already committed your merge locally (but haven't pushed to remote yet), and want to revert it as well:

git reset --hard HEAD~1 

Get a random boolean in python?

u could try this it produces randomly generated array of true and false :

a=[bool(i) for i in np.array(np.random.randint(0,2,10))]

out: [True, True, True, True, True, False, True, False, True, False]

JavaFX How to set scene background image

You can change style directly for scene using .root class:

.root {
    -fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}

Add this to CSS and load it as "Uluk Biy" described in his answer.

Deleting rows from parent and child tables

If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.

e.g.

CREATE TABLE supplier 
( supplier_id numeric(10) not null, 
 supplier_name varchar2(50) not null, 
 contact_name varchar2(50),  
 CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) 
); 



CREATE TABLE products 
( product_id numeric(10) not null, 
 supplier_id numeric(10) not null, 
 CONSTRAINT fk_supplier 
   FOREIGN KEY (supplier_id) 
  REFERENCES supplier(supplier_id) 
  ON DELETE CASCADE 
); 

Delete the supplier, and it will delate all products for that supplier

Generate Java class from JSON?

Answering this old question with recent project ;-).

At the moment the best solution is probably JsonSchema2Pojo :

It does the job from the seldom used Json Schema but also with plain Json. It provides Ant and Maven plugin and an online test application can give you an idea of the tool. I put a Json Tweet and generated all the containing class (Tweet, User, Location, etc..).

We'll use it on Agorava project to generate Social Media mapping and follow the contant evolution in their API.

Get a json via Http Request in NodeJS

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

How to SELECT a dropdown list item by value programmatically

This is a simple way to select an option from a dropdownlist based on a string val

private void SetDDLs(DropDownList d,string val)
    {
        ListItem li;
        for (int i = 0; i < d.Items.Count; i++)
        {
            li = d.Items[i];
            if (li.Value == val)
            {
                d.SelectedIndex = i;
                break;
            }
        }
    }

Concatenating two one-dimensional NumPy arrays

The line should be:

numpy.concatenate([a,b])

The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.

From the NumPy documentation:

numpy.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays together.

It was trying to interpret your b as the axis parameter, which is why it complained it couldn't convert it into a scalar.

Set value for particular cell in pandas DataFrame with iloc

If you know the position, why not just get the index from that?

Then use .loc:

df.loc[index, 'COL_NAME'] = x

Live Video Streaming with PHP

PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.

For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.

Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.

PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).

Hope this helps.

Session variables in ASP.NET MVC

I would think you'll want to think about if things really belong in a session state. This is something I find myself doing every now and then and it's a nice strongly typed approach to the whole thing but you should be careful when putting things in the session context. Not everything should be there just because it belongs to some user.

in global.asax hook the OnSessionStart event

void OnSessionStart(...)
{
    HttpContext.Current.Session.Add("__MySessionObject", new MySessionObject());
}

From anywhere in code where the HttpContext.Current property != null you can retrive that object. I do this with an extension method.

public static MySessionObject GetMySessionObject(this HttpContext current)
{
    return current != null ? (MySessionObject)current.Session["__MySessionObject"] : null;
}

This way you can in code

void OnLoad(...)
{
    var sessionObj = HttpContext.Current.GetMySessionObject();
    // do something with 'sessionObj'
}

Excel Formula which places date/time in cell when data is entered in another cell in the same row

You can use If function Write in the cell where you want to input the date the following formula: =IF(MODIFIED-CELLNUMBER<>"",IF(CELLNUMBER-WHERE-TO-INPUT-DATE="",NOW(),CELLNUMBER-WHERE-TO-INPUT-DATE),"")

When is it acceptable to call GC.Collect?

As a memory fragmentation solution. I was getting out of memory exceptions while writing a lot of data into a memory stream (reading from a network stream). The data was written in 8K chunks. After reaching 128M there was exception even though there was a lot of memory available (but it was fragmented). Calling GC.Collect() solved the issue. I was able to handle over 1G after the fix.

How to get the previous url using PHP

I can't add a comment yet, so I wanted to share that HTTP_REFERER is not always sent.

Notice: Undefined index: HTTP_REFERER

How do I compare 2 rows from the same table (SQL Server)?

OK, after 2 years it's finally time to correct the syntax:

SELECT  t1.value, t2.value
FROM    MyTable t1
JOIN    MyTable t2
ON      t1.id = t2.id
WHERE   t1.id = @id
        AND t1.status = @status1
        AND t2.status = @status2

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

The following answer is to merge data into same table

MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
    ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif') 
WHEN NOT MATCHED THEN
        INSERT ( d.USERS_ID, d.USER_NAME)
        VALUES ('123','itszaif');

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert.

Run-time error '1004' - Method 'Range' of object'_Global' failed

When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.

If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.

inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.

The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like

With ThisWorkbook.Worksheets("Template")
    .Range(inputTemplateHeader).Value = NO_ENTRY
    .Range(inputTemplateContent).Value = NO_ENTRY
End With

Adjust the workbook and worksheet references to fit your particular situation.

Saving a select count(*) value to an integer (SQL Server)

[update] -- Well, my own foolishness provides the answer to this one. As it turns out, I was deleting the records from myTable before running the select COUNT statement.

How did I do that and not notice? Glad you asked. I've been testing a sql unit testing platform (tsqlunit, if you're interested) and as part of one of the tests I ran a truncate table statement, then the above. After the unit test is over everything is rolled back, and records are back in myTable. That's why I got a record count outside of my tests.

Sorry everyone...thanks for your help.

Manually map column names with class properties

Before you open the connection to your database, execute this piece of code for each of your poco classes:

// Section
SqlMapper.SetTypeMap(typeof(Section), new CustomPropertyTypeMap(
    typeof(Section), (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
    prop.GetCustomAttributes(false).OfType<ColumnAttribute>().Any(attr => attr.Name == columnName))));

Then add the data annotations to your poco classes like this:

public class Section
{
    [Column("db_column_name1")] // Side note: if you create aliases, then they would match this.
    public int Id { get; set; }
    [Column("db_column_name2")]
    public string Title { get; set; }
}

After that, you are all set. Just make a query call, something like:

using (var sqlConnection = new SqlConnection("your_connection_string"))
{
    var sqlStatement = "SELECT " +
                "db_column_name1, " +
                "db_column_name2 " +
                "FROM your_table";

    return sqlConnection.Query<Section>(sqlStatement).AsList();
}

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

The first line of link below saved my day:

To add values to options from your project’s build settings, prepend the value list with $(inherited).

https://github.com/CocoaPods/CocoaPods/wiki/Creating-a-project-that-uses-CocoaPods#faq

Also, do not forget to insert this line at the beginning of your pod file:

platform :iOS, '5.0'

CSS Font Border?

There's an experimental CSS property called text-stroke, supported on some browsers behind a -webkit prefix.

_x000D_
_x000D_
h1 {_x000D_
    -webkit-text-stroke: 2px black; /* width and color */_x000D_
_x000D_
    font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
_x000D_
_x000D_

Another possible trick would be to use four shadows, one pixel each on all directions, using property text-shadow:

_x000D_
_x000D_
h1 {_x000D_
    /* 1 pixel black shadow to left, top, right and bottom */_x000D_
    text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;_x000D_
_x000D_
    font-family: sans; color: yellow;_x000D_
}
_x000D_
<h1>Hello World</h1>
_x000D_
_x000D_
_x000D_

But it would get blurred for more than 1 pixel thickness.

Set initial focus in an Android application

@Someone Somewhere I used this to clear focus:

editText.clearFocus();

and it helps

Evaluating string "3*(4+2)" yield int 18

There is not. You will need to use some external library, or write your own parser. If you have the time to do so, I suggest to write your own parser as it is a quite interesting project. Otherwise you will need to use something like bcParser.

How to delete all files and folders in a folder by cmd call

I had an index folder with 33 folders that needed all the files and subfolders removed in them. I opened a command line in the index folder and then used these commands:

for /d in (*) do rd /s /q "%a" & (
md "%a")

I separated them into two lines (hit enter after first line, and when asked for more add second line) because if entered on a single line this may not work. This command will erase each directory and then create a new one which is empty, thus removing all files and subflolders in the original directory.

How to check version of python modules?

Assuming we are using Jupyter Notebook (if using Terminal, drop the exclamation marks):

1) if the package (e.g. xgboost) was installed with pip:

!pip show xgboost
!pip freeze | grep xgboost
!pip list | grep xgboost

2) if the package (e.g. caffe) was installed with conda:

!conda list caffe

How does cookie based authentication work?

A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.

To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.

There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.

A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.

How to link C++ program with Boost using CMake

Here is my take:

cmake_minimum_required(VERSION 3.15)

project(TryOuts LANGUAGES CXX)

find_package(Boost QUIET REQUIRED COMPONENTS program_options)

if(NOT Boost_FOUND)
    message(FATAL_ERROR "Boost Not found")
endif()

add_executable(helloworld main.cpp)

target_link_libraries(helloworld PUBLIC Boost::program_options)

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

Update: This will create a second context same as in applicationContext.xml

or you can add this code snippet to your web.xml

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

instead of

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

Map with Key as String and Value as List in Groovy

Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

// Java syntax 

Map<String,List> map1  = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1); 
assert map1.get("abc") == list1;

// slightly less Java-esque

def map2  = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2

// typical Groovy

def map3  = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3

How to wrap text in textview in Android

Try @Guykun's approach

android:layout_weight="1" android:ellipsize="none" android:maxLines="100" android:scrollHorizontally="false"

Also, make sure that parents width is not set to wrap content. This is the thing that I was missing.

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

Regex pattern for checking if a string starts with a certain substring?

You could use:

^(mailto|ftp|joe)

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

You could also look at the System.Uri class if you are parsing URIs.

jQuery ajax call to REST service

I think there is no need to specify

'http://localhost:8080`" 

in the URI part.. because. if you specify it, You'll have to change it manually for every environment.

Only

"/restws/json/product/get" also works

Setting up foreign keys in phpMyAdmin?

Step 1: You have to add the line: default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service. enter image description here

Step 2: Now when you create the table you will see the type of table is: InnoDB

enter image description here

Step 3: Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key: Select the Index Key from Action Label as shown below.

enter image description here

Step 4: Now open the Relation View in the same child table from bottom near the Print View as shown below.

enter image description here Step 5: Select the column U like to have the Foreign key as Select the Parent column from the drop down. dbName.TableName.ColumnName

Select appropriate Values for ON DELETE and ON UPDATE enter image description here

How to fast get Hardware-ID in C#?

I got here looking for the same thing and I found another solution. If you guys are interested I share this class:

using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
    /// </summary>
    public class FingerPrint  
    {
        private static string fingerPrint = string.Empty;
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " + 
            biosId() + "\nBASE >> " + baseId() +
                            //"\nDISK >> "+ diskId() + "\nVIDEO >> " + 
            videoId() +"\nMAC >> "+ macId()
                                     );
            }
            return fingerPrint;
        }
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration", 
                "MACAddress", "IPEnabled");
        }
        #endregion
    }
}

I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.

Note: Add reference to System.Management.

android get real path by Uri.getPath()

This helped me to get uri from Gallery and convert to a file for Multipart upload

File file = FileUtils.getFile(this, fileUri);

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

Force LF eol in git repo and working copy

Without a bit of information about what files are in your repository (pure source code, images, executables, ...), it's a bit hard to answer the question :)

Beside this, I'll consider that you're willing to default to LF as line endings in your working directory because you're willing to make sure that text files have LF line endings in your .git repository wether you work on Windows or Linux. Indeed better safe than sorry....

However, there's a better alternative: Benefit from LF line endings in your Linux workdir, CRLF line endings in your Windows workdir AND LF line endings in your repository.

As you're partially working on Linux and Windows, make sure core.eol is set to native and core.autocrlf is set to true.

Then, replace the content of your .gitattributes file with the following

* text=auto

This will let Git handle the automagic line endings conversion for you, on commits and checkouts. Binary files won't be altered, files detected as being text files will see the line endings converted on the fly.

However, as you know the content of your repository, you may give Git a hand and help him detect text files from binary files.

Provided you work on a C based image processing project, replace the content of your .gitattributes file with the following

* text=auto
*.txt text
*.c text
*.h text
*.jpg binary

This will make sure files which extension is c, h, or txt will be stored with LF line endings in your repo and will have native line endings in the working directory. Jpeg files won't be touched. All of the others will be benefit from the same automagic filtering as seen above.

In order to get a get a deeper understanding of the inner details of all this, I'd suggest you to dive into this very good post "Mind the end of your line" from Tim Clem, a Githubber.

As a real world example, you can also peek at this commit where those changes to a .gitattributes file are demonstrated.

UPDATE to the answer considering the following comment

I actually don't want CRLF in my Windows directories, because my Linux environment is actually a VirtualBox sharing the Windows directory

Makes sense. Thanks for the clarification. In this specific context, the .gitattributes file by itself won't be enough.

Run the following commands against your repository

$ git config core.eol lf
$ git config core.autocrlf input

As your repository is shared between your Linux and Windows environment, this will update the local config file for both environment. core.eol will make sure text files bear LF line endings on checkouts. core.autocrlf will ensure potential CRLF in text files (resulting from a copy/paste operation for instance) will be converted to LF in your repository.

Optionally, you can help Git distinguish what is a text file by creating a .gitattributes file containing something similar to the following:

# Autodetect text files
* text=auto

# ...Unless the name matches the following
# overriding patterns

# Definitively text files 
*.txt text
*.c text
*.h text

# Ensure those won't be messed up with
*.jpg binary
*.data binary

If you decided to create a .gitattributes file, commit it.

Lastly, ensure git status mentions "nothing to commit (working directory clean)", then perform the following operation

$ git checkout-index --force --all

This will recreate your files in your working directory, taking into account your config changes and the .gitattributes file and replacing any potential overlooked CRLF in your text files.

Once this is done, every text file in your working directory WILL bear LF line endings and git status should still consider the workdir as clean.

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

How to loop backwards in python?

range() and xrange() take a third parameter that specifies a step. So you can do the following.

range(10, 0, -1)

Which gives

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

But for iteration, you should really be using xrange instead. So,

xrange(10, 0, -1)

Note for Python 3 users: There are no separate range and xrange functions in Python 3, there is just range, which follows the design of Python 2's xrange.

When to Redis? When to MongoDB?

Redis and MongoDB are both non-relational databases but they're of different categories.

Redis is a Key/Value database, and it's using In-memory storage which makes it super fast. It's a good candidate for caching stuff and temporary data storage(in memory) and as the most of cloud platforms (such as Azure,AWS) support it, it's memory usage is scalable.But if you're gonna use it on your machines with limited resources, consider it's memory usage.

MongoDB on the other hand, is a document database. It's a good option for keeping large texts, images, videos, etc and almost anything you do with databases except transactions.For example if you wanna develop a blog or social network, MongoDB is a proper choice. It's scalable with scale-out strategy. It uses disk as storage media, so data would be persisted.

How to convert an NSString into an NSNumber

If you know that you receive integers, you could use:

NSString* val = @"12";
[NSNumber numberWithInt:[val intValue]];

Regular expression to match non-ASCII characters?

Unicode Property Escapes are among the features of ES2018.

Basic Usage

With Unicode Property Escapes, you can match a letter from any language with the following simple regular expression:

/\p{Letter}/u

Or with the shorthand, even terser:

/\p{L}/u

Matching Words

Regarding the question's concrete use case (matching words), note that you can use Unicode Property Escapes in character classes, making it easy to match letters together with other word-characters like hyphens:

/[\p{L}-]/u

Stitching it all together, you could match words of all[1] languages with this beautifully short RegEx:

/[\p{L}-]+/ug

Example (shamelessly plugged from the answer above):

'Düsseldorf, Köln, ??????, ???, ??????? !@#$'.match(/[\p{L}-]+/ug)

// ["Düsseldorf", "Köln", "??????", "???", "???????"]

[1] Note that I'm not an expert on languages. You may still want to do your own research regarding other characters that might be parts of words besides letters and hyphens.

Browser Support

This feature is available in all major evergreen browsers.

Transpiling

If support for older browsers is needed, Unicode Property Escapes can be transpiled to ES5 with a tool called regexpu. There's an online demo available here. As you can see in the demo, you can in fact match non-latin letters today with the following (horribly long) ES5 regular expression:

/(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])/

If you're using Babel, there's also a regexpu-powered plugin for that (Babel v6 plugin, Babel v7 plugin).

Java division by zero doesnt throw an ArithmeticException - why?

There is a trick, Arithmetic exceptions only happen when you are playing around with integers and only during / or % operation.

If there is any floating point number in an arithmetic operation, internally all integers will get converted into floating point. This may help you to remember things easily.

Row Offset in SQL Server

I would avoid using SELECT *. Specify columns you actually want even though it may be all of them.

SQL Server 2005+

SELECT col1, col2 
FROM (
    SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow

SQL Server 2000

Efficiently Paging Through Large Result Sets in SQL Server 2000

A More Efficient Method for Paging Through Large Result Sets

Install Node.js on Ubuntu

sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core
git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

http://jstricks.com/install-node-js/

How to get the selected radio button’s value?

Since jQuery 1.8, the correct syntax for the query is

$('input[name="genderS"]:checked').val();

Not $('input[@name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the @).

How to sort List of objects by some property

Java-8 solution using Stream API:

A. When timeStarted and timeEnded are public (as mentioned in the requirement) and therefore do not (need to) have public getter methods:

List<ActiveAlarm> sorted = 
    list.stream()
        .sorted(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted)
                        .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded))
        .collect(Collectors.toList());

B. When timeStarted and timeEnded have public getter methods:

List<ActiveAlarm> sorted = 
    list.stream()
        .sorted(Comparator.comparingLong(ActiveAlarm::getTimeStarted)
                        .thenComparingLong(ActiveAlarm::getTimeEnded))
        .collect(Collectors.toList());

If you want to sort the original list itself:

A. When timeStarted and timeEnded are public (as mentioned in the requirement) and therefore do not (need to) have public getter methods:

list.sort(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted)
                    .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded));

B. When timeStarted and timeEnded have public getter methods:

list.sort(Comparator.comparingLong(ActiveAlarm::getTimeStarted)
                    .thenComparingLong(ActiveAlarm::getTimeEnded));

How do you unit test private methods?

I want to create a clear code example here which you can use on any class in which you want to test private method.

In your test case class just include these methods and then employ them as indicated.

  /**
   *
   * @var Class_name_of_class_you_want_to_test_private_methods_in
   * note: the actual class and the private variable to store the 
   * class instance in, should at least be different case so that
   * they do not get confused in the code.  Here the class name is
   * is upper case while the private instance variable is all lower
   * case
   */
  private $class_name_of_class_you_want_to_test_private_methods_in;

  /**
   * This uses reflection to be able to get private methods to test
   * @param $methodName
   * @return ReflectionMethod
   */
  protected static function getMethod($methodName) {
    $class = new ReflectionClass('Class_name_of_class_you_want_to_test_private_methods_in');
    $method = $class->getMethod($methodName);
    $method->setAccessible(true);
    return $method;
  }

  /**
   * Uses reflection class to call private methods and get return values.
   * @param $methodName
   * @param array $params
   * @return mixed
   *
   * usage:     $this->_callMethod('_someFunctionName', array(param1,param2,param3));
   *  {params are in
   *   order in which they appear in the function declaration}
   */
  protected function _callMethod($methodName, $params=array()) {
    $method = self::getMethod($methodName);
    return $method->invokeArgs($this->class_name_of_class_you_want_to_test_private_methods_in, $params);
  }

$this->_callMethod('_someFunctionName', array(param1,param2,param3));

Just issue the parameters in the order that they appear in the original private function

How to trim leading and trailing white spaces of a string?

For trimming your string, Go's "strings" package have TrimSpace(), Trim() function that trims leading and trailing spaces.

Check the documentation for more information.

Pythonic way to combine FOR loop and IF statement

A simple way to find unique common elements of lists a and b:

a = [1,2,3]
b = [3,6,2]
for both in set(a) & set(b):
    print(both)

Freeze the top row for an html table only (Fixed Table Header Scrolling)

Using css zebra styling

Copy paste this example and see the header fixed.

       <style>
       .zebra tr:nth-child(odd){
       background:white;
       color:black;
       }

       .zebra tr:nth-child(even){
       background: grey;
       color:black;
       }

      .zebra tr:nth-child(1) {
       background:black;
       color:yellow;
       position: fixed;
       margin:-30px 0px 0px 0px;
       }
       </style>


   <DIV  id= "stripped_div"

         class= "zebra"
         style = "
            border:solid 1px red;
            height:15px;
            width:200px;
            overflow-x:none;
            overflow-y:scroll;
            padding:30px 0px 0px 0px;"
            >

                <table>
                   <tr >
                       <td>Name:</td>
                       <td>Age:</td>
                   </tr>
                    <tr >
                       <td>Peter</td>
                       <td>10</td>
                   </tr>
                </table>

    </DIV>

Notice the top padding of of 30px in the div leaves space that is utilized by the 1st row of stripped data ie tr:nth-child(1) that is "fixed position" and formatted to a margin of -30px

LINQ to SQL Left Outer Join

I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.

Using LINQPad I created the following LINQ query:

//Querying from both the CustomerInfo table and OrderInfo table
from cust in CustomerInfo
where cust.CustomerID == 123456
select new {cust, cust.OrderInfo}

Which was translated to the (slightly truncated) query below

 -- Region Parameters
 DECLARE @p0 Int = 123456
-- EndRegion
SELECT [t0].[CustomerID], [t0].[AlternateCustomerID],  [t1].[OrderID], [t1].[OnlineOrderID], (
    SELECT COUNT(*)
    FROM [OrderInfo] AS [t2]
    WHERE [t2].[CustomerID] = [t0].[CustomerID]
    ) AS [value]
FROM [CustomerInfo] AS [t0]
LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[CustomerID] = @p0
ORDER BY [t0].[CustomerID], [t1].[OrderID]

Notice the LEFT OUTER JOIN above.

Angularjs on page load call function

Instead of using onload, use Angular's ng-init.

<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">

Note: This requires that myFunction is a property of the CinemaCtrl scope.

Multi value Dictionary

I know this is an old thread, but - since it's not been mentioned this works

  Dictionary<string, object> LookUp = new Dictionary<string, object>();
  LookUp.Add("bob", new { age = "23", height = "2.1m", weight = "110kg"});
  LookUp.Add("jasper", new { age = "33", height = "1.75m", weight = "90kg"});
  foreach(KeyValuePair<string, object> entry in LookUp )
  {
      object person = entry.Value;
      Console.WriteLine("Person name:" + entry.Key + " Age: "  + person.age);          
  }

Constructor of an abstract class in C#

It's a way to enforce a set of invariants of the abstract class. That is, no matter what the subclass does, you want to make sure some things are always true of the base class... example:

abstract class Foo
{
    public DateTime TimeCreated {get; private set;}

    protected Foo()
    {
         this.TimeCreated = DateTime.Now;
    }
}

abstract class Bar : Foo
{
    public Bar() : base() //Bar's constructor's must call Foo's parameterless constructor.
    { }
}

Don't think of a constructor as the dual of the new operator. The constructor's only purpose is to ensure that you have an object in a valid state before you start using it. It just happens to be that we usually call it through a new operator.

Show div on scrollDown after 800px

If you want to show a div after scrolling a number of pixels:

Working Example

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});

_x000D_
_x000D_
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});
_x000D_
body {
  height: 1600px;
}
.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll down... </p>
<div class="bottomMenu"></div>
_x000D_
_x000D_
_x000D_

Its simple, but effective.

Documentation for .scroll()
Documentation for .scrollTop()


If you want to show a div after scrolling a number of pixels,

without jQuery:

Working Example

myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 800) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);

_x000D_
_x000D_
myID = document.getElementById("myID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 800) {
    myID.className = "bottomMenu show"
  } else {
    myID.className = "bottomMenu hide"
  }
};

window.addEventListener("scroll", myScrollFunc);
_x000D_
body {
  height: 2000px;
}
.bottomMenu {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
  transition: all 1s;
}
.hide {
  opacity: 0;
  left: -100%;
}
.show {
  opacity: 1;
  left: 0;
}
_x000D_
<div id="myID" class="bottomMenu hide"></div>
_x000D_
_x000D_
_x000D_

Documentation for .scrollY
Documentation for .className
Documentation for .addEventListener


If you want to show an element after scrolling to it:

Working Example

$('h1').each(function () {
    var y = $(document).scrollTop();
    var t = $(this).parent().offset().top;
    if (y > t) {
        $(this).fadeIn();
    } else {
        $(this).fadeOut();
    }
});

_x000D_
_x000D_
$(document).scroll(function() {
  //Show element after user scrolls 800px
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }

  // Show element after user scrolls past 
  // the top edge of its parent 
  $('h1').each(function() {
    var t = $(this).parent().offset().top;
    if (y > t) {
      $(this).fadeIn();
    } else {
      $(this).fadeOut();
    }
  });
});
_x000D_
body {
  height: 1600px;
}
.bottomMenu {
  display: none;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  border-top: 1px solid #000;
  background: red;
  z-index: 1;
}
.scrollPast {
  width: 100%;
  height: 150px;
  background: blue;
  position: relative;
  top: 50px;
  margin: 20px 0;
}
h1 {
  display: none;
  position: absolute;
  bottom: 0;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Down...</p>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

</div>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

</div>
<div class="scrollPast">
  <h1>I fade in when you scroll to my parent</h1>

</div>
<div class="bottomMenu">I fade in when you scroll past 800px</div>
_x000D_
_x000D_
_x000D_

Note that you can't get the offset of elements set to display: none;, grab the offset of the element's parent instead.

Documentation for .each()
Documentation for .parent()
Documentation for .offset()


If you want to have a nav or div stick or dock to the top of the page once you scroll to it and unstick/undock when you scroll back up:

Working Example

$(document).scroll(function () {
    //stick nav to top of page
    var y = $(this).scrollTop();
    var navWrap = $('#navWrap').offset().top;
    if (y > navWrap) {
        $('nav').addClass('sticky');
    } else {
        $('nav').removeClass('sticky');
    }
});

#navWrap {
    height:70px
}
nav {
    height: 70px;
    background:gray;
}
.sticky {
    position: fixed;
    top:0;
}

_x000D_
_x000D_
$(document).scroll(function () {
    //stick nav to top of page
    var y = $(this).scrollTop();
    var navWrap = $('#navWrap').offset().top;
    if (y > navWrap) {
        $('nav').addClass('sticky');
    } else {
        $('nav').removeClass('sticky');
    }
});
_x000D_
body {
    height:1600px;
    margin:0;
}
#navWrap {
    height:70px
}
nav {
    height: 70px;
    background:gray;
}
.sticky {
    position: fixed;
    top:0;
}
h1 {
    margin: 0;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
  imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
  oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
<div id="navWrap">
  <nav>
    <h1>I stick to the top when you scroll down and unstick when you scroll up to my original position</h1>

  </nav>
</div>
<p>Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless creaturas,
  imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus. Zonbi tattered for solum
  oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.</p>
_x000D_
_x000D_
_x000D_

JavaScript: How to get parent element by selector?

Here is simple way to access parent id

document.getElementById("child1").parentNode;

will do the magic for you to access the parent div.

<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>

Set the layout weight of a TextView programmatically

You have to use TableLayout.LayoutParams with something like this:

TextView tv = new TextView(v.getContext());
tv.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));

The last parameter is the weight.

Mapping composite keys using EF code first

For Mapping Composite primary key using Entity framework we can use two approaches.

1) By Overriding the OnModelCreating() Method

For ex: I have the model class named VehicleFeature as shown below.

public class VehicleFeature
{
    public int VehicleId { get; set; }
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

The Code in my DBContext would be like ,

public class VegaDbContext : DbContext
{
    public DbSet<Make> Makes{get;set;}

    public DbSet<Feature> Features{get;set;}
    public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)        
    {           

    }
    // we override the OnModelCreating method here.
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
    }
}

2) By Data Annotations.

public class VehicleFeature
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    [Key]
    public int VehicleId { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    [Key]
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

Please refer the below links for the more information.

1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx

2) How to add a composite unique key using EF 6 Fluent Api?

How to use UIPanGestureRecognizer to move object? iPhone/iPad

swift 2 version of the @MS AppTech answer

func handlePan(panGest : UIPanGestureRecognizer) {
let velocity : CGPoint = panGest.velocityInView(self.view);
        let magnitude : CGFloat = CGFloat(sqrtf((Float(velocity.x) * Float(velocity.x)) + (Float(velocity.y) * Float(velocity.y))));
        let slideMult :CGFloat = magnitude / 200;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

        let slideFactor : CGFloat = 0.1 * slideMult; // Increase for more of a slide
        var finalPoint : CGPoint = CGPointMake(panGest.view!.center.x + (velocity.x * slideFactor),
                                         panGest.view!.center.y + (velocity.y * slideFactor));
        finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height);

        UIView.animateWithDuration(Double(slideFactor*2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            panGest.view!.center = finalPoint;
            }, completion: nil)
}

XMLHttpRequest (Ajax) Error

So there might be a few things wrong here.

First start by reading how to use XMLHttpRequest.open() because there's a third optional parameter for specifying whether to make an asynchronous request, defaulting to true. That means you're making an asynchronous request and need to specify a callback function before you do the send(). Here's an example from MDN:

var oXHR = new XMLHttpRequest();

oXHR.open("GET", "http://www.mozilla.org/", true);

oXHR.onreadystatechange = function (oEvent) {
    if (oXHR.readyState === 4) {
        if (oXHR.status === 200) {
          console.log(oXHR.responseText)
        } else {
           console.log("Error", oXHR.statusText);
        }
    }
};

oXHR.send(null);

Second, since you're getting a 101 error, you might use the wrong URL. So make sure that the URL you're making the request with is correct. Also, make sure that your server is capable of serving your quiz.xml file.

You'll probably have to debug by simplifying/narrowing down where the problem is. So I'd start by making an easy synchronous request so you don't have to worry about the callback function. So here's another example from MDN for making a synchronous request:

var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false); 
request.send(null);

if (request.status == 0)
    console.log(request.responseText);

Also, if you're just starting out with Javascript, you could refer to MDN for Javascript API documentation/examples/tutorials.

Most efficient way to prepend a value to an array

f you need to preserve the old array, slice the old one and unshift the new value(s) to the beginning of the slice.

var oldA=[4,5,6];
newA=oldA.slice(0);
newA.unshift(1,2,3)

oldA+'\n'+newA

/*  returned value:
4,5,6
1,2,3,4,5,6
*/

How to set "style=display:none;" using jQuery's attr method?

You can use the jquery attr() method to achieve the setting of teh attribute and the method removeAttr() to delete the attribute for your element msform As seen in the code

$('#msform').attr('style', 'display:none;');


$('#msform').removeAttr('style');

How to use Tomcat 8 in Eclipse?

The latest version of Springsource STS (3.6) supports Tomcat 8. It is based on eclipse Luna 4.4 and supports Java 8. Have at it!

How to ensure a <select> form field is submitted when it is disabled?

Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.

Cannot open backup device. Operating System error 5

I had this issue recently as well, however I was running the backup job from server A but the database being backed up was on server B to a file share on server C. When the agent on server A tells server B to run a backup t-sql command, its actually the service account that sql is running under on SERVER B that attempts to write the backup to server C.

Just remember, its the service account of the sql server performing the actual BACKUP DATABASE command is what needs privileges on the file system, not the agent.

Do we have router.reload in vue-router?

this.$router.go(this.$router.currentRoute)

Vue-Router Docs:

I checked vue-router repo on GitHub and it seems that there isn't reload() method any more. But in the same file, there is: currentRoute object.

Source: vue-router/src/index.js
Docs: docs

get currentRoute (): ?Route {
    return this.history && this.history.current
  }

Now you can use this.$router.go(this.$router.currentRoute) for reload current route.

Simple example.

Version for this answer:

"vue": "^2.1.0",
"vue-router": "^2.1.1"

ASP.NET MVC 3 Razor - Adding class to EditorFor

It is possible to provide a class or other information through AdditionalViewData - I use this where I'm allowing a user to create a form based on database fields (propertyName, editorType, and editorClass).

Based on your initial example:

@Html.EditorFor(x => x.Created, new { cssClass = "date" })

and in the custom template:

<div>
    @Html.TextBoxFor(x => x.Created, new { @class = ViewData["cssClass"] })
</div>

Convert Long into Integer

The best simple way of doing so is:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }

UITableView, Separator color where to set?

Try + (instancetype)appearance of UITableView:

Objective-C:

[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"

Swift 3.0:

UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"

Note: Change will reflect to all tables used in application.

Click events on Pie Charts in Chart.js

Update: As @Soham Shetty comments, getSegmentsAtEvent(event) only works for 1.x and for 2.x getElementsAtEvent should be used.

.getElementsAtEvent(e)

Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.

Calling getElementsAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.

canvas.onclick = function(evt){
    var activePoints = myLineChart.getElementsAtEvent(evt);
    // => activePoints is an array of points on the canvas that are at the same position as the click event.
};

Example: https://jsfiddle.net/u1szh96g/208/


Original answer (valid for Chart.js 1.x version):

You can achieve this using getSegmentsAtEvent(event)

Calling getSegmentsAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the segment elements that are at that the same position of that event.

From: Prototype Methods

So you can do:

$("#myChart").click( 
    function(evt){
        var activePoints = myNewChart.getSegmentsAtEvent(evt);           
        /* do something */
    }
);  

Here is a full working example:

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.js"></script>
        <script type="text/javascript" src="Chart.js"></script>
        <script type="text/javascript">
            var data = [
                {
                    value: 300,
                    color:"#F7464A",
                    highlight: "#FF5A5E",
                    label: "Red"
                },
                {
                    value: 50,
                    color: "#46BFBD",
                    highlight: "#5AD3D1",
                    label: "Green"
                },
                {
                    value: 100,
                    color: "#FDB45C",
                    highlight: "#FFC870",
                    label: "Yellow"
                }
            ];

            $(document).ready( 
                function () {
                    var ctx = document.getElementById("myChart").getContext("2d");
                    var myNewChart = new Chart(ctx).Pie(data);

                    $("#myChart").click( 
                        function(evt){
                            var activePoints = myNewChart.getSegmentsAtEvent(evt);
                            var url = "http://example.com/?label=" + activePoints[0].label + "&value=" + activePoints[0].value;
                            alert(url);
                        }
                    );                  
                }
            );
        </script>
    </head>
    <body>
        <canvas id="myChart" width="400" height="400"></canvas>
    </body>
</html>

How to find numbers from a string?

Regular expressions are built to parse. While the syntax can take a while to pick up on this approach is very efficient, and is very flexible for handling more complex string extractions/replacements

Sub Tester()
     MsgBox CleanString("3d1fgd4g1dg5d9gdg")
End Sub

Function CleanString(strIn As String) As String
    Dim objRegex
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
     .Global = True
     .Pattern = "[^\d]+"
    CleanString = .Replace(strIn, vbNullString)
    End With
End Function

how to run a command at terminal from java program?

I know this question is quite old, but here's a library that encapsulates the ProcessBuilder api.

How to fix the "508 Resource Limit is reached" error in WordPress?

Actually it happens when the number of processes exceeds the limits set by the hosting provider.

To avoid either we need to enhance the capacity by hosting providers or we need to check in the code whether any process takes longer time (like background tasks).

TortoiseGit-git did not exit cleanly (exit code 1)

Right from my experience, I most often get this when I have locally changed files that will be over ridden by the pull, you need to stash or move the files before you can pull it.

How to bind to a PasswordBox in MVVM

I posted a GIST here that is a bindable password box.

using System.Windows;
using System.Windows.Controls;

namespace CustomControl
{
    public class BindablePasswordBox : Decorator
    {
        /// <summary>
        /// The password dependency property.
        /// </summary>
        public static readonly DependencyProperty PasswordProperty;

        private bool isPreventCallback;
        private RoutedEventHandler savedCallback;

        /// <summary>
        /// Static constructor to initialize the dependency properties.
        /// </summary>
        static BindablePasswordBox()
        {
            PasswordProperty = DependencyProperty.Register(
                "Password",
                typeof(string),
                typeof(BindablePasswordBox),
                new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnPasswordPropertyChanged))
            );
        }

        /// <summary>
        /// Saves the password changed callback and sets the child element to the password box.
        /// </summary>
        public BindablePasswordBox()
        {
            savedCallback = HandlePasswordChanged;

            PasswordBox passwordBox = new PasswordBox();
            passwordBox.PasswordChanged += savedCallback;
            Child = passwordBox;
        }

        /// <summary>
        /// The password dependency property.
        /// </summary>
        public string Password
        {
            get { return GetValue(PasswordProperty) as string; }
            set { SetValue(PasswordProperty, value); }
        }

        /// <summary>
        /// Handles changes to the password dependency property.
        /// </summary>
        /// <param name="d">the dependency object</param>
        /// <param name="eventArgs">the event args</param>
        private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs eventArgs)
        {
            BindablePasswordBox bindablePasswordBox = (BindablePasswordBox) d;
            PasswordBox passwordBox = (PasswordBox) bindablePasswordBox.Child;

            if (bindablePasswordBox.isPreventCallback)
            {
                return;
            }

            passwordBox.PasswordChanged -= bindablePasswordBox.savedCallback;
            passwordBox.Password = (eventArgs.NewValue != null) ? eventArgs.NewValue.ToString() : "";
            passwordBox.PasswordChanged += bindablePasswordBox.savedCallback;
        }

        /// <summary>
        /// Handles the password changed event.
        /// </summary>
        /// <param name="sender">the sender</param>
        /// <param name="eventArgs">the event args</param>
        private void HandlePasswordChanged(object sender, RoutedEventArgs eventArgs)
        {
            PasswordBox passwordBox = (PasswordBox) sender;

            isPreventCallback = true;
            Password = passwordBox.Password;
            isPreventCallback = false;
        }
    }
}

How to change text color and console color in code::blocks?

Functions like textcolor worked in old compilers like turbo C and Dev C. In today's compilers these functions would not work. I am going to give two function SetColor and ChangeConsoleToColors. You copy paste these functions code in your program and do the following steps.The code I am giving will not work in some compilers.

The code of SetColor is -

 void SetColor(int ForgC)
 {
     WORD wColor;

      HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
      CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                 //Mask out all but the background attribute, and add in the forgournd     color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
 }

To use this function you need to call it from your program. For example I am taking your sample program -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(void)
{
  SetColor(4);
  printf("\n \n \t This text is written in Red Color \n ");
  getch();
  return 0;
}

void SetColor(int ForgC)
 {
 WORD wColor;

  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                 //Mask out all but the background attribute, and add in the forgournd color
      wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
      SetConsoleTextAttribute(hStdOut, wColor);
 }
 return;
}

When you run the program you will get the text color in RED. Now I am going to give you the code of each color -

Name         | Value
             |
Black        |   0
Blue         |   1
Green        |   2
Cyan         |   3
Red          |   4
Magenta      |   5
Brown        |   6
Light Gray   |   7
Dark Gray    |   8
Light Blue   |   9
Light Green  |   10
Light Cyan   |   11
Light Red    |   12
Light Magenta|   13
Yellow       |   14
White        |   15

Now I am going to give the code of ChangeConsoleToColors. The code is -

void ClearConsoleToColors(int ForgC, int BackC)
 {
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
  DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
}

In this function you pass two numbers. If you want normal colors just put the first number as zero and the second number as the color. My example is -

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);

int main()
{
ClearConsoleToColors(0,15);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
 DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
} 

In this case I have put the first number as zero and the second number as 15 so the console color will be white as the code for white is 15. This is working for me in code::blocks. Hope it works for you too.

A Generic error occurred in GDI+ in Bitmap.Save method

In my case the bitmap image file already existed in the system drive, so my app threw the error "A Generic error occured in GDI+".

  1. Verify that the destination folder exists
  2. Verify that there isn't already a file with the same name in the destination folder

Compare two files report difference in python

You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.

How can a divider line be added in an Android RecyclerView?

All of these answers got me close but they were each missing a key detail. After a bit of research, I found the easiest route to be a combination of these 3 steps:

  1. Use the support library's DividerItemDecoration
  2. Create a divider with the right color
  3. Set this divider in your theme as the listDivider

Step 1: while configuring RecyclerView

recyclerView.addItemDecoration(
        new DividerItemDecoration(context, layoutManager.getOrientation()));

Step 2: in a file like res/drawable/divider_gray.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:width="1px" android:height="1px" />
    <solid android:color="@color/gray" />
</shape>

Step 3: in the app's theme

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Other theme items above -->
    <item name="android:listDivider">@drawable/divider_gray</item>
</style>

EDIT: Updated to skip last divider:
After using this a bit, I realized it was drawing a divider after the last item, which was annoying. So I modified Step 1 as follows to override that default behavior in DividerItemDecoration (of course, making a separate class is another option):

recyclerView.addItemDecoration(
        new DividerItemDecoration(context, layoutManager.getOrientation()) {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                // hide the divider for the last child
                if (position == parent.getAdapter().getItemCount() - 1) {
                    outRect.setEmpty();
                } else {
                    super.getItemOffsets(outRect, view, parent, state);
                }
            }
        }
);

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

What datatype should be used for storing phone numbers in SQL Server 2005?

SQL Server 2005 is pretty well optimized for substring queries for text in indexed varchar fields. For 2005 they introduced new statistics to the string summary for index fields. This helps significantly with full text searching.

What are invalid characters in XML

In summary, valid characters in the text are:

  • tab, line-feed and carriage-return.
  • all non-control characters are valid except & and <.
  • > is not valid if following ]].

Sections 2.2 and 2.4 of the XML specification provide the answer in detail:

Characters

Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646

Character data

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

Changing Java Date one hour back

You can use from bellow code for date and time :

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       //get current date time with Calendar()
       Calendar cal = Calendar.getInstance();
       System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));

       cal.add(Calendar.DATE, 1);
       System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, 1);
       System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, 1);
       System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, 1);
       System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, 1);
       System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, 1);
       System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.DATE, -1);
       System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, -1);
       System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, -1);
       System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, -1);
       System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, -1);
       System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, -1);
       System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));

Output :

Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52

This link is good : See here

And see : See too

And : Here

And : Here

And : Here

If you need just time :

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

Use of min and max functions in C++

There is an important difference between std::min, std::max and fmin and fmax.

std::min(-0.0,0.0) = -0.0
std::max(-0.0,0.0) = -0.0

whereas

fmin(-0.0, 0.0) = -0.0
fmax(-0.0, 0.0) =  0.0

So std::min is not a 1-1 substitute for fmin. The functions std::min and std::max are not commutative. To get the same result with doubles with fmin and fmax one should swap the arguments

fmin(-0.0, 0.0) = std::min(-0.0,  0.0)
fmax(-0.0, 0.0) = std::max( 0.0, -0.0)

But as far as I can tell all these functions are implementation defined anyway in this case so to be 100% sure you have to test how they are implemented.


There is another important difference. For x ! = NaN:

std::max(Nan,x) = NaN
std::max(x,NaN) = x
std::min(Nan,x) = NaN
std::min(x,NaN) = x

whereas

fmax(Nan,x) = x
fmax(x,NaN) = x
fmin(Nan,x) = x
fmin(x,NaN) = x

fmax can be emulated with the following code

double myfmax(double x, double y)
{
   // z > nan for z != nan is required by C the standard
   int xnan = isnan(x), ynan = isnan(y);
   if(xnan || ynan) {
        if(xnan && !ynan) return y;
        if(!xnan && ynan) return x;
        return x;
   }
   // +0 > -0 is preferred by C the standard 
   if(x==0 && y==0) {
       int xs = signbit(x), ys = signbit(y);
       if(xs && !ys) return y;
       if(!xs && ys) return x;
       return x;
   }
   return std::max(x,y);
}

This shows that std::max is a subset of fmax.

Looking at the assembly shows that Clang uses builtin code for fmax and fmin whereas GCC calls them from a math library. The assembly for clang for fmax with -O3 is

movapd  xmm2, xmm0
cmpunordsd      xmm2, xmm2
movapd  xmm3, xmm2
andpd   xmm3, xmm1
maxsd   xmm1, xmm0
andnpd  xmm2, xmm1
orpd    xmm2, xmm3
movapd  xmm0, xmm2

whereas for std::max(double, double) it is simply

maxsd   xmm0, xmm1

However, for GCC and Clang using -Ofast fmax becomes simply

maxsd   xmm0, xmm1

So this shows once again that std::max is a subset of fmax and that when you use a looser floating point model which does not have nan or signed zero then fmax and std::max are the same. The same argument obviously applies to fmin and std::min.

how to fetch data from database in Hibernate

The correct way from hibernate doc:

    Session s = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {

        tx = s.beginTransaction();        

        // here get object
        List<Employee> list = s.createCriteria(Employee.class).list();

        tx.commit();

    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }            
        Logger.getLogger("con").info("Exception: " + ex.getMessage());
        ex.printStackTrace(System.err);
    } finally {
        s.close(); 
    }

HibernateUtil code (can find at Google):

            public class HibernateUtil {

                private static final SessionFactory tmrSessionFactory;
                private static final Ejb3Configuration tmrEjb3Config;
                private static final EntityManagerFactory tmrEntityManagerFactory;

                static {

                    try {

                        tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
                        tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
                        tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();

                    } catch (HibernateException ex) {
                        Logger.getLogger("app").log(Level.WARN, ex.getMessage());
                        throw new ExceptionInInitializerError(ex);
                    }
                }

                public static SessionFactory getSessionFactory() {
                    return tmrSessionFactory;
                }

                /* getters and setters here */


            }

Shell script - remove first and last quote (") from a variable

The shortest way around - try:

echo $opt | sed "s/\"//g"

It actually removes all "s (double quotes) from opt (are there really going to be any more double quotes other than in the beginning and the end though? So it's actually the same thing, and much more brief ;-))

Is "else if" faster than "switch() case"?

Switch is generally faster than a long list of ifs because the compiler can generate a jump table. The longer the list, the better a switch statement is over a series of if statements.

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

Jingle Sort, as described here.

You give each value in your list to a different child on Christmas. Children, being awful human beings, will compare the value of their gifts and sort themselves accordingly.

Can't append <script> element

I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );

From: JSON for jQuery

How to add font-awesome to Angular 2 + CLI project

This post describes how to integrate Fontawesome 5 into Angular 6 (Angular 5 and previous versions will also work, but then you have to adjust my writings)

Option 1: Add the css-Files

Pro: Every icon will be included

Contra: Every icon will be included (bigger app size because all fonts are included)

Add the following package:

npm install @fortawesome/fontawesome-free-webfonts

Afterwards add the following lines to your angular.json:

"app": {
....
"styles": [
....
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fontawesome.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-regular.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-brands.css",
"node_modules/@fortawesome/fontawesome-free-webfonts/css/fa-solid.css"
],
...    
}

Option 2: Angular package

Pro: Smaller app size

Contra: You have to include every icon you want to use seperatly

Use the FontAwesome 5 Angular package:

npm install @fortawesome/angular-fontawesome

Just follow their documentation to add the icons. They use the svg-icons, so you only have to add the svgs / icons, you really use.

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

What is an IIS application pool?

An application pool is like a pond, if I create 2 application pools, first application pool has 100 fishes and another application pool has 200 fishes, here fish is like an application in application pool. They are managed by worker processes. Best advantage is: if pound number-1 has bad water and cases all fish are effected then there is security of fish in pound number-2. Like this if any application pool is effected by any problem but there is not any effect of this problem in application pool 2 so security in improve, and another profit is that is you provide all necessary authentication and rights to all applications in a single application pool.

What is the difference between user variables and system variables?

System environment variables are globally accessed by all users.
User environment variables are specific only to the currently logged-in user.

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

Here is a way to do it while passing in an extra argument:

https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

With the backend:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

.


And yet another way with an in-template filter only:

https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)

<div ng:app>
  <div ng-controller="HelloCntl">
    <ul>
       <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
            <span>{{friend.name}}</span>
            <span>{{friend.phone}}</span>
        </li>
    </ul>
</div>

ProcessStartInfo hanging on "WaitForExit"? Why?

Mark Byers' answer is excellent, but I would just add the following:

The OutputDataReceived and ErrorDataReceived delegates need to be removed before the outputWaitHandle and errorWaitHandle get disposed. If the process continues to output data after the timeout has been exceeded and then terminates, the outputWaitHandle and errorWaitHandle variables will be accessed after being disposed.

(FYI I had to add this caveat as an answer as I couldn't comment on his post.)

Pythonic way to check if a list is sorted or not

Definitely works in Python 3 and above for integers or strings:

def tail(t):
    return t[:]

letters = ['a', 'b', 'c', 'd', 'e']
rest = tail(letters)
rest.sort()
if letters == rest:
    print ('Given list is SORTED.')
else:
    print ('List NOT Sorted.')

=====================================================================

Another way of finding if the given list is sorted or not

trees1 = list ([1, 4, 5, 3, 2])
trees2 = list (trees1)
trees2.sort()
if trees1 == trees2:
    print ('trees1 is SORTED')
else:
    print ('Not sorted')

log4net vs. Nlog

Shameless plug for an open source project I run, but given the lively discussion about which .NET logging framework is more active I thought I'd post an obligatory link to Serilog.

To use within an application, Serilog is similar to (and draws heavily on) log4net. Unlike other .NET logging options, however, Serilog is about preserving the structure of log events for offline analysis. When you write:

Log.Information("The answer is {Answer}", 42);

Most logging libraries immediately render the message into a string. Serilog can do that too, but it preserves the { Answer: 42 } property so that later on, using one of a number of NoSQL data stores, you can properly query events based on the value of Answer.

We're close to a 1.0 and support all of the modern (.NET 4.5, Windows Store and Windows Phone 8) platforms.

Checking host availability by using ping in bash scripts

This is a complete bash script which pings target every 5 seconds and logs errors to a file.

Enjoy!

#!/bin/bash
        
        FILE=errors.txt
        TARGET=192.168.0.1

          touch $FILE
          while true;
          do
            DATE=$(date '+%d/%m/%Y %H:%M:%S')
            ping -c 1 $TARGET &> /dev/null
            if [[ $? -ne 0 ]]; then
              echo "ERROR "$DATE
              echo $DATE >> $FILE
            else
              echo "OK "$DATE
            fi
              sleep 5
          done

Using varchar(MAX) vs TEXT on SQL Server

  • Basic Definition

TEXT and VarChar(MAX) are Non-Unicode large Variable Length character data type, which can store maximum of 2147483647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).

  • Which one to Use?

As per MSDN link Microsoft is suggesting to avoid using the Text datatype and it will be removed in a future versions of Sql Server. Varchar(Max) is the suggested data type for storing the large string values instead of Text data type.

  • In-Row or Out-of-Row Storage

Data of a Text type column is stored out-of-row in a separate LOB data pages. The row in the table data page will only have a 16 byte pointer to the LOB data page where the actual data is present. While Data of a Varchar(max) type column is stored in-row if it is less than or equal to 8000 byte. If Varchar(max) column value is crossing the 8000 bytes then the Varchar(max) column value is stored in a separate LOB data pages and row will only have a 16 byte pointer to the LOB data page where the actual data is present. So In-Row Varchar(Max) is good for searches and retrieval.

  • Supported/Unsupported Functionalities

Some of the string functions, operators or the constructs which doesn’t work on the Text type column, but they do work on VarChar(Max) type column.

  1. = Equal to Operator on VarChar(Max) type column
  2. Group by clause on VarChar(Max) type column

    • System IO Considerations

As we know that the VarChar(Max) type column values are stored out-of-row only if the length of the value to be stored in it is greater than 8000 bytes or there is not enough space in the row, otherwise it will store it in-row. So if most of the values stored in the VarChar(Max) column are large and stored out-of-row, the data retrieval behavior will almost similar to the one that of the Text type column.

But if most of the values stored in VarChar(Max) type columns are small enough to store in-row. Then retrieval of the data where LOB columns are not included requires the more number of data pages to read as the LOB column value is stored in-row in the same data page where the non-LOB column values are stored. But if the select query includes LOB column then it requires less number of pages to read for the data retrieval compared to the Text type columns.

Conclusion

Use VarChar(MAX) data type rather than TEXT for good performance.

Source

How to initailize byte array of 100 bytes in java with all 0's

byte[] bytes = new byte[100];

Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.

Reliable way for a Bash script to get the full path to itself

Here's what I've come up with (edit: plus some tweaks provided by sfstewman, levigroker, Kyle Strand, and Rob Kennedy), that seems to mostly fit my "better" criteria:

SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

That SCRIPTPATH line seems particularly roundabout, but we need it rather than SCRIPTPATH=`pwd` in order to properly handle spaces and symlinks.

The inclusion of output redirection (>/dev/null 2>&1) handles the rare(?) case where cd might produce output that would interfere with the surrounding $( ... ) capture. (Such as cd being overridden to also ls a directory after switching to it.)

Note also that esoteric situations, such as executing a script that isn't coming from a file in an accessible file system at all (which is perfectly possible), is not catered to there (or in any of the other answers I've seen).

How to use protractor to check if an element is visible?

I had a similar issue, in that I only wanted return elements that were visible in a page object. I found that I'm able to use the css :not. In the case of this issue, this should do you...

expect($('i.icon-spinner:not(.ng-hide)').isDisplayed()).toBeTruthy();

In the context of a page object, you can get ONLY those elements that are visible in this way as well. Eg. given a page with multiple items, where only some are visible, you can use:

this.visibileIcons = $$('i.icon:not(.ng-hide)'); 

This will return you all visible i.icons

How to Convert the value in DataTable into a string array in c#

    private string[] GetPrimaryKeysofTable(string TableName)
    {
        string stsqlCommand = "SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
                              "WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1" +
                              "AND table_name = '" +TableName+ "'";
        SqlCommand command = new SqlCommand(stsqlCommand, Connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        adapter.Fill(table);

        string[] result = new string[table.Rows.Count];
        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            result[i++] = dr[0].ToString();
        }

        return result;
    }

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

You need to set up SSH keys.

This GitHub page explains how to generate keys.

If you have an existing key, you copy $HOME/.ssh/id_rsa.pub and paste it into the GitHub SSH settings page.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

It is important to understand that accessors restrict access to variable, but not their content. In ruby, like in some other OO languages, every variable is a pointer to an instance. So if you have an attribute to an Hash, for example, and you set it to be "read only" you always could change its content, but not the content of pointer. Look at this:

irb(main):024:0> class A
irb(main):025:1> attr_reader :a
irb(main):026:1> def initialize
irb(main):027:2> @a = {a:1, b:2}
irb(main):028:2> end
irb(main):029:1> end
=> :initialize
irb(main):030:0> a = A.new
=> #<A:0x007ffc5a10fe88 @a={:a=>1, :b=>2}>
irb(main):031:0> a.a
=> {:a=>1, :b=>2}
irb(main):032:0> a.a.delete(:b)
=> 2
irb(main):033:0> a.a
=> {:a=>1}
irb(main):034:0> a.a = {}
NoMethodError: undefined method `a=' for #<A:0x007ffc5a10fe88 @a={:a=>1}>
        from (irb):34
        from /usr/local/bin/irb:11:in `<main>'

As you can see is possible delete a key/value pair from the Hash @a, as add new keys, change values, eccetera. But you can't point to a new object because is a read only instance variable.

How to retrieve the dimensions of a view?

Use getMeasuredWidth() and getMeasuredHeight() for your view.

Developer guide: View

POI setting Cell Background to a Custom Color

Slot free in NPOI excel indexedcolors from 57+

            Color selColor;

        var wb = new HSSFWorkbook();

        var sheet = wb.CreateSheet("NPOI");
        var style = wb.CreateCellStyle();
        var font = wb.CreateFont();
        var palette = wb.GetCustomPalette();

        short indexColor = 57; 
        palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);

        font.Color = palette.GetColor(indexColor).Indexed;

hash keys / values as array

In ES5 supported (or shimmed) browsers...

var keys = Object.keys(myHash);

var values = keys.map(function(v) { return myHash[v]; });

Shims from MDN...

sql ORDER BY multiple values in specific order?

You can use a LEFT JOIN with a "VALUES ('f',1),('p',2),('a',3),('i',4)" and use the second column in your order-by expression. Postgres will use a Hash Join which will be much faster than a huge CASE if you have a lot of values. And it is easier to autogenerate.

If this ordering information is fixed, then it should have its own table.

How to represent matrices in python

Python doesn't have matrices. You can use a list of lists or NumPy

Async always WaitingForActivation

For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task class and TaskStatus enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.

In the context of methods marked as async, the resulting Task is not a Task representing the execution of the method, but a Task for the continuation of the method.

This is only able to make use of a few possible states:

  • Canceled
  • Faulted
  • RanToCompletion
  • WaitingForActivation

I understand that Runningcould appear to have been a better default than WaitingForActivation, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await-ing something else). The other option may have been to add a new value to TaskStatus, however this could have been a breaking change for existing applications and libraries.

All of this is very different to when making use of Task.Run which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus enumeration.

If you wish to keep track of the status of an async method, take a look at the IProgress(T) interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T) interface.

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

Float sum with javascript

Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed() function:

var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?

Import Excel to Datagridview

try this following snippet, its working fine.

private void button1_Click(object sender, EventArgs e)
{
     try
     {
             OpenFileDialog openfile1 = new OpenFileDialog();
             if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             {
                   this.textBox1.Text = openfile1.FileName;
             }
             {
                   string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                   OleDbConnection conn = new OleDbConnection(pathconn);
                   OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                   DataTable dt = new DataTable();
                   MyDataAdapter.Fill(dt);
                   dataGridView1.DataSource = dt;
             }
      }
      catch { }
}

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Checking that a List is not empty in Hamcrest

Create your own custom IsEmpty TypeSafeMatcher:

Even if the generics problems are fixed in 1.3 the great thing about this method is it works on any class that has an isEmpty() method! Not just Collections!

For example it will work on String as well!

/* Matches any class that has an <code>isEmpty()</code> method
 * that returns a <code>boolean</code> */ 
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
    @Factory
    public static <T> Matcher<T> empty()
    {
        return new IsEmpty<T>();
    }

    @Override
    protected boolean matchesSafely(@Nonnull final T item)
    {
        try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
        catch (final NoSuchMethodException e) { return false; }
        catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}

$(...).datepicker is not a function - JQuery - Bootstrap

Need to include jquery-ui too:

<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

EF LINQ include multiple and nested entities

this is from my project

 var saleHeadBranch = await _context.SaleHeadBranch
 .Include(d => d.SaleDetailBranch)
 .ThenInclude(d => d.Item)
 .Where(d => d.BranchId == loginTkn.branchId)
 .FirstOrDefaultAsync(d => d.Id == id);

What is the best place for storing uploaded images, SQL database or disk file system?

Definitely resize the image, and check it's format if you can. There have been cases of malicious files being uploaded and served by unwitting hosts- for instance, the GIFAR vulnerability allowed you to hide a malicious java applet in a GIF file, which would then be able to read cookies in the current context and send them to another site for a cross-site scripting attack. Resizing the images usually prevents this, as it munges the embedded code. While this attack has been fixed by JVM patches, naively serving up binary files without scrubbing them opens you up to a whole range of vulnerabilities.

Remember, most virus scanners can only run against the filesystem- if you store your binaries in the DB, you won't be able to run a scanner against them very easily.

String comparison using '==' vs. 'strcmp()'

Using == might be dangerous.

Note, that it would cast the variable to another data type if the two differs.

Examples:

  • echo (1 == '1') ? 'true' : 'false';
  • echo (1 == true) ? 'true' : 'false';

As you can see, these two are from different types, but the result is true, which might not be what your code will expect.

Using ===, however, is recommended as test shows that it's a bit faster than strcmp() and its case-insensitive alternative strcasecmp().

Quick googling yells this speed comparison: http://snipplr.com/view/758/

Concat all strings inside a List<string> using LINQ

You can use Aggregate, to concatenate the strings into a single, character separated string but will throw an Invalid Operation Exception if the collection is empty.

You can use Aggregate function with a seed string.

var seed = string.Empty;
var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carAggregate = cars.Aggregate(seed,
                (partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');

you can use string.Join doesn’t care if you pass it an empty collection.

var seperator = ",";

var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};

var carJoin = string.Join(seperator, cars);

Spring Boot Java Config Set Session Timeout

server.session.timeout in the application.properties file is now deprecated. The correct setting is:

server.servlet.session.timeout=60s

Also note that Tomcat will not allow you to set the timeout any less than 60 seconds. For details about that minimum setting see https://github.com/spring-projects/spring-boot/issues/7383.

Length of string in bash

Using your example provided

#KISS (Keep it simple stupid)
size=${#myvar}
echo $size

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Format telephone and credit card numbers in AngularJS

Here is the way I created ssn directive which checks for the the pattern and I have used RobinHerbots jquery.inputmask

angular.module('SocialSecurityNumberDirective', [])
       .directive('socialSecurityNumber', socialSecurityNumber);

function socialSecurityNumber() {
    var jquery = require('jquery');
    var inputmask = require("jquery.inputmask");
    return {
        require: 'ngModel',
        restrict: 'A',
        priority: 1000,
        link: function(scope,element, attr, ctrl) {

            var jquery_element = jquery(element);
            jquery_element.inputmask({mask:"***-**-****",autoUnmask:true});
            jquery_element.on('keyup paste focus blur', function() {
                var val = element.val();    
                ctrl.$setViewValue(val);
                ctrl.$render();

             });

            var pattern = /^\d{9}$/;

            var newValue = null;

            ctrl.$validators.ssnDigits = function(value) {
                 newValue = element.val();
                return newValue === '' ? true : pattern.test(newValue);    
            };
        }
    };
}

How to decorate a class?

I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)

What you're thinking of is a metaclass. The __new__ function in a metaclass is passed the full proposed definition of the class, which it can then rewrite before the class is created. You can, at that time, sub out the constructor for a new one.

Example:

def substitute_init(self, id, *args, **kwargs):
    pass

class FooMeta(type):

    def __new__(cls, name, bases, attrs):
        attrs['__init__'] = substitute_init
        return super(FooMeta, cls).__new__(cls, name, bases, attrs)

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):
        pass

Replacing the constructor is perhaps a bit dramatic, but the language does provide support for this kind of deep introspection and dynamic modification.

Oracle JDBC ojdbc6 Jar as a Maven Dependency

For anyone reading this post in the future, you don't need to cd to the directory where the jar is present. Here is what you need to do -

Go to your project folder from where you can run maven commands (When you do an ls -ltr in this folder, you should see pom.xml)

Do this -

mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=<Path where the jar is, example downloads>/ojdbc6.jar -DgeneratePom=true

Once this is done, you can add the dependency in your pom.xml, something like this -

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.3</version>
    </dependency>

Replace words in the body text

I am new to Javascript and just started learning these skills. Please check if the below method is useful to replace the text.

<script>

    var txt=document.getElementById("demo").innerHTML;
    var pos = txt.replace(/Hello/g, "hi")
    document.getElementById("demo").innerHTML = pos;

</script>

Getting current unixtimestamp using Moment.js

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

Using setattr() in python

Suppose you want to give attributes to an instance which was previously not written in code. The setattr() does just that. It takes the instance of the class self and key and value to set.

class Example:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

Creating custom function in React component

Another way:

export default class Archive extends React.Component { 

  saySomething = (something) => {
    console.log(something);
  }

  handleClick = (e) => {
    this.saySomething("element clicked");
  }

  componentDidMount() {
    this.saySomething("component did mount");
  }

  render() {
    return <button onClick={this.handleClick} value="Click me" />;
  }
}

In this format you don't need to use bind

Group by with multiple columns using lambda

if your table is like this

rowId     col1    col2    col3    col4
 1          a       e       12       2
 2          b       f       42       5
 3          a       e       32       2
 4          b       f       44       5


var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 =  r.Field<int>("col1"), pp2 = r.Field<int>("col2")});

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Another bit of "wisdom". I have a database facing both, the internet and an internal app. I have a context for each face. That helps me to keep a disciplined, secured segregation.

View a file in a different Git branch without changing branches

This should work:

git show branch:file

Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use

git show branch:file > exported_file

You should also look at VonC's answers to some related questions:

UPDATE 2015-01-19:

Nowadays you can use relative paths with git show a1b35:./file.txt.

Javascript - User input through HTML input tag to set a Javascript variable?

When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:

  • Use var foo = prompt("Give me input");, which will give you the string that the user enters into a popup box (or null if they cancel it)
  • Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.

How to increase the max connections in postgres?

change max_connections variable in postgresql.conf file located in /var/lib/pgsql/data or /usr/local/pgsql/data/

CSS Cell Margin

Try padding-right. You're not allowed to put margin's between cells.

<table>
   <tr>
      <td style="padding-right: 10px;">one</td>
      <td>two</td>
   </tr>
</table>

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

use Values either while creating variable X or while encoding as mentioned above

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')

dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4].values
X=dataset.iloc[:, 0:4].values

How to view method information in Android Studio?

The easiest and the most straightforward way:

To activate: File > Settings > Editor > General

For Mac OS X, Android Studio > Preferences > Editor > General and check Show quick documentation on mouse move:

Settings dialog with checked option

Other ways:

  • You can go into your IntelliJ's bin folder and search for idea.properties. Add this line to the document:

    auto.show.quick.doc=true

    Now you'll have the same floating docs window like in Eclipse.

  • You have to press CTRL+Q to see the Javadoc.

    You can pin the window and make the documentation appear every time you select a method with your mouse though.

Android Studio 1.0: You have to hold CTRL if you want to get hold of documentation window for e.g. scrolling documentation otherwise as you move your mouse away from method documentation window will disappear.

Override element.style using CSS

Use JavaScript.

For example:

var elements = document.getElementById("demoFour").getElementsByTagName("li");
for (var i = 0; i < elements.length; i++) {
    elements[i].style.display = "inline";
}

How do I capture SIGINT in Python?

Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.

Setting a signal handler behaves the same.

On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.

Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

LIMIT 10..20 in SQL Server

as you found, this is the preferred sql server method:

SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases 
 ) a WHERE a.row > 5 and a.row <= 10

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Have you tried using the stream_context_set_option() method ?

$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);

In addition, try file_get_contents() for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had same issue and I solved it by "pod setup" after installing cocoapods.

Make a VStack fill the width of the screen in SwiftUI

One more alternative is to place one of the subviews inside of an HStack and place a Spacer() after it:

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {

            HStack {
                Text("Title")
                    .font(.title)
                    .background(Color.yellow)
                Spacer()
            }

            Text("Content")
                .lineLimit(nil)
                .font(.body)
                .background(Color.blue)

            Spacer()
            }

            .background(Color.red)
    }
}

resulting in :

HStack inside a VStack

PDO Prepared Inserts multiple rows in single query

I had the same problem and this is how i accomplish for myself, and i made a function for myself for it ( and you can use it if that helps you).

Example:

INSERT INTO countries (country, city) VALUES (Germany, Berlin), (France, Paris);

$arr1 = Array("Germany", "Berlin");
$arr2 = Array("France", "France");

insertMultipleData("countries", Array($arr1, $arr2));


// Inserting multiple data to the Database.
public function insertMultipleData($table, $multi_params){
    try{
        $db = $this->connect();

        $beforeParams = "";
        $paramsStr = "";
        $valuesStr = "";

        for ($i=0; $i < count($multi_params); $i++) { 

            foreach ($multi_params[$i] as $j => $value) {                   

                if ($i == 0) {
                    $beforeParams .=  " " . $j . ",";
                }

                $paramsStr .= " :"  . $j . "_" . $i .",";                                       
            }

            $paramsStr = substr_replace($paramsStr, "", -1);
            $valuesStr .=  "(" . $paramsStr . "),"; 
            $paramsStr = "";
        }


        $beforeParams = substr_replace($beforeParams, "", -1);
        $valuesStr = substr_replace($valuesStr, "", -1);


        $sql = "INSERT INTO " . $table . " (" . $beforeParams . ") VALUES " . $valuesStr . ";";

        $stmt = $db->prepare($sql);


        for ($i=0; $i < count($multi_params); $i++) { 
            foreach ($multi_params[$i] as $j => &$value) {
                $stmt->bindParam(":" . $j . "_" . $i, $value);                                      
            }
        }

        $this->close($db);
        $stmt->execute();                       

        return true;

    }catch(PDOException $e){            
        return false;
    }

    return false;
}

// Making connection to the Database 
    public function connect(){
        $host = Constants::DB_HOST;
        $dbname = Constants::DB_NAME;
        $user = Constants::DB_USER;
        $pass = Constants::DB_PASS;

        $mysql_connect_str = 'mysql:host='. $host . ';dbname=' .$dbname;

        $dbConnection = new PDO($mysql_connect_str, $user, $pass);
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return $dbConnection;
    }

    // Closing the connection
    public function close($db){
        $db = null;
    }

If insertMultipleData($table, $multi_params) returns TRUE, your data has been inserted to your database.

How to stop INFO messages displaying on spark console?

In Python/Spark we can do:

def quiet_logs( sc ):
  logger = sc._jvm.org.apache.log4j
  logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
  logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )

The after defining Sparkcontaxt 'sc' call this function by : quiet_logs( sc )

How to get the number of columns in a matrix?

Use the size() function.

>> size(A,2)

Ans =

   3

The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.

Official documentation.

Web colors in an Android color xml resource file

You have surely made your own by now, but for the benefit of others, please find w3c and x11 below.

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="white">#FFFFFF</color>
 <color name="yellow">#FFFF00</color>
 <color name="fuchsia">#FF00FF</color>
 <color name="red">#FF0000</color>
 <color name="silver">#C0C0C0</color>
 <color name="gray">#808080</color>
 <color name="olive">#808000</color>
 <color name="purple">#800080</color>
 <color name="maroon">#800000</color>
 <color name="aqua">#00FFFF</color>
 <color name="lime">#00FF00</color>
 <color name="teal">#008080</color>
 <color name="green">#008000</color>
 <color name="blue">#0000FF</color>
 <color name="navy">#000080</color>
 <color name="black">#000000</color>
</resources>

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="White">#FFFFFF</color>
 <color name="Ivory">#FFFFF0</color>
 <color name="LightYellow">#FFFFE0</color>
 <color name="Yellow">#FFFF00</color>
 <color name="Snow">#FFFAFA</color>
 <color name="FloralWhite">#FFFAF0</color>
 <color name="LemonChiffon">#FFFACD</color>
 <color name="Cornsilk">#FFF8DC</color>
 <color name="Seashell">#FFF5EE</color>
 <color name="LavenderBlush">#FFF0F5</color>
 <color name="PapayaWhip">#FFEFD5</color>
 <color name="BlanchedAlmond">#FFEBCD</color>
 <color name="MistyRose">#FFE4E1</color>
 <color name="Bisque">#FFE4C4</color>
 <color name="Moccasin">#FFE4B5</color>
 <color name="NavajoWhite">#FFDEAD</color>
 <color name="PeachPuff">#FFDAB9</color>
 <color name="Gold">#FFD700</color>
 <color name="Pink">#FFC0CB</color>
 <color name="LightPink">#FFB6C1</color>
 <color name="Orange">#FFA500</color>
 <color name="LightSalmon">#FFA07A</color>
 <color name="DarkOrange">#FF8C00</color>
 <color name="Coral">#FF7F50</color>
 <color name="HotPink">#FF69B4</color>
 <color name="Tomato">#FF6347</color>
 <color name="OrangeRed">#FF4500</color>
 <color name="DeepPink">#FF1493</color>
 <color name="Fuchsia">#FF00FF</color>
 <color name="Magenta">#FF00FF</color>
 <color name="Red">#FF0000</color>
 <color name="OldLace">#FDF5E6</color>
 <color name="LightGoldenrodYellow">#FAFAD2</color>
 <color name="Linen">#FAF0E6</color>
 <color name="AntiqueWhite">#FAEBD7</color>
 <color name="Salmon">#FA8072</color>
 <color name="GhostWhite">#F8F8FF</color>
 <color name="MintCream">#F5FFFA</color>
 <color name="WhiteSmoke">#F5F5F5</color>
 <color name="Beige">#F5F5DC</color>
 <color name="Wheat">#F5DEB3</color>
 <color name="SandyBrown">#F4A460</color>
 <color name="Azure">#F0FFFF</color>
 <color name="Honeydew">#F0FFF0</color>
 <color name="AliceBlue">#F0F8FF</color>
 <color name="Khaki">#F0E68C</color>
 <color name="LightCoral">#F08080</color>
 <color name="PaleGoldenrod">#EEE8AA</color>
 <color name="Violet">#EE82EE</color>
 <color name="DarkSalmon">#E9967A</color>
 <color name="Lavender">#E6E6FA</color>
 <color name="LightCyan">#E0FFFF</color>
 <color name="BurlyWood">#DEB887</color>
 <color name="Plum">#DDA0DD</color>
 <color name="Gainsboro">#DCDCDC</color>
 <color name="Crimson">#DC143C</color>
 <color name="PaleVioletRed">#DB7093</color>
 <color name="Goldenrod">#DAA520</color>
 <color name="Orchid">#DA70D6</color>
 <color name="Thistle">#D8BFD8</color>
 <color name="LightGrey">#D3D3D3</color>
 <color name="Tan">#D2B48C</color>
 <color name="Chocolate">#D2691E</color>
 <color name="Peru">#CD853F</color>
 <color name="IndianRed">#CD5C5C</color>
 <color name="MediumVioletRed">#C71585</color>
 <color name="Silver">#C0C0C0</color>
 <color name="DarkKhaki">#BDB76B</color>
 <color name="RosyBrown">#BC8F8F</color>
 <color name="MediumOrchid">#BA55D3</color>
 <color name="DarkGoldenrod">#B8860B</color>
 <color name="FireBrick">#B22222</color>
 <color name="PowderBlue">#B0E0E6</color>
 <color name="LightSteelBlue">#B0C4DE</color>
 <color name="PaleTurquoise">#AFEEEE</color>
 <color name="GreenYellow">#ADFF2F</color>
 <color name="LightBlue">#ADD8E6</color>
 <color name="DarkGray">#A9A9A9</color>
 <color name="Brown">#A52A2A</color>
 <color name="Sienna">#A0522D</color>
 <color name="YellowGreen">#9ACD32</color>
 <color name="DarkOrchid">#9932CC</color>
 <color name="PaleGreen">#98FB98</color>
 <color name="DarkViolet">#9400D3</color>
 <color name="MediumPurple">#9370DB</color>
 <color name="LightGreen">#90EE90</color>
 <color name="DarkSeaGreen">#8FBC8F</color>
 <color name="SaddleBrown">#8B4513</color>
 <color name="DarkMagenta">#8B008B</color>
 <color name="DarkRed">#8B0000</color>
 <color name="BlueViolet">#8A2BE2</color>
 <color name="LightSkyBlue">#87CEFA</color>
 <color name="SkyBlue">#87CEEB</color>
 <color name="Gray">#808080</color>
 <color name="Olive">#808000</color>
 <color name="Purple">#800080</color>
 <color name="Maroon">#800000</color>
 <color name="Aquamarine">#7FFFD4</color>
 <color name="Chartreuse">#7FFF00</color>
 <color name="LawnGreen">#7CFC00</color>
 <color name="MediumSlateBlue">#7B68EE</color>
 <color name="LightSlateGray">#778899</color>
 <color name="SlateGray">#708090</color>
 <color name="OliveDrab">#6B8E23</color>
 <color name="SlateBlue">#6A5ACD</color>
 <color name="DimGray">#696969</color>
 <color name="MediumAquamarine">#66CDAA</color>
 <color name="CornflowerBlue">#6495ED</color>
 <color name="CadetBlue">#5F9EA0</color>
 <color name="DarkOliveGreen">#556B2F</color>
 <color name="Indigo">#4B0082</color>
 <color name="MediumTurquoise">#48D1CC</color>
 <color name="DarkSlateBlue">#483D8B</color>
 <color name="SteelBlue">#4682B4</color>
 <color name="RoyalBlue">#4169E1</color>
 <color name="Turquoise">#40E0D0</color>
 <color name="MediumSeaGreen">#3CB371</color>
 <color name="LimeGreen">#32CD32</color>
 <color name="DarkSlateGray">#2F4F4F</color>
 <color name="SeaGreen">#2E8B57</color>
 <color name="ForestGreen">#228B22</color>
 <color name="LightSeaGreen">#20B2AA</color>
 <color name="DodgerBlue">#1E90FF</color>
 <color name="MidnightBlue">#191970</color>
 <color name="Aqua">#00FFFF</color>
 <color name="Cyan">#00FFFF</color>
 <color name="SpringGreen">#00FF7F</color>
 <color name="Lime">#00FF00</color>
 <color name="MediumSpringGreen">#00FA9A</color>
 <color name="DarkTurquoise">#00CED1</color>
 <color name="DeepSkyBlue">#00BFFF</color>
 <color name="DarkCyan">#008B8B</color>
 <color name="Teal">#008080</color>
 <color name="Green">#008000</color>
 <color name="DarkGreen">#006400</color>
 <color name="Blue">#0000FF</color>
 <color name="MediumBlue">#0000CD</color>
 <color name="DarkBlue">#00008B</color>
 <color name="Navy">#000080</color>
 <color name="Black">#000000</color>
</resources>

How to click a href link using Selenium

 webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

The above line works fine. Please remove the space after href.

Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.

What HTTP status response code should I use if the request is missing a required parameter?

For those interested, Spring MVC (3.x at least) returns a 400 in this case, which seems wrong to me.

I tested several Google URLs (accounts.google.com) and removed required parameters, and they generally return a 404 in this case.

I would copy Google.

How to filter object array based on attributes?

var filterHome = homes.filter(home =>
  return (home.price <= 999 &&
         home.num_of_baths >= 2.5 &&
         home.num_of_beds >=2 &&
         home.sqft >= 998));
console.log(filterHome);

You can use this lambda function. More detail can be found here since we are filtering the data based on you have condition which return true or false and it will collect the data in different array so your actual array will be not modified.

@JGreig Please look into it.

How to connect to Mysql Server inside VirtualBox Vagrant?

Log in to your box with ssh [email protected] -p 2222 (password vagrant)

Then: sudo nano /etc/mysql/my.cnf and comment out the following lines with #

#skip-external-locking 
#bind-address

save it & exit

then: sudo service mysql restart

Then you can connect through SSH to your MySQL server.

How do I setup a SSL certificate for an express.js server?

See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(port);

Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

Android: how to get the current day of the week (Monday, etc...) in the user's language?

I know already answered but who looking for 'Fri' like this

for Fri -

SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);

and who wants full date string they can use 4E for Friday

For Friday-

SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);

Enjoy...

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

Is it possible to change the location of packages for NuGet?

None of this answers was working for me (Nuget 2.8.6) because of missing some tips, will try to add them here as it might be useful for others.

After reading the following sources:
https://docs.nuget.org/consume/NuGet-Config-Settings
https://github.com/NuGet/Home/issues/1346
It appears that

  1. To make working Install-Package properly with different repositoryPath you need to use forward slashes, it's because they are using Uri object to parse location.
  2. Without $ on the begining it was still ignoring my settings.
  3. NuGet caches config file, so after modifications you need to reload solution/VS.
  4. I had also strange issue while using command of NuGet.exe to set this option, as it modified my global NuGet.exe under AppData\Roaming\NuGet and started to restore packages there (Since that file has higher priority, just guessing).

E.g.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <solution>
    <add key="disableSourceControlIntegration" value="true" />
  </solution>
  <config>
    <add key="repositorypath" value="$/../../../Common/packages" />
  </config>
</configuration>

You can also use NuGet command to ensure that syntax will be correct like this:

NuGet.exe config -Set repositoryPath=$/../../../Common/packages -ConfigFile NuGet.Config

Use curly braces to initialize a Set in Python

From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

How to find the maximum value in an array?

Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.

int max = array.get(0);

for (int i = 1; i < array.length; i++) {
    if (array.get(i) > max) {
      max = array.get(i);
    }
}

Is this how you define a function in jQuery?

You can extend jQuery prototype and use your function as a jQuery method.

(function($)
{
    $.fn.MyBlah = function(blah)
    {
        $(this).addClass(blah);
        console.log('blah class added');
    };
})(jQuery);

jQuery(document).ready(function($)
{
    $('#blahElementId').MyBlah('newClass');
});

More info on extending jQuery prototype here: http://api.jquery.com/jquery.fn.extend/

How to place object files in separate subdirectory

For anyone that is working with a directory style like this:

project
    > src
        > pkgA     
        > pkgB
        ...
    > bin
        > pkgA
        > pkgB
        ...

The following worked very well for me. I made this myself, using the GNU make manual as my main reference; this, in particular, was extremely helpful for my last rule, which ended up being the most important one for me.

My Makefile:

PROG := sim
CC := g++
ODIR := bin
SDIR := src
MAIN_OBJ := main.o
MAIN := main.cpp
PKG_DIRS := $(shell ls $(SDIR))
CXXFLAGS = -std=c++11 -Wall $(addprefix -I$(SDIR)/,$(PKG_DIRS)) -I$(BOOST_ROOT)
FIND_SRC_FILES = $(wildcard $(SDIR)/$(pkg)/*.cpp) 
SRC_FILES = $(foreach pkg,$(PKG_DIRS),$(FIND_SRC_FILES)) 
OBJ_FILES = $(patsubst $(SDIR)/%,$(ODIR)/%,\
$(patsubst %.cpp,%.o,$(filter-out $(SDIR)/main/$(MAIN),$(SRC_FILES))))

vpath %.h $(addprefix $(SDIR)/,$(PKG_DIRS))
vpath %.cpp $(addprefix $(SDIR)/,$(PKG_DIRS)) 
vpath $(MAIN) $(addprefix $(SDIR)/,main)

# main target
#$(PROG) : all
$(PROG) : $(MAIN) $(OBJ_FILES) 
    $(CC) $(CXXFLAGS) -o $(PROG) $(SDIR)/main/$(MAIN) 

# debugging
all : ; $(info $$PKG_DIRS is [${PKG_DIRS}])@echo Hello world

%.o : %.cpp
    $(CC) $(CXXFLAGS) -c $< -o $@

# This one right here, folks. This is the one.
$(OBJ_FILES) : $(ODIR)/%.o : $(SDIR)/%.h
    $(CC) $(CXXFLAGS) -c $< -o $@

# for whatever reason, clean is not being called...
# any ideas why???
.PHONY: clean

clean :
    @echo Build done! Cleaning object files...
    @rm -r $(ODIR)/*/*.o

By using $(SDIR)/%.h as a prerequisite for $(ODIR)/%.o, this forced make to look in source-package directories for source code instead of looking in the same folder as the object file.

I hope this helps some people. Let me know if you see anything wrong with what I've provided.

BTW: As you may see from my last comment, clean is not being called and I am not sure why. Any ideas?

How do you uninstall all dependencies listed in package.json (NPM)?

I recently found a node command that allows uninstalling all the development dependencies as follows:

npm prune --production

As I mentioned, this command only uninstalls the development dependency packages. At least it helped me not to have to do it manually.

Java System.out.print formatting

Since you're using formatters for the rest of it, just use DecimalFormat:

import java.text.DecimalFormat;

DecimalFormat xFormat = new DecimalFormat("000")
System.out.print(xFormat.format(x + 1) + " ");

Alternative you could do whole job in whole line using printf:

System.out.printf("%03d %s  %s    %s    \n",  x + 1, // the payment number
formatter.format(monthlyInterest),  // round our interest rate
formatter.format(principleAmt),
formatter.format(remainderAmt));

set date in input type date

Your code would have worked if it had been in this format: YYYY-MM-DD, this is the computer standard for date formats http://en.wikipedia.org/wiki/ISO_8601

How to code a BAT file to always run as admin mode?

Use the complete physical drive\path to your Target batch file in the shortcut Properties.

This does not work in Windows 10 if you use subst drives like I tried to do at first...

True and False for && logic and || Logic table

I`d like to add to the already good answers:

The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".

Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!

int main ()
{
  std::cout <<  "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
  std::cout <<  "true - false = " << true - false << std::endl;
  std::cout <<  "false - true = " << false - true << std::endl;
  std::cout <<  "false - false = " << false - false << std::endl << std::endl;

  std::cout <<  "true + true = " << true + true << std::endl;
  std::cout <<  "true + false = " << true + false << std::endl;
  std::cout <<  "false + true = " << false + true << std::endl;
  std::cout <<  "false + false = " << false + false << std::endl << std::endl;

  std::cout <<  "true * true = " << true * true << std::endl;
  std::cout <<  "true * false = " << true * false << std::endl;
  std::cout <<  "false * true = " << false * true << std::endl;
  std::cout <<  "false * false = " << false * false << std::endl << std::endl;

  std::cout <<  "true / true = " << true / true << std::endl;
  //  std::cout <<  true / false << std::endl; ///-Wdiv-by-zero
  std::cout <<  "false / true = " << false / true << std::endl << std::endl;
  //  std::cout <<  false / false << std::endl << std::endl; ///-Wdiv-by-zero

  std::cout <<  "(true || true) = " << (true || true) << std::endl;
  std::cout <<  "(true || false) = " << (true || false) << std::endl;
  std::cout <<  "(false || true) = " << (false || true) << std::endl;
  std::cout <<  "(false || false) = " << (false || false) << std::endl << std::endl;

  std::cout <<  "(true && true) = " << (true && true) << std::endl;
  std::cout <<  "(true && false) = " << (true && false) << std::endl;
  std::cout <<  "(false && true) = " << (false && true) << std::endl;
  std::cout <<  "(false && false) = " << (false && false) << std::endl << std::endl;

}

yields :

true - true = 0
true - false = 1
false - true = -1
false - false = 0

true + true = 2
true + false = 1
false + true = 1
false + false = 0

true * true = 1
true * false = 0
false * true = 0
false * false = 0

true / true = 1
false / true = 0

(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0

(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Check to see if the Remote Procedure Call (RPC) service is running. If it is, then it's a firewall issue between your workstation and the server. You can test it by temporary disabling the firewall and retrying the command.

Edit after comment:

Ok, it's a firewall issue. You'll have to either limit the ports WMI/RPC work on, or open a lot of ports in the McAfee firewall.

Here are a few sites that explain this:

  1. Microsoft KB for limiting ports
  2. McAfee site talking about the same thing

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

Enumerations on PHP

Finally, A PHP 7.1+ answer with constants that cannot be overridden.

/**
 * An interface that groups HTTP Accept: header Media Types in one place.
 */
interface MediaTypes
{
    /**
    * Now, if you have to use these same constants with another class, you can
    * without creating funky inheritance / is-a relationships.
    * Also, this gets around the single inheritance limitation.
    */

    public const HTML = 'text/html';
    public const JSON = 'application/json';
    public const XML = 'application/xml';
    public const TEXT = 'text/plain';
}

/**
 * An generic request class.
 */
abstract class Request
{
    // Why not put the constants here?
    // 1) The logical reuse issue.
    // 2) Single Inheritance. 
    // 3) Overriding is possible.

    // Why put class constants here?
    // 1) The constant value will not be necessary in other class families.
}

/**
 * An incoming / server-side HTTP request class.
 */
class HttpRequest extends Request implements MediaTypes
{
    // This class can implement groups of constants as necessary.
}

If you are using namespaces, code completion should work.

However, in doing this, you loose the ability to hide the constants within the class family (protected) or class alone (private). By definition, everything in an Interface is public.

PHP Manual: Interfaces

How do you open an SDF file (SQL Server Compact Edition)?

You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to

  1. View ->
  2. Server Explorer ->
  3. Data Connections ->
  4. Add Connection...
  5. Change... (Data Source:)
  6. Microsoft SQL Server Compact 4.0
  7. Browse...

and following the instructions there.

If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.

(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

/* I have done it this way, and also tested it */

Step 1 = Register custom cell class (in case of prototype cell in table) or nib (in case of custom nib for custom cell) for table like this in viewDidLoad method:

[self.yourTableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];

OR

[self.yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];

Step 2 = Use UITableView's "dequeueReusableCellWithIdentifier: forIndexPath:" method like this (for this, you must register class or nib) :

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];

            cell.imageViewCustom.image = nil; // [UIImage imageNamed:@"default.png"];
            cell.textLabelCustom.text = @"Hello";

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                // retrive image on global queue
                UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:     [NSURL URLWithString:kImgLink]]];

                dispatch_async(dispatch_get_main_queue(), ^{

                    CustomTableViewCell * cell = (CustomTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
                  // assign cell image on main thread
                    cell.imageViewCustom.image = img;
                });
            });

            return cell;
        }

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;