Programs & Examples On #Mechanicalturk

Mechanical Turk is crowd sourcing web-service by Amazon. It provides a marketplace for tasks that can be performed by humans. Requesters publish HITs (Human Intelligence Tasks) that are performed by Workers. Amazon provides web based API to access and manage HITs.

What is the difference between a symbolic link and a hard link?

Hard links are very useful when doing incremental backups. See rsnapshot, for example. The idea is to do copy using hard links:

  • copy backup number n to n + 1
  • copy backup n - 1 to n
  • ...
  • copy backup 0 to backup 1
  • update backup 0 with any changed files.

The new backup will not take up any extra space apart from any changes you've made, since all the incremental backups will point to the same set of inodes for files which haven't changed.

Trusting all certificates with okHttp

I made an extension function for Kotlin. Paste it where ever you like and import it while creating OkHttpClient.

fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
    val naiveTrustManager = object : X509TrustManager {
        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
    }

    val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
        val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
        init(null, trustAllCerts, SecureRandom())
    }.socketFactory

    sslSocketFactory(insecureSocketFactory, naiveTrustManager)
    hostnameVerifier(HostnameVerifier { _, _ -> true })
    return this
}

use it like this:

val okHttpClient = OkHttpClient.Builder().apply {
    // ...
    if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
        ignoreAllSSLErrors()
    //...
}.build()

jQuery send string as POST parameters

Not a direct answer to your question.. But following is the only syntax that used to work for me -

data: '{"winNumber": "' + win + '"}',

And the parameter-name match with the argument of the server method

Get current time as formatted string in Go?

Find more info in this post: Get current date and time in various format in golang

This is a taste of the different formats that you'll find in the previous post:

enter image description here

Why is Java's SimpleDateFormat not thread-safe?

Here’s an example defines a SimpleDateFormat object as a static field. When two or more threads access “someMethod” concurrently with different dates, they can mess with each other’s results.

    public class SimpleDateFormatExample {
         private static final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

         public String someMethod(Date date) {
            return simpleFormat.format(date);
         }
    }

You can create a service like below and use jmeter to simulate concurrent users using the same SimpleDateFormat object formatting different dates and their results will be messed up.

public class FormattedTimeHandler extends AbstractHandler {

private static final String OUTPUT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
private static final String INPUT_TIME_FORMAT = "yyyy-MM-ddHH:mm:ss";
private static final SimpleDateFormat simpleFormat = new SimpleDateFormat(OUTPUT_TIME_FORMAT);
// apache commons lang3 FastDateFormat is threadsafe
private static final FastDateFormat fastFormat = FastDateFormat.getInstance(OUTPUT_TIME_FORMAT);

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);

    final String inputTime = request.getParameter("time");
    Date date = LocalDateTime.parse(inputTime, DateTimeFormat.forPattern(INPUT_TIME_FORMAT)).toDate();

    final String method = request.getParameter("method");
    if ("SimpleDateFormat".equalsIgnoreCase(method)) {
        // use SimpleDateFormat as a static constant field, not thread safe
        response.getWriter().println(simpleFormat.format(date));
    } else if ("FastDateFormat".equalsIgnoreCase(method)) {
        // use apache commons lang3 FastDateFormat, thread safe
        response.getWriter().println(fastFormat.format(date));
    } else {
        // create new SimpleDateFormat instance when formatting date, thread safe
        response.getWriter().println(new SimpleDateFormat(OUTPUT_TIME_FORMAT).format(date));
    }
}

public static void main(String[] args) throws Exception {
    // embedded jetty configuration, running on port 8090. change it as needed.
    Server server = new Server(8090);
    server.setHandler(new FormattedTimeHandler());

    server.start();
    server.join();
}

}

The code and jmeter script can be downloaded here .

JavaScript module pattern with example

In order to approach to Modular design pattern, you need to understand these concept first:

Immediately-Invoked Function Expression (IIFE):

(function() {
      // Your code goes here 
}());

There are two ways you can use the functions. 1. Function declaration 2. Function expression.

Here are using function expression.

What is namespace? Now if we add the namespace to the above piece of code then

var anoyn = (function() {
}());

What is closure in JS?

It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.

var scope = "I am global";
function whatismyscope() {
    var scope = "I am just a local";
    function func() {return scope;}
    return func;
}
whatismyscope()()

Now we will apply these three concepts I mentioned above to define our first modular design pattern:

var modularpattern = (function() {
    // your module code goes here
    var sum = 0 ;

    return {
        add:function() {
            sum = sum + 1;
            return sum;
        },
        reset:function() {
            return sum = 0;    
        }  
    }   
}());
alert(modularpattern.add());    // alerts: 1
alert(modularpattern.add());    // alerts: 2
alert(modularpattern.reset());  // alerts: 0

jsfiddle for the code above.

The objective is to hide the variable accessibility from the outside world.

Hope this helps. Good Luck.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

How to detect online/offline event cross-browser?

navigator.onLine is a mess

I face this when trying to make an ajax call to the server.

There are several possible situations when the client is offline:

  • the ajax call timouts and you receive error
  • the ajax call returns success, but the msg is null
  • the ajax call is not executed because browser decides so (may be this is when navigator.onLine becomes false after a while)

The solution I am using is to control the status myself with javascript. I set the condition of a successful call, in any other case I assume the client is offline. Something like this:

var offline;
pendingItems.push(item);//add another item for processing
updatePendingInterval = setInterval("tryUpdatePending()",30000);
tryUpdatePending();

    function tryUpdatePending() {

        offline = setTimeout("$('#offline').show()", 10000);
        $.ajax({ data: JSON.stringify({ items: pendingItems }), url: "WebMethods.aspx/UpdatePendingItems", type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
          success: function (msg) {
            if ((!msg) || msg.d != "ok")
              return;
            pending = new Array(); //empty the pending array
            $('#offline').hide();
            clearTimeout(offline);
            clearInterval(updatePendingInterval);
          }
        });
      }

jQuery dialog popup

You can check this link: http://jqueryui.com/dialog/

This code should work fine

$("#dialog").dialog();

How to abort makefile if variable not set?

You can use an IF to test:

check:
        @[ "${var}" ] || ( echo ">> var is not set"; exit 1 )

Result:

$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1

How can I remove an entry in global configuration with git config?

Try these commands to remove all users' usernames and emails.

git config --global --unset-all user.name
git config --global --unset-all user.email

Replacing from match to end-of-line

Use this, two<anything any number of times><end of line>

's/two.*$/BLAH/g'

How to acces external json file objects in vue.js app

If your file looks like this:

[
    {
        "firstname": "toto",
        "lastname": "titi"
    },
    {
        "firstname": "toto2",
        "lastname": "titi2"
    },
]

You can do:

import json from './json/data.json';
// ....
json.forEach(x => { console.log(x.firstname, x.lastname); });

Handling the window closing event with WPF / MVVM Light Toolkit

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        MessageBox.Show("closing");
    }

Creating a system overlay window (always on top)

WORKING ALWAYS ON TOP IMAGE BUTTON

first of all sorry for my english

i edit your codes and make working image button that listens his touch event do not give touch control to his background elements.

also it gives touch listeners to out of other elements

button alingments are bottom and left

you can chage alingments but you need to chages cordinats in touch event in the if element

import android.annotation.SuppressLint;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

public class HepUstte extends Service {
    HUDView mView;

    @Override
    public void onCreate() {
        super.onCreate();   

        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();

        final Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo_l);


        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                kangoo.getWidth(), 
                kangoo.getHeight(),
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                |WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                 PixelFormat.TRANSLUCENT);






        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);



        mView = new HUDView(this,kangoo);

        mView.setOnTouchListener(new OnTouchListener() {


            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                //Log.e("kordinatlar", arg1.getX()+":"+arg1.getY()+":"+display.getHeight()+":"+kangoo.getHeight());
                if(arg1.getX()<kangoo.getWidth() & arg1.getY()>0)
                {
                 Log.d("tiklandi", "touch me");
                }
                return false;
            }
             });


        wm.addView(mView, params);



        }



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

}



@SuppressLint("DrawAllocation")
class HUDView extends ViewGroup {


    Bitmap kangoo;

    public HUDView(Context context,Bitmap kangoo) {
        super(context);

        this.kangoo=kangoo;



    }


    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);


        // delete below line if you want transparent back color, but to understand the sizes use back color
        canvas.drawColor(Color.BLACK);

        canvas.drawBitmap(kangoo,0 , 0, null); 


        //canvas.drawText("Hello World", 5, 15, mLoadPaint);

    }


    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    }

    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
       // Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();

        return true;
    }
}

Oracle JDBC intermittent Connection Issue

The root cause of this problem has to do with user authentication versions. For each database user, multiple password verifiers are kept in the database. Typically when you upgrade your database, a new password verifier will be added to the list, a stronger one. The following query shows the password verifier versions that are available for each user. For example:

SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';

PASSWORD_VERSIONS
-----------------
11G 12C

When upgrading to a newer driver you can use a newer version of the verifier because the driver and server negotiate the strongest possible verifier to to be used. This newer version of the verifier will be more secure and will involve generating larger random numbers or using more complex hashing functions which can explain why you see issues while establishing JDBC connections. As mentioned by other responses using /dev/urandom normally resolves these issues. You can also decide to downgrade your password verifier and make the newer driver use the same older password verifier that your previous driver was using. For example if you want to use the 10G password verifier (for testing purposes only), first you need to make sure it's available for your user. Set SQLNET.ALLOWED_LOGON_VERSION_SERVER=8 in sqlnet.ora on the server. Then:

SQL> alter user scott identified by "tiger";

User altered.

SQL> SELECT PASSWORD_VERSIONS FROM DBA_USERS WHERE USERNAME='SCOTT';
PASSWORD_VERSIONS
-----------------
10G 11G 12C

Then you can force the JDBC thin driver to use the 10G verifier by setting this JDBC property oracle.jdbc.thinLogonCapability="o3". If you run into the error "ORA-28040: No matching authentication protocol" then that means your server is not allowing the 10G verifier to be used. If that's the case then you need to check your configuration again.

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

How can I view live MySQL queries?

Gibbs MySQL Spyglass

AgilData launched recently the Gibbs MySQL Scalability Advisor (a free self-service tool) which allows users to capture a live stream of queries to be uploaded to Gibbs. Spyglass (which is Open Source) will watch interactions between your MySQL Servers and client applications. No reconfiguration or restart of the MySQL database server is needed (either client or app).

GitHub: AgilData/gibbs-mysql-spyglass

Learn more: Packet Capturing MySQL with Rust

Install command:

curl -s https://raw.githubusercontent.com/AgilData/gibbs-mysql-spyglass/master/install.sh | bash

fopen deprecated warning

I'am using VisualStdio 2008. In this case I often set Preprocessor Definitions

Menu \ Project \ [ProjectName] Properties... Alt+F7

If click this menu or press Alt + F7 in project window, you can see "Property Pages" window.

Then see menu on left of window.

Configuration Properties \ C/C++ \ Preprocessor

Then add _CRT_SECURE_NO_WARNINGS to \ Preprocessor Definitions.

Change MySQL default character set to UTF-8 in my.cnf?

NijaCat was close, but specified overkill:

To set the default to UTF-8, you want to add the following to my.cnf

[client]
default-character-set=utf8

[mysqld]
default-character-set = utf8

Then, to verify:

mysql> show variables like "%character%";show variables like "%collation%";

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database   | utf8_general_ci |
| collation_server     | utf8_general_ci |
+----------------------+-----------------+
3 rows in set (0.00 sec)

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

How do I install Python packages on Windows?

pip is the package installer for python, update it first, then download what you need

python -m pip install --upgrade pip

Then:

python -m pip install <package_name>

Change value of input placeholder via model?

As Wagner Francisco said, (in JADE)

input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`

And in your controller :

$scope.someScopeVariable = 'somevalue'

Is there a method for String conversion to Title Case?

The simplest way of converting any string into a title case, is to use googles package org.apache.commons.lang.WordUtils

System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));

Will result this

This Will Be My Example

I'm not sure why its named "capitalizeFully", where in fact the function is not doing a full capital result, but anyways, thats the tool that we need.

How do I resolve a TesseractNotFoundError?

One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

Convert Json string to Json object in Swift 4

The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries. In raw json strings, arrays begin with [ and dictionaries begin with {.


I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
    {
       print(jsonArray) // use the json here     
    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

How to connect with Java into Active Directory

Here is a simple code that authenticate and make an LDAP search usin JNDI on a W2K3 :

class TestAD
{
  static DirContext ldapContext;
  public static void main (String[] args) throws NamingException
  {
    try
    {
      System.out.println("Début du test Active Directory");

      Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
      ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      //ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389");
      ldapEnv.put(Context.PROVIDER_URL,  "ldap://dom.fr:389");
      ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
      //ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
      ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=jean paul blanc,ou=MonOu,dc=dom,dc=fr");
      ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
      //ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
      ldapContext = new InitialDirContext(ldapEnv);

      // Create the search controls         
      SearchControls searchCtls = new SearchControls();

      //Specify the attributes to return
      String returnedAtts[]={"sn","givenName", "samAccountName"};
      searchCtls.setReturningAttributes(returnedAtts);

      //Specify the search scope
      searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      //specify the LDAP search filter
      String searchFilter = "(&(objectClass=user))";

      //Specify the Base for the search
      String searchBase = "dc=dom,dc=fr";
      //initialize counter to total the results
      int totalResults = 0;

      // Search for objects using the filter
      NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);

      //Loop through the search results
      while (answer.hasMoreElements())
      {
        SearchResult sr = (SearchResult)answer.next();

        totalResults++;

        System.out.println(">>>" + sr.getName());
        Attributes attrs = sr.getAttributes();
        System.out.println(">>>>>>" + attrs.get("samAccountName"));
      }

      System.out.println("Total results: " + totalResults);
      ldapContext.close();
    }
    catch (Exception e)
    {
      System.out.println(" Search error: " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }
}

JSON to string variable dump

You can use console.log() in Firebug or Chrome to get a good object view here, like this:

$.getJSON('my.json', function(data) {
  console.log(data);
});

If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).

If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/

XML serialization in Java?

XMLBeans works great if you have a schema for your XML. It creates Java objects for the schema and creates easy to use parse methods.

How to fix the session_register() deprecated issue?

I wrote myself a little wrapper, so I don't have to rewrite all of my code from the past decades, which emulates register_globals and the missing session functions.

I've picked up some ideas from different sources and put some own stuff to get a replacement for missing register_globals and missing session functions, so I don't have to rewrite all of my code from the past decades. The code also works with multidimensional arrays and builds globals from a session.

To get the code to work use auto_prepend_file on php.ini to specify the file containing the code below. E.g.: auto_prepend_file = /srv/www/php/.auto_prepend.php.inc

You should have runkit extension from PECL installed and the following entries on your php.ini:

extension_dir = <your extension dir>
extension = runkit.so
runkit.internal_override = On

.auto_prepend.php.inc:

<?php
//Fix for removed session functions
if (!function_exists('session_register'))
{
    function session_register()
    {
        $register_vars = func_get_args();
        foreach ($register_vars as $var_name)
        {
            $_SESSION[$var_name] = $GLOBALS[$var_name];
            if (!ini_get('register_globals'))
            {   $GLOBALS[$var_name] = &$_SESSION[$var_name]; }
        }
    }

    function session_is_registered($var_name)
    {   return isset($_SESSION[$var_name]); }

    function session_unregister($var_name)
    {   unset($_SESSION[$var_name]); }
}

//Fix for removed function register_globals
if (!isset($PXM_REG_GLOB))
{
    $PXM_REG_GLOB=1;
    if (!ini_get('register_globals'))
    {
        if (isset($_REQUEST))   { extract($_REQUEST); }
        if (isset($_SERVER))        { extract($_SERVER); }

        //$_SESSION globals must be registred with call of session_start()
        // Best option - Catch session_start call - Runkit extension from PECL must be present
        if (extension_loaded("runkit"))
        {
            if (!function_exists('session_start_default'))
            {   runkit_function_rename("session_start", "session_start_default"); }
            if (!function_exists('session_start'))
            {
                function session_start($options=null)
                {
                    $return=session_start_default($options);
                    if (isset($_SESSION))
                    {
                        $var_names=array_keys($_SESSION);
                        foreach($var_names as $var_name)
                        {   $GLOBALS[$var_name]=&$_SESSION[$var_name]; }
                    }
                    return $return;
                }
            }
        }
        // Second best option - Will always extract $_SESSION if session cookie is present.
        elseif ($_COOKIE["PHPSESSID"])
        {
            session_start();
            if (isset($_SESSION))
            {
                $var_names=array_keys($_SESSION);
                foreach($var_names as $var_name)
                {   $GLOBALS[$var_name]=&$_SESSION[$var_name]; }
            }
        }
    }
}
?>

how to change text in Android TextView

setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like

textview.append("Step Two: fry egg");

Why do I need to do `--set-upstream` all the time?

You can set up a really good alias that can handle this without the overly verbose syntax.

I have the following alias in ~/.gitconfig:

po = "!git push -u origin \"$(git rev-parse --abbrev-ref HEAD)\""

After making a commit on a new branch, you can push your new branch by simply typing the command:

git po

database attached is read only

You need to change permission for your database folder: properties -> security tab -> edit... -> add... -> username "NT Service\MSSQL$SQLEXPRESS" or "NT Service\MSSQLSERVER". Close the windows, open Advanced..., double click the user and set as follows: Type: Allow Applies to: This folder, subfolder and files Basic permissions: all Make sure the owner is set too.

jQuery post() with serialize and extra data

You can use serializeArray [docs] and add the additional data:

var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});

$.post("page.php", data);

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

I had the same trouble, this is what worked for me.

You can click at the wampserver icon, then at the PHP error log. Check if it says this: Unable to load dynamic library 'c:/wamp/bin/php/php5.5.12/ext/php_ldap.dll'

If yes, then you can reload your version of PHP, by clicking at the wampserver icon, then PHP, then version, and then you click at your version. Wait for everything to be online again, then try to access phpmyadmin.

How can I get the current screen orientation?

I just want to propose another alternative that will concern some of you :

android:configChanges="orientation|keyboardHidden" 

implies that we explicitly declare the layout to be injected.

In case we want to keep the automatic injection thanks to the layout-land and layout folders. All you have to do is add it to the onCreate:

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        getSupportActionBar().hide();

    } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        getSupportActionBar().show();
    }

Here, we display or not the actionbar depending on the orientation of the phone

copying all contents of folder to another folder using batch file?

On my PC, xcopy and robocopy need also the path to them, i.e. C:\Windows\System32\xcopy.exe

That's why I use simply "copy": copy /y ....\Folder1\File.txt ....\Folder2\

Install an apk file from command prompt?

The simple way to do that is by command

adb install example.apk

and if you want to target connect device you can add parameter " -d "

adb install -d example.apk

if you have more than one device/emulator connected you will get this error

adb: error: connect failed: more than one device/emulator - waiting for device - error: more than one device/emulator

to avoid that you can list all devices by below command

adb devices

you will get results like below

 C:\Windows\System32>adb devices 
 List of devices attached 
 a3b09hh3e    device 
 emulator-5334    device

chose one of these devices and add parameter to adb command as " -s a3b09hh3e " as below

adb -s a3b09a6e install  example.apk

also as a hint if the path of the apk long and have a spaces, just add it between double quotes like

adb -s a3b09a6e install  "c:\my apk location\here 123\example.apk"

How can I mock the JavaScript window object using Jest?

In your Jest configuration, add setupFilesAfterEnv: ["./setupTests.js"], create that file, and add the code you want to run before the tests:

// setupTests.js
window.crypto = {
   .....
};

Reference: setupFilesAfterEnv [array]

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Change Schema Name Of Table In SQL

Your Code is:

FROM
 dbo.Employees
TO
 exe.Employees

I tried with this query.

ALTER SCHEMA exe TRANSFER dbo.Employees

Just write create schema exe and execute it

How does true/false work in PHP?

Since I've visited this page several times, I've decided to post an example (loose) comparison test.

Results:

""        -> false
"0"       -> false
"1"       -> true
"01"      -> true
"abc"     -> true
"true"    -> true
"false"   -> true
0         -> false
0.1       -> true
1         -> true
1.1       -> true
-42       -> true
"NAN"     -> true
0         -> false
          -> true
null      -> false
true      -> true
false     -> false
[]        -> false
["a"]     -> true
{}        -> true
{}        -> true
{"s":"f"} -> true

Code:

class Vegetable {}

class Fruit {
    public $s = "f";
}

$cases = [
    "",
    "0",
    "1",
    "01",
    "abc",
    "true",
    "false",
    0,
    0.1,
    1,
    1.1,
    -42,
    "NAN",
    (float) "NAN",
    NAN,
    null,
    true,
    false,
    [],
    ["a"],
    new stdClass(),
    new Vegetable(),
    new Fruit(),
];

echo "<pre>" . PHP_EOL;

foreach ($cases as $case) {
    printf("%s -> %s" . PHP_EOL, str_pad(json_encode($case), 9, " ", STR_PAD_RIGHT), json_encode( $case == true ));
}

When a strict (===) comparison is done, everything except true returns false.

How can I change the text inside my <span> with jQuery?

Try this

$("#abc").html('<span class = "xyz"> SAMPLE TEXT</span>');

Handle all the css relevant to that span within xyz

How to convert a string or integer to binary in Ruby?

In ruby Integer class, to_s is defined to receive non required argument radix called base, pass 2 if you want to receive binary representation of a string.

Here is a link for an official documentation of String#to_s

  1.upto(10).each { |n|  puts n.to_s(2) }

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

From MSDN:

The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.

There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:

  1. Stop the WPF Font Cache 4.0 service.
  2. Delete all of the WPFFontCache_v0400* files. In Windows XP, you'll find them in your C:\Documents and Settings\LocalService\Local Settings\Application Data\ folder.
  3. Start the service again.

How to change border color of textarea on :focus

so simple :

 outline-color : blue !important;

the whole CSS for my react-boostrap button is:

.custom-btn {
    font-size:1.9em;
    background: #2f5bff;
    border: 2px solid #78e4ff;
    border-radius: 3px;
    padding: 50px 70px;
    outline-color : blue !important;
    text-transform: uppercase;
    user-select: auto;
    -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
    -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
}

How do I get the current absolute URL in Ruby on Rails?

For Rails 3.2 or Rails 4 Simply get in this way "request.original_url" Reference: Original URL Method

For Rails 3 As request.url is deprecated.We can get absolute path by concatenating

"#{request.protocol}#{request.host_with_port}#{request.fullpath}"

For Rails 2

request.url

How to overcome "'aclocal-1.15' is missing on your system" warning?

2017 - High Sierra

It is really hard to get autoconf 1.15 working on Mac. We hired an expert to get it working. Everything worked beautifully.

Later I happened to upgrade a Mac to High Sierra.

The Docker pipeline stopped working!

Even though autoconf 1.15 is working fine on the Mac.

How to fix,

Short answer, I simply trashed the local repo, and checked out the repo again.

This suggestion is noted in the mix on this QA page and elsewhere.

It then worked fine!

It likely has something to do with the aclocal.m4 and similar files. (But who knows really). I endlessly massaged those files ... but nothing.

For some unknown reason if you just scratch your repo and get the repo again: everything works!

I tried for hours every combo of touching/deleting etc etc the files in question, but no. Just check out the repo from scratch!

VB.NET Connection string (Web.Config, App.Config)

Public Function connectDB() As OleDbConnection

        Dim Con As New OleDbConnection
        'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & ""
        Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD"
        Try
            Con.Open()
        Catch ex As Exception
            showMessage(ex)
        End Try
        Return Con
    End Function

How to use a findBy method with comparative criteria

The Symfony documentation now explicitly shows how to do this:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT p
    FROM AppBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');    
$products = $query->getResult();

From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql

Why is there an unexplainable gap between these inline-block div elements?

In this instance, your div elements have been changed from block level elements to inline elements. A typical characteristic of inline elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)

There are a few solutions that can be used to solve this.

Method 1 - Remove the whitespace from the markup

Example 1 - Comment the whitespace out: (example)

<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>

Example 2 - Remove the line breaks: (example)

<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>

Example 3 - Close part of the tag on the next line (example)

<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>

Example 4 - Close the entire tag on the next line: (example)

<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>

Method 2 - Reset the font-size

Since the whitespace between the inline elements is determined by the font-size, you could simply reset the font-size to 0, and thus remove the space between the elements.

Just set font-size: 0 on the parent elements, and then declare a new font-size for the children elements. This works, as demonstrated here (example)

#parent {
    font-size: 0;
}

#child {
    font-size: 16px;
}

This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size is declared using em units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline elements.

Method 3 - Set the parent element to display: flex

In some cases, you can also set the display of the parent element to flex. (example)

This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.

.parent {
    display: flex;
}
.parent > div {
    display: inline-block;
    padding: 1em;
    border: 2px solid #f00;
}

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
    display: inline-block;_x000D_
    padding: 1em;_x000D_
    border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
    <div>text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Sides notes:

It is incredibly unreliable to use negative margins to remove the space between inline elements. Please don't use negative margins if there are other, more optimal, solutions.

What does "Error: object '<myvariable>' not found" mean?

The error means that R could not find the variable mentioned in the error message.

The easiest way to reproduce the error is to type the name of a variable that doesn't exist. (If you've defined x already, use a different variable name.)

x
## Error: object 'x' not found

The more complex version of the error has the same cause: calling a function when x does not exist.

mean(x)
## Error in mean(x) : 
##   error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found

Once the variable has been defined, the error will not occur.

x <- 1:5
x
## [1] 1 2 3 4 5     
mean(x)
## [1] 3

You can check to see if a variable exists using ls or exists.

ls()        # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.

Errors like this can occur when you are using non-standard evaluation. For example, when using subset, the error will occur if a column name is not present in the data frame to subset.

d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found

The error can also occur if you use custom evaluation.

get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found

In the second case, the var function cannot be found when R looks in the utils package's environment because utils is further down the search list than stats.


In more advanced use cases, you may wish to read:

python: how to send mail with TO, CC and BCC?

As of Python 3.2, released Nov 2011, the smtplib has a new function send_message instead of just sendmail, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they


# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Using the headers work fine, because send_message respects BCC as outlined in the documentation:

send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg


With sendmail it was common to add the CC headers to the message, doing something such as:

msg['Bcc'] = [email protected]

Or

msg = "From: [email protected]" +
      "To: [email protected]" +
      "BCC: [email protected]" +
      "Subject: You've got mail!" +
      "This is the message body"

The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail.

The caveat is that send_message requires a Message object, meaning you'll need to import a class from email.message instead of merely passing strings into sendmail.

How to Run Terminal as Administrator on Mac Pro

sudo dscl . -create /Users/joeadmin
sudo dscl . -create /Users/joeadmin UserShell /bin/bash
sudo dscl . -create /Users/joeadmin RealName "Joe Admin" 
sudo dscl . -create /Users/joeadmin UniqueID "510"
sudo dscl . -create /Users/joeadmin PrimaryGroupID 20
sudo dscl . -create /Users/joeadmin NFSHomeDirectory /Users/joeadmin
sudo dscl . -passwd /Users/joeadmin password 
sudo dscl . -append /Groups/admin GroupMembership joeadmin

press enter after every sentence

Then do a:

sudo reboot

Change joeadmin to whatever you want, but it has to be the same all the way through. You can also put a password of your choice after password.

How can I display the current branch and folder path in terminal?

From Mac OS Catalina .bash_profile is replaced with .zprofile

Step 1: Create a .zprofile

touch .zprofile

Step 2:

nano .zprofile

type below line in this

source ~/.bash_profile

and save(ctrl+o return ctrl+x)

Step 3: Restart your terminal

To Add Git Branch Name Now you can add below lines in .bash_profile

    parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

Restart your terminal this will work.

Note: Even you can rename .bash_profile to .zprofile that also works.

Cannot set content-type to 'application/json' in jQuery.ajax

Hi These two lines worked for me.

contentType:"application/json; charset=utf-8", dataType:"json"

 $.ajax({
            type: "POST",
            url: "/v1/candidates",
            data: obj,
            **contentType:"application/json; charset=utf-8",
            dataType:"json",**
            success: function (data) {
                table.row.add([
                    data.name, data.title
                ]).draw(false);
            }

Thanks, Prashant

What is the default Precision and Scale for a Number in Oracle?

Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

ToString() function in Go

Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

In my case, just using flex-shrink: 0 didn't work. But adding flex-grow: 1 to it worked.

.item {
    flex-shrink: 0;
    flex-grow: 1;
}

endsWith in JavaScript

if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)

String.prototype.endsWith = function(suffix) {
    if (this[this.length - 1] == suffix) return true;
    return false;
}

or as a standalone function

function strEndsWith(str,suffix) {
    if (str[str.length - 1] == suffix) return true;
    return false;
}

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

document.createElement("script") synchronously

Ironically, I have what you want, but want something closer to what you had.

I am loading things in dynamically and asynchronously, but with an load callback like so (using dojo and xmlhtpprequest)

  dojo.xhrGet({
    url: 'getCode.php',
    handleAs: "javascript",
    content : {
    module : 'my.js'
  },
  load: function() {
    myFunc1('blarg');
  },
  error: function(errorMessage) {
    console.error(errorMessage);
  }
});

For a more detailed explanation, see here

The problem is that somewhere along the line the code gets evaled, and if there's anything wrong with your code, the console.error(errorMessage); statement will indicate the line where eval() is, not the actual error. This is SUCH a big problem that I am actually trying to convert back to <script> statements (see here.

Disable vertical sync for glxgears

The vblank_mode environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others.

$>   vblank_mode=0 glxgears

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

How can I count the number of elements with same class?

You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size

_x000D_
_x000D_
var parent = document.getElementById("parentId");_x000D_
var nodesSameClass = parent.getElementsByClassName("test");_x000D_
console.log(nodesSameClass.length);
_x000D_
<div id="parentId">_x000D_
  <p class="prueba">hello word1</p>_x000D_
  <p class="test">hello word2</p>_x000D_
  <p class="test">hello word3</p>_x000D_
  <p class="test">hello word4</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between max-device-width and max-width for mobile web?

Don't use device-width/height anymore.

device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features

Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.

How I can check if an object is null in ruby on rails 2?

In your example, you can simply replace null with `nil and it will work fine.

require 'erb'

template = <<EOS
<% if (@objectname != nil) then %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

Contrary to what the other poster said, you can see above that then works fine in Ruby. It's not common, but it is fine.

#blank? and #present? have other implications. Specifically, if the object responds to #empty?, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.

Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be

require 'erb'

template = <<EOS
<% if @objectname %>
  @objectname is not nil
<% else %>
  @objectname is nil
<% end %>
EOS

@objectname = nil
ERB.new(template, nil, '>').result # => "  @objectname is nil\n"

@objectname = 'some name'
ERB.new(template, nil, '>').result # => "  @objectname is not nil\n"

If you explicitly need to check nil and not false, you can use the #nil? method, for which nil is the only object that will cause this to return true.

nil.nil?          # => true
false.nil?        # => false
Object.new.nil?   # => false

What does LINQ return when the results are empty

Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.

Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.

How would I get everything before a : in a string Python

partition() may be better then split() for this purpose as it has the better predicable results for situations you have no delimiter or more delimiters.

how to remove the dotted line around the clicked a element in html

In my case it was a button, and apparently, with buttons, this is only a problem in Firefox. Solution found here:

button::-moz-focus-inner {
  border: 0;
}

Make a DIV fill an entire table cell

The following should work. You have to set a height to the parent cell. https://jsfiddle.net/nrvd3vgd/

<table style="width:200px; border: 1px solid #000;">
    <tr>
        <td style="height:100px;"></td>
    </tr>
    <tr>
        <td style="height:200px;">
            <div style="height:100%; background: #f00;"></div>
        </td>
    </tr>
</table>

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

This is how I solved it:

Integer.toHexString(System.identityHashCode(object));

How to stretch a table over multiple pages

You should \usepackage{longtable}.

LEFT OUTER JOIN in LINQ

Using lambda expression

db.Categories    
  .GroupJoin(db.Products,
      Category => Category.CategoryId,
      Product => Product.CategoryId,
      (x, y) => new { Category = x, Products = y })
  .SelectMany(
      xy => xy.Products.DefaultIfEmpty(),
      (x, y) => new { Category = x.Category, Product = y })
  .Select(s => new
  {
      CategoryName = s.Category.Name,     
      ProductName = s.Product.Name   
  });

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):

C:\xampp\php\PEAR\initcontrols\header_myworks.php

providing the path you pasted in the subject is correct. Make sure your file is located there.

For more info you can get and set the include path programmatically.

How to get first character of string?

Looks like I am late to the party, but try the below solution which I personally found the best solution:

var x = "testing sub string"
alert(x[0]);
alert(x[1]);

Output should show alert with below values: "t" "e"

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

Change Primary Key

Sometimes when we do these steps:

 alter table my_table drop constraint my_pk; 
 alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

The last statement fails with

ORA-00955 "name is already used by an existing object"

Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.

You can combine the dropping of primary key constraint and unique index into a single sql statement:

alter table my_table drop constraint my_pk drop index; 

check this: ORA-00955 "name is already used by an existing object"

Find element in List<> that contains a value

Enumerable.First returns the element instead of an index. In both cases you will get an exception if no matching element appears in the list (your original code will throw an IndexOutOfBoundsException when you try to get the item at index -1, but First will throw an InvalidOperationException).

MyList.First(item => string.Equals("foo", item.name)).value

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

I came here looking for an answer to my distorted images. Not totally sure about what the op is looking for above, but I found that adding in align-items: center would solve it for me. Reading the docs, it makes sense to override this if you are flexing images directly, since align-items: stretch is the default. Another solution is to wrap your images with a div first.

.myFlexedImage {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
}

nodejs mongodb object id to string

try this: objectId.str;

see doc.

Can we open pdf file using UIWebView on iOS?

UIWebView *pdfWebView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

NSURL *targetURL = [NSURL URLWithString:@"http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf"];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [pdfWebView loadRequest:request];
    [self.view addSubview:pdfWebView];

Test if characters are in a string

You can use grep

grep("es", "Test")
[1] 1
grep("et", "Test")
integer(0)

Error in finding last used cell in Excel with VBA

Sub lastRow()

    Dim i As Long
        i = Cells(Rows.Count, 1).End(xlUp).Row
            MsgBox i

End Sub

sub LastRow()

'Paste & for better understanding of the working use F8 Key to run the code .

dim WS as worksheet
dim i as long

set ws = thisworkbook("SheetName")

ws.activate

ws.range("a1").select

ws.range("a1048576").select

activecell.end(xlup).select

i= activecell.row

msgbox "My Last Row Is " & i

End sub

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

Wow, this one took me a while to solve, as I was using SVN through Eclipse. In the end, the only thing that worked for me was to commit all non-affected files, then (with Eclipse closed) rename the project directory, and re-check the project out from SVN. Glad it works properly now!

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

JSP : JSTL's <c:out> tag

You can explicitly enable escaping of Xml entities by using an attribute escapeXml value equals to true. FYI, it's by default "true".

How do you test running time of VBA code?

Seconds with 2 decimal spaces:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer

seconds format

Milliseconds:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer

milliseconds format

Milliseconds with comma seperator:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer

Milliseconds with comma seperator

Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.

Calendar Recurring/Repeating Events - Best Storage Method

The two examples you've given are very simple; they can be represented as a simple interval (the first being four days, the second being 14 days). How you model this will depend entirely on the complexity of your recurrences. If what you have above is truly that simple, then store a start date and the number of days in the repeat interval.

If, however, you need to support things like

Event A repeats every month on the 3rd of the month starting on March 3, 2011

Or

Event A repeats second Friday of the month starting on March 11, 2011

Then that's a much more complex pattern.

Location of Django logs and errors

Logs are set in your settings.py file. A new, default project, looks like this:

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

By default, these don't create log files. If you want those, you need to add a filename parameter to your handlers

    'applogfile': {
        'level':'DEBUG',
        'class':'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
        'maxBytes': 1024*1024*15, # 15MB
        'backupCount': 10,
    },

This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.

In the loggers section from above, you need to add applogfile to the handlers for your application

'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'APPNAME': {
            'handlers': ['applogfile',],
            'level': 'DEBUG',
        },
    }

This example will put your logs in your Django root in a file named APPNAME.log

Creating a URL in the controller .NET MVC

I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:

var urlHelper = new UrlHelper(this.ControllerContext);

Or, you could just use the Controller.Url property if you inherit from Controller.

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

List of Stored Procedures/Functions Mysql Command Line

Shows all the stored procedures:

SHOW PROCEDURE STATUS;

Shows all the functions:

SHOW FUNCTION STATUS;

Shows the definition of the specified procedure:

SHOW CREATE PROCEDURE [PROC_NAME];

Shows you all the procedures of the given database:

SHOW PROCEDURE STATUS WHERE Db = '[db_name]';

Alphabet range in Python

[chr(i) for i in range(ord('a'),ord('z')+1)]

Preloading images with jQuery

I usually use this snippet of code on my projects for the loading of the images in a page. You can see the result here https://jsfiddle.net/ftor34ey/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />

<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
    .bg {
        background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
    }
</style>
<div class="bg"></div>

<div id="loadingProgress"></div>

The script save in an array all the src and background-image of the page and load all of them.

You can see/read/show the progress of the loading by the var loadCount.

let backgroundImageArray = [];

function backgroundLoading(i) {

    let loadCount = 0;

    let img = new Image();
    $(img).on('load', function () {

        if (i < backgroundImageArray.length) {

            loadCount = parseInt(((100 / backgroundImageArray.length) * i));
            backgroundLoading(i + 1);

        } else {

            loadCount = 100;
            // do something when the page finished to load all the images
            console.log('loading completed!!!');
            $('#loadingProgress').append('<div>loading completed!!!</div>');

        }

        console.log(loadCount + '%');
        $('#loadingProgress').append('<div>' + loadCount + '%</div>');

    }).attr('src', backgroundImageArray[i - 1]);

}

$(document).ready(function () {

    $('*').each(function () {

        var backgroundImage = $(this).css('background-image');
        var putInArray = false;

        var check = backgroundImage.substr(0, 3);

        if (check == 'url') {

            backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
            backgroundImage = backgroundImage.replace('"', '');
            backgroundImage = backgroundImage.replace('"', '');

            if (backgroundImage.substr(0, 4) == 'http') {
                backgroundImage = backgroundImage;
            }
            putInArray = true;

        } else if ($(this).get(0).tagName == 'IMG') {

            backgroundImage = $(this).attr('src');
            putInArray = true;

        }

        if (putInArray) {
            backgroundImageArray[backgroundImageArray.length] = backgroundImage;
        }

    });

    backgroundLoading(1);

});

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

To run Mocha with mocha command from your terminal you need to install mocha globally on this machine:

npm install --global mocha

Then cd to your projectFolder/test and run mocha yourTestFileName.js


If you want to make mocha available inside your package.json as a development dependency:

npm install --save-dev mocha

Then add mocha to your scripts inside package.json.

"scripts": {
    "test": "mocha"
  },

Then run npm test inside your terminal.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

What's the difference between <b> and <strong>, <i> and <em>?

You should generally try to avoid <b> and <i>. They were introduced for layouting the page (changing the way how it looks) in early HMTL versions prior to the creation of CSS, like the meanwhile removed font tag, and were mainly kept for backward compatibility and because some forums allow inline HTML and that's an easy way to change the look of text (like BBCode using [i], you can use <i> and so on).

Since the creation of CSS, layouting is actually nothing that should be done in HTML anymore, that's why CSS has been created in the first place (HTML == Structure, CSS == Layout). These tags may as well vanish in the future, after all you can just use CSS and span tags to make text bold/italic if you need a "meaningless" font variation. HTML 5 still allows them but declares that marking text that way has no meaning.

<em> and <strong> on the other hand only says that something is "emphasized" or "strongly emphasized", it leaves it completely open to the browser how to render it. Most browsers will render em as italic and strong as bold as the standard suggests by default, but they are not forced to do that (they may use different colors, font sizes, fonts, whatever). You can use CSS to change the behavior the way you desire. You can make em bold if you like and strong bold and red, for example.

Check/Uncheck checkbox with JavaScript

I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.

So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.

Which version of CodeIgniter am I currently using?

Please check the file "system/core/CodeIgniter.php". It is defined in const CI_VERSION = '3.1.10';

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

All good answers. To put it in simple language [BCNF] No partial key can depend on a key.

i.e No partial subset ( i.e any non trivial subset except the full set ) of a candidate key can be functionally dependent on some candidate key.

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

Refresh Page C# ASP.NET

Depending on what exactly you require, a Server.Transfer might be a resource-cheaper alternative to Response.Redirect. More information is in Server.Transfer Vs. Response.Redirect.

How to measure elapsed time

When the game starts:

long tStart = System.currentTimeMillis();

When the game ends:

long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;

Can I use CASE statement in a JOIN condition?

A CASE expression returns a value from the THEN portion of the clause. You could use it thusly:

SELECT  * 
FROM    sys.indexes i 
    JOIN sys.partitions p 
        ON i.index_id = p.index_id  
    JOIN sys.allocation_units a 
        ON CASE 
           WHEN a.type IN (1, 3) AND a.container_id = p.hobt_id THEN 1
           WHEN a.type IN (2) AND a.container_id = p.partition_id THEN 1
           ELSE 0
           END = 1

Note that you need to do something with the returned value, e.g. compare it to 1. Your statement attempted to return the value of an assignment or test for equality, neither of which make sense in the context of a CASE/THEN clause. (If BOOLEAN was a datatype then the test for equality would make sense.)

Create list of single item repeated N times

Itertools has a function just for that:

import itertools
it = itertools.repeat(e,n)

Of course itertools gives you a iterator instead of a list. [e] * n gives you a list, but, depending on what you will do with those sequences, the itertools variant can be much more efficient.

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

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

I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".

EDIT

It looks like you may be able to use the GetObject function to pull the textbox from the workbook.

How to filter a RecyclerView with a SearchView

With Android Architecture Components through the use of LiveData this can be easily implemented with any type of Adapter. You simply have to do the following steps:

1. Setup your data to return from the Room Database as LiveData as in the example below:

@Dao
public interface CustomDAO{

@Query("SELECT * FROM words_table WHERE column LIKE :searchquery")
    public LiveData<List<Word>> searchFor(String searchquery);
}

2. Create a ViewModel object to update your data live through a method that will connect your DAO and your UI

public class CustomViewModel extends AndroidViewModel {

    private final AppDatabase mAppDatabase;

    public WordListViewModel(@NonNull Application application) {
        super(application);
        this.mAppDatabase = AppDatabase.getInstance(application.getApplicationContext());
    }

    public LiveData<List<Word>> searchQuery(String query) {
        return mAppDatabase.mWordDAO().searchFor(query);
    }

}

3. Call your data from the ViewModel on the fly by passing in the query through onQueryTextListener as below:

Inside onCreateOptionsMenu set your listener as follows

searchView.setOnQueryTextListener(onQueryTextListener);

Setup your query listener somewhere in your SearchActivity class as follows

private android.support.v7.widget.SearchView.OnQueryTextListener onQueryTextListener =
            new android.support.v7.widget.SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    getResults(query);
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    getResults(newText);
                    return true;
                }

                private void getResults(String newText) {
                    String queryText = "%" + newText + "%";
                    mCustomViewModel.searchQuery(queryText).observe(
                            SearchResultsActivity.this, new Observer<List<Word>>() {
                                @Override
                                public void onChanged(@Nullable List<Word> words) {
                                    if (words == null) return;
                                    searchAdapter.submitList(words);
                                }
                            });
                }
            };

Note: Steps (1.) and (2.) are standard AAC ViewModel and DAO implementation, the only real "magic" going on here is in the OnQueryTextListener which will update the results of your list dynamically as the query text changes.

If you need more clarification on the matter please don't hesitate to ask. I hope this helped :).

How can I pad a value with leading zeros?

A simple one for my use case (to fill milliseconds never > 999) You can adjust the number of zeros for yours or use a more generic way if required.

/**
 * @val integer
 * @zeros padding
 */
function zeroFill(val, zeros)
{
    var str = val.toString();
    if (str.length >= zeros)
        return str;
    str = "000" + str;
    return str.substring(str.length - zeros);
}

How to append the output to a file?

Use >> to append:

command >> file

How to secure an ASP.NET Web API

in continuation to @ Cuong Le's answer , my approach to prevent replay attack would be

// Encrypt the Unix Time at Client side using the shared private key(or user's password)

// Send it as part of request header to server(WEB API)

// Decrypt the Unix Time at Server(WEB API) using the shared private key(or user's password)

// Check the time difference between the Client's Unix Time and Server's Unix Time, should not be greater than x sec

// if User ID/Hash Password are correct and the decrypted UnixTime is within x sec of server time then it is a valid request

Insert multiple rows with one query MySQL

If you would like to insert multiple values lets say from multiple inputs that have different post values but the same table to insert into then simply use:

mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES 
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows

Best programming based games

The game in question was definitely Robowar for the Mac. My son had a lot of fun with it and went on to program real robots.

As mentioned earlier by Proud, there is a wiki page for it: http://en.wikipedia.org/wiki/RoboWar

Although there has not been a lot of activity surrounding the game over the last few years, there was a tournament held recently, and there is a yahoo email group.

How to set null to a GUID property

Guid? myGuidVar = (Guid?)null;

It could be. Unnecessary casting not required.

Guid? myGuidVar = null;

django order_by query set, ascending and descending

Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.

class MyModel(models.Model):

    check_in = models.DateField()

    class Meta:
        ordering = ('-check_in',)

How to convert int to Integer

i it integer, int to Integer

Integer intObj = new Integer(i);

add to collection

list.add(String.valueOf(intObj));

ant build.xml file doesn't exist

You have invoked Ant with the verbose (-v) mode but the default buildfile build.xml does not exist. Nor have you specified any other buildfile for it to use.

I would say your Ant installation is fine.

Adding placeholder text to textbox

I came up with a method that worked for me, but only because I was willing to use the textbox name as my placeholder. See below.

public TextBox employee = new TextBox();

private void InitializeHomeComponent()
{
    //
    //employee
    //
    this.employee.Name = "Caller Name";
    this.employee.Text = "Caller Name";
    this.employee.BackColor = System.Drawing.SystemColors.InactiveBorder;
    this.employee.Location = new System.Drawing.Point(5, 160);
    this.employee.Size = new System.Drawing.Size(190, 30);
    this.employee.TabStop = false;
    this.Controls.Add(employee);
    // I loop through all of my textboxes giving them the same function
    foreach (Control C in this.Controls)
    {
        if (C.GetType() == typeof(System.Windows.Forms.TextBox))
        {
            C.GotFocus += g_GotFocus;
            C.LostFocus += g_LostFocus;
        }
     }
 }

    private void g_GotFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        tbox.Text = "";
    }

    private void g_LostFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        if (tbox.Text == "")
        {
            tbox.Text = tbox.Name;
        }
    }

Self-reference for cell, column and row in worksheet functions

My current Column is calculated by:

Method 1:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))

Method 2:

=LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)

My current Row is calculated by:

=RIGHT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ROW()))

so an indirect link to Sheet2!My Column but a different row, specified in Column A on my row is:

Method 1:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),LEN(ADDRESS(ROW(),COLUMN(),4,1))-LEN(ROW()))&INDIRECT(ADDRESS(ROW(),1,4,1)))

Method 2:

=INDIRECT("Sheet2!"&LEFT(ADDRESS(ROW(),COLUMN(),4,1),INT((COLUMN()-1)/26)+1)&INDIRECT(ADDRESS(ROW(),1,4,1)))

So if A6=3 and my row is 6 and my Col is C returns contents of "Sheet2!C3"

So if A7=1 and my row is 7 and my Col is D returns contents of "Sheet2!D1"

How to delete parent element using jQuery

what about using unwrap()

<div class="parent">
<p class="child">
</p>
</div>

after using - $(".child").unwrap() - it will be;

<p class="child">
</p>

Check if image exists on server using JavaScript?

This works fine:

function checkImage(imageSrc) {
    var img = new Image();        
    try {
        img.src = imageSrc;
        return true;
    } catch(err) {
        return false;
    }    
}

How to extract custom header value in Web API message handler?

For ASP.Net Core there is an easy solution if want to use the param directly in the controller method: Use the [FromHeader] annotation.

        public JsonResult SendAsync([FromHeader] string myParam)
        {
        if(myParam == null)  //Param not set in request header
        {
           return null;
        }
        return doSomething();
    }   

Additional Info: In my case the "myParam" had to be a string, int was always 0.

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

Git Clone from GitHub over https with two-factor authentication

1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:

$ git push
Username for 'https://github.com':            # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token

Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Redirect Windows cmd stdout and stderr to a single file

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1

Detecting the onload event of a window opened with window.open

If the pop-up's document is from a different domain, this is simply not possible.

Update April 2015: I was wrong about this: if you own both domains, you can use window.postMessage and the message event in pretty much all browsers that are relevant today.

If not, there's still no way you'll be able to make this work cross-browser without some help from the document being loaded into the pop-up. You need to be able to detect a change in the pop-up that occurs once it has loaded, which could be a variable that JavaScript in the pop-up page sets when it handles its own load event, or if you have some control of it you could add a call to a function in the opener.

Can an abstract class have a constructor?

In a concrete class, declaration of a constructor for a concrete type Fnord effectively exposes two things:

  • A means by which code can request the creation of an instance of Fnord

  • A means by which an instance of a type derived from Fnord which is under construction can request that all base-class features be initialized.

While there should perhaps be a means by which these two abilities could be controlled separately, for every concrete type one definition will enable both. Although the first ability is not meaningful for an abstract class, the second ability is just as meaningful for an abstract class as it would be for any other, and thus its declaration is just as necessary and useful.

ld cannot find an existing library

The problem is the linker is looking for libmagic.so but you only have libmagic.so.1

A quick hack is to symlink libmagic.so.1 to libmagic.so

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

How to get current SIM card number in Android?

You have everything right, but the problem is with getLine1Number() function.

getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.

this method works only for few cell phone but not all phones.

So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber(). It is always unique, valid and it always exists.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

html table span entire width?

Try (in your <head> section, or existing css definitions)...

<style>
  body {
   margin:0;
   padding:0;
  }
</style>

Mockito, JUnit and Spring

You don't really need the MockitoAnnotations.initMocks(this); if you're using mockito 1.9 ( or newer ) - all you need is this:

@InjectMocks
private MyTestObject testObject;

@Mock
private MyDependentObject mockedObject;

The @InjectMocks annotation will inject all your mocks to the MyTestObject object.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

For me the following code works fine, all conditional comments are working in all IE versions:

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 11)|!(IE)]><!--> <html> <!--<![endif]-->

<script>
    if (document.documentMode===10){
        document.documentElement.className+=' ie10';
    }
    else if (document.documentMode===11){
        document.documentElement.className+=' ie11';
    }
</script>

I'm on windows 8.1, not sure if it's related to ie11 update...

Manually install Gradle and use it in Android Studio

Follow these steps

  1. Download gradle
  2. Extract the file to a specific location you desire
  3. Open android studio Click on setting and on build, execution and deployment, then gradle
  4. Enable work offline and change service directory to the location of the extracted filed.

This is what worked for me. I hope it helps.

How can you test if an object has a specific property?

Like this?

 [bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Show/Hide Div on Scroll

$(window).scroll(function () {
  var Bottom = $(window).height() + $(window).scrollTop() >= $(document).height();
if(Bottom )
{
$('#div').hide();
}
});

Programmatic equivalent of default(Type)

The Expressions can help here:

    private static Dictionary<Type, Delegate> lambdasMap = new Dictionary<Type, Delegate>();

    private object GetTypedNull(Type type)
    {
        Delegate func;
        if (!lambdasMap.TryGetValue(type, out func))
        {
            var body = Expression.Default(type);
            var lambda = Expression.Lambda(body);
            func = lambda.Compile();
            lambdasMap[type] = func;
        }
        return func.DynamicInvoke();
    }

I did not test this snippet, but i think it should produce "typed" nulls for reference types..

findAll() in yii

Another simple way get by using findall in yii

$id =101; 
$comments = EmailArchive::model()->findAll(array("condition"=>"':email_id'=$id"));
foreach($comments as $comments_1) 
{ 
echo  "email:".$comments_1['email_id'];
}

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

  1. Uninstall mysql using yum remove mysql*

  2. Recursively delete /usr/bin/mysql and /var/lib/mysql

  3. Delete the file /etc/my.cnf.rmp

  4. Use ps -e to check the processes to make sure mysql isn't still running.

  5. Reboot server with reboot

  6. Run yum install mysql-server. This also seems to install the mysql client as a dependency.

  7. Give mysql ownership and group priveleges with:

    chown -R mysql /var/lib/mysql

    chgrp -R mysql /var/lib/mysql

  8. Use service mysqld start to start MySQL Daemon.

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

Radio button checked event handling

The HTML code:

<input type="radio" name="theName" value="1" id="option-1">
<input type="radio" name="theName" value="2">
<input type="radio" name="theName" value="3">

The Javascript code:

$(document).ready(function(){
    $('input[name="theName"]').change(function(){
        if($('#option-1').prop('checked')){
            alert('Option 1 is checked!');
        }else{
            alert('Option 1 is unchecked!');
        }
    });
});

In multiple radio with name "theName", detect when option 1 is checked or unchecked. Works in all situations: on click control, use the keyboard, use joystick, automatic change the values from other dinamicaly function, etc.

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

How can I create 2 separate log files with one log4j config file?

Modify your log4j.properties file accordingly:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

Change the log levels for each logger depending to your needs.

What ports does RabbitMQ use?

To find out what ports rabbitmq uses:

$ epmd -names

Outputs:

epmd: up and running on port 4369 with data:
name rabbit at port 25672

Run these as root:

lsof -i :4369
lsof -i :25672

More about epmd options.

How to access form methods and controls from a class in C#?

If the form starts up first, in the form Load handler we can instantiate a copy of our class. We can have properties that reference whichever controls we want to reference. Pass the reference to the form 'this' to the constructor for the class.

public partial class Form1 : Form
{
    public ListView Lv
    {
        get { return lvProcesses; }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Utilities ut = new Utilities(this);
    }
}

In your class, the reference from the form is passed into the constructor and stored as a private member. This form reference can be used to access the form's properties.

class Utilities
{
    private Form1 _mainForm;
    public Utilities(Form1 mainForm)
    {
        _mainForm = mainForm;
        _mainForm.Lv.Items.Clear();
    }
}

Storing and Retrieving ArrayList values from hashmap

Our variable:

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

To store:

map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));

To add numbers one and one, you can do something like this:

String key = "mango";
int number = 42;
if (map.get(key) == null) {
    map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);

In Java 8 you can use putIfAbsent to add the list if it did not exist already:

map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);

Use the map.entrySet() method to iterate on:

for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.
}

How to get number of rows inserted by a transaction

You can use @@trancount in MSSQL

From the documentation:

Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

How to get featured image of a product in woocommerce

This should do the trick:

<?php
    $product_meta = get_post_meta($post_id);
    echo wp_get_attachment_image( $product_meta['_thumbnail_id'][0], 'full' );
?>

You can change the parameters according to your needs.

Configure WAMP server to send email

I used Mercury/32 and Pegasus Mail to get the mail() functional. It works great too as a mail server if you want an email address ending with your domain name.

How to read a single char from the console in Java (as the user types it)?

There is no portable way to read raw characters from a Java console.

Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

Java null check why use == instead of .equals()

According to sources it doesn't matter what to use for default method implementation:

public boolean equals(Object object) {
    return this == object;
}

But you can't be sure about equals in custom class.

configure Git to accept a particular self-signed server certificate for a particular https remote

On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

javascript : sending custom parameters with window.open() but its not working

You can try this instead


var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;

Note: Do not use this method to pass sensitive information like username, password.

UTF-8 byte[] to String

Java String class has a built-in-constructor for converting byte array to string.

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray, "UTF-8");

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

It is an npm 5.4.0 issue https://github.com/npm/npm/issues/18287

Workarounds are

  • downgrade to 5.3
  • try running with --no-optional, i.e. npm install --no-optional

jQuery.post( ) .done( ) and success:

The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.

Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:

asyncCall(function(err, data1){
    if(err) return callback(err);       
    anotherAsyncCall(function(err2, data2){
        if(err2) return calllback(err2);
        oneMoreAsyncCall(function(err3, data3){
            if(err3) return callback(err3);
            // are we done yet?
        });
    });
});

With Promises above code can be rewritten as below:

asyncCall()
.then(function(data1){
    // do something...
    return anotherAsyncCall();
})
.then(function(data2){
    // do something...  
    return oneMoreAsyncCall();    
})
.then(function(data3){
    // the third and final async response
})
.fail(function(err) {
    // handle any error resulting from any of the above calls    
})
.done();

Versioning SQL Server database

I would suggest using comparison tools to improvise a version control system for your database. Two good alternatives are xSQL Schema Compare and xSQL Data Compare.

Now, if your goal is to have only the database's schema under version control you can simply use xSQL Schema Compare to generate xSQL Snapshots of the schema and add these files in your version control. Then, to revert or update to a specific version, just compare the current version of the database with the snapshot for the destination version.

Also, if you want to have the data under version control as well, you can use xSQL Data Compare to generate change scripts for you database and add the .sql files in your version control. You could then execute these scripts to revert / update to any version you want. Keep in mind that for the 'revert' functionality you need to generate change scripts that, when executed, will make Version 3 the same as Version 2 and for the 'update' functionality, you need to generate change scripts that do the opposite.

Lastly, with some basic batch programming skills you can automate the whole process by using the command line versions of xSQL Schema Compare and xSQL Data Compare

Disclaimer: I'm affiliated to xSQL.

Setting query string using Fetch GET request

Update March 2017:

URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.


The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:

var url = new URL("https://geo.example.org/api"),
    params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

However, I'm not sure Chrome supports the searchParams property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.

Update April 2018:

With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search instead of looping over all keys and append them

var url = new URL('https://sl.se')

var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]

url.search = new URLSearchParams(params).toString();

fetch(url)

Sidenote: URLSearchParams is also available in NodeJS

const { URL, URLSearchParams } = require('url');

How can I copy the content of a branch to a new local branch?

git branch copyOfMyBranch MyBranch

This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

If you load a page in your browser using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your API must not allow for HTTPS connections. Because of this, you must either force HTTP on the main page or request that they allow HTTPS connections.

Note on this: The request will still work if you go to the API URL instead of attempting to load it with AJAX. This is because the browser is not loading a resource from within a secured page, instead it's loading an insecure page and it's accepting that. In order for it to be available through AJAX, though, the protocols should match.

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

How to remove certain characters from a string in C++?

using namespace std;


// c++03
string s = "(555) 555-5555";
s.erase(remove_if(s.begin(), s.end(), not1(ptr_fun(::isdigit))), s.end());

// c++11
s.erase(remove_if(s.begin(), s.end(), ptr_fun(::ispunct)), s.end());

Note: It's posible you need write ptr_fun<int, int> rather than simple ptr_fun

c# .net change label text

you should convert test type >>>> test.tostring();

change the last line to this :

Label1.Text = "Du har nu lånat filmen:" + test.tostring();

adding comment in .properties files

According to the documentation of the PropertyFile task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The first error

java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

You have a couple of choices that you can pick from to get the code to compile.

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

Get remote registry value

If you have Powershell remoting and CredSSP setup then you can update your code to the following:

$Session = New-PSSession -ComputerName $Computer1 -Authentication CredSSP
$NetbackupVersion1 = Invoke-Command -Session $Session -ScriptBlock { $(Get-ItemProperty hklm:\SOFTWARE\Veritas\NetBackup\CurrentVersion).PackageVersion}
Remove-PSSession $Session

Adding div element to body or document in JavaScript

The modern way is to use ParentNode.append(), like so:

_x000D_
_x000D_
let element = document.createElement('div');_x000D_
element.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';_x000D_
document.body.append(element);
_x000D_
_x000D_
_x000D_

Waiting till the async task finish its work

In your AsyncTask add one ProgressDialog like:

private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);

you can setMessage in onPreExecute() method like:

this.dialog.setMessage("Processing..."); 
this.dialog.show();

and in your onPostExecute(Void result) method dismiss your ProgressDialog.

How to load up CSS files using Javascript?

I know this is a pretty old thread but here comes my 5 cents.

There is another way to do this depending on what your needs are.

I have a case where i want a css file to be active only a while. Like css switching. Activate the css and then after another event deativate it.

Instead of loading the css dynamically and then removing it you can add a Class/an id in front of all elements in the new css and then just switch that class/id of the base node of your css (like body tag).

You would with this solution have more css files initially loaded but you have a more dynamic way of switching css layouts.

How can I generate a tsconfig.json file?

You need to have typescript library installed and then you can use

npx tsc --init 

If the response is error TS5023: Unknown compiler option 'init'. that means the library is not installed

yarn add --dev typescript

and run npx command again

How to export a Vagrant virtual machine to transfer it

You have two ways to do this, I'll call it dirty way and clean way:

1. The dirty way

Create a box from your current virtual environment, using vagrant package command:

http://docs.vagrantup.com/v2/cli/package.html

Then copy the box to the other pc, add it using vagrant box add and run it using vagrant up as usual.

Keep in mind that files in your working directory (the one with the Vagrantfile) are shared when the virtual machine boots, so you need to copy it to the other pc as well.

2. The clean way

Theoretically it should never be necessary to do export/import with Vagrant. If you have the foresight to use provisioning for configuring the virtual environment (chef, puppet, ansible), and a version control system like git for your working directory, copying an environment would be at this point simple as running:

git clone <your_repo>
vagrant up

Use placeholders in yaml

With Yglu Structural Templating, your example can be written:

foo: !()
  !? $.propname: 
     type: number 
     default: !? $.default

bar:
  !apply .foo: 
    propname: "some_prop"
    default: "some default"

Disclaimer: I am the author or Yglu.

Accessing bash command line args $@ vs $*

A nice handy overview table from the Bash Hackers Wiki:

Syntax Effective result
$* $1 $2 $3 … ${N}
$@ $1 $2 $3 … ${N}
"$*" "$1c$2c$3c…c${N}"
"$@" "$1" "$2" "$3" … "${N}"

where c in the third row is the first character of $IFS, the Input Field Separator, a shell variable.

If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*" trick with the input field separator set to tab IFS=$'\t'.

How do I create a new user in a SQL Azure database?

I use the Azure Management console tool of CodePlex, with a very useful GUI, try it. You can save type some code.

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

PostgreSQL Forging Key DELETE, UPDATE CASCADE

CREATE TABLE apps_user(
  user_id SERIAL PRIMARY KEY,
  username character varying(30),
  userpass character varying(50),
  created_on DATE
);

CREATE TABLE apps_profile(
    pro_id SERIAL PRIMARY KEY,
    user_id INT4 REFERENCES apps_user(user_id) ON DELETE CASCADE ON UPDATE CASCADE,
    firstname VARCHAR(30),
    lastname VARCHAR(50),
    email VARCHAR UNIQUE,
    dob DATE
);

How npm start runs a server on port 8000

To start the port correctly in your desired port use:

npm start -- --port 8000

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us

            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },

    list: {
        blueHorse: {
            color: 'blue'
        },

        redHorse: {
            color: 'red'
        }
    }
};

Template:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

Outputs:

color: blue
color: red

(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.

ActiveRecord find and only return selected columns

pluck(column_name)

This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.

Examples:

Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns

How to get first two characters of a string in oracle query?

Just use SUBSTR function. It takes 3 parameters: String column name, starting index and length of substring:

select SUBSTR(OrderNo, 1, 2) FROM shipment;

How do I flush the PRINT buffer in TSQL?

Just for the reference, if you work in scripts (batch processing), not in stored procedure, flushing output is triggered by the GO command, e.g.

print 'test'
print 'test'
go

In general, my conclusion is following: output of mssql script execution, executing in SMS GUI or with sqlcmd.exe, is flushed to file, stdoutput, gui window on first GO statement or until the end of the script.

Flushing inside of stored procedure functions differently, since you can not place GO inside.

Reference: tsql Go statement

Inner text shadow with CSS

Building on the :before :after technique by web_designer, here is something that comes closer to your look:

First, make your text the color of the inner shadow (black-ish in the case of the OP).

Now, use an :after psuedo class to create a transparent duplicate of the original text, placed directly on top of it. Assign a regular text shadow to it with no offset. Assign the original text color to the shadow, and adjust alpha as needed.

http://dabblet.com/gist/2499892

You don't get complete control over spread, etc. of the shadow like you do in PS, but for smaller blur values it is quite passable. The shadow goes past the bounds of the text, so if you are working in an environment with a high contrast background-foreground, it will be obvious. For lower contrast items, especially ones with the same hue, it's not too noticeable. For example, I've been able to make very nice looking etched text in metal backgrounds using this technique.

Counting lines, words, and characters within a text file using Python

One of the way I like is this one , but may be good for small files

with open(fileName,'r') as content_file:
    content = content_file.read()
    lineCount = len(re.split("\n",content))
    words = re.split("\W+",content.lower())

To count words, there is two way, if you don't care about repetition you can just do

words_count = len(words)

if you want the counts of each word you can just do

import collections
words_count = collections.Counter(words) #Count the occurrence of each word