Programs & Examples On #Quickbooks

QuickBooks is popular small to medium-sized business accounting software created by Intuit, Inc. QuickBooks Pro/Premier/Enterprise for Windows all include support for programmatic access to QuickBooks via Intuit's SDK/XML-based APIs. QuickBooks Online edition also supports an XML-based API. QuickBooks for Mac does not support any SDK/API/programmatic access.

Generate Java classes from .XSD files...?

If you don't mind using an external library, I've used Castor to do this in the past.

using .join method to convert array to string without commas

You can specify an empty string as an argument to join, if no argument is specified a comma is used.

 arr.join('');

http://jsfiddle.net/mowglisanu/CVr25/1/

Loop through files in a folder using VBA?

Dir takes wild cards so you could make a big difference adding the filter for test up front and avoiding testing each file

Sub LoopThroughFiles()
    Dim StrFile As String
    StrFile = Dir("c:\testfolder\*test*")
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir
    Loop
End Sub

How to center images on a web page for all screen sizes

Try something like this...

<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

Alternatively, style the tbody with a predetermined size (via height:20em, for example) and use overflow-y:scroll;

Then, you can have a huge tbody, which will scroll independently of the rest of the page.

How to continue a Docker container which has exited

These commands will work for any container (not only last exited ones). This way will work even after your system has rebooted. To do so, these commands will use "container id".

Steps:

  1. List all dockers by using this command and note the container id of the container you want to restart: docker ps -a

  2. Start your container using container id: docker start <container_id>

  3. Attach and run your container: docker attach <container_id>

NOTE: Works on linux

R: Plotting a 3D surface from x, y, z

You can use the function outer() to generate it.

Have a look at the demo for the function persp(), which is a base graphics function to draw perspective plots for surfaces.

Here is their first example:

x <- seq(-10, 10, length.out = 50)  
y <- x  
rotsinc <- function(x,y) {
    sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }  
    10 * sinc( sqrt(x^2+y^2) )  
}

z <- outer(x, y, rotsinc)  
persp(x, y, z)

The same applies to surface3d():

require(rgl)  
surface3d(x, y, z)

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 "-".

SQL MAX of multiple columns?

Please try using UNPIVOT:

SELECT MAX(MaxDt) MaxDt
   FROM tbl 
UNPIVOT
   (MaxDt FOR E IN 
      (Date1, Date2, Date3)
)AS unpvt;

How to join entries in a set into one string?

You have the join statement backwards try:

print ', '.join(set_3)

List of all special characters that need to be escaped in a regex

The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.

There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:

regex.replaceAll("[\\W]", "\\\\$0")

Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:

  • > becomes \> which is equivalent to >
  • [ becomes \[ which is the escaped form of [
  • 8 is still 8.
  • \) becomes \\\) which is the escaped forms of \ and ( concatenated.

Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].

JQuery string contains check

Please try:

str1.contains(str2)

AttributeError: 'tuple' object has no attribute

I am working in python flask: I had the same problem... There was a "," after I declared my my form variables; I am working with wtforms. That is what caused all the confusion

npx command not found

if you are using Linux system, use sudo command

sudo npm i -g npx

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

iOS: Multi-line UILabel in Auto Layout

One way to do this... As text length increases try to change (decrease) the fontsize of the label text using

Label.adjustsFontSizeToFitWidth = YES;

How do I calculate someone's age based on a DateTime type birthday?

I would simply do this:

DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;

This way you can calculate the exact age of a person, down to the millisecond if you want.

How to check if div element is empty

var empty = $("#cartContent").html().trim().length == 0;

PHP foreach change original array values

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

I would recommend doing the following:

foreach ($fields as $key => $field) {
    if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
        $fields[$key]['value'] = "Some error";
    }
}

So basically use $field when you need the values, and $fields[$key] when you need to change the data.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Listing all foreign keys in a db including description

    SELECT  
    i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
    i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
    i2.UPDATE_RULE, i2.DELETE_RULE 
    FROM   
    information_schema.KEY_COLUMN_USAGE AS i1  
    INNER JOIN 
    information_schema.REFERENTIAL_CONSTRAINTS AS i2 
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
    WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL  
    AND  i1.TABLE_SCHEMA  ='db_name';

restricting to a specific column in a table table

AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'

How to generate and validate a software license key?

I don't know how elaborate you want to get

but i believe that .net can access the hard drive serial number.

you could have the program send you that and something eles ( like user name and mac address of the nic)

you compute a code based off that and email them back the key.

they will keep them from switching machines after they have the key.

How to count the number of columns in a table using SQL?

select count(*) 
from user_tab_columns
where table_name='MYTABLE' --use upper case

Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';

Relation between CommonJS, AMD and RequireJS?

Quoting

AMD:

  • One browser-first approach
  • Opting for asynchronous behavior and simplified backwards compatibility
  • It doesn't have any concept of File I/O.
  • It supports objects, functions, constructors, strings, JSON and many other types of modules.

CommonJS:

  • One server-first approach
  • Assuming synchronous behavior
  • Cover a broader set of concerns such as I/O, File system, Promises and more.
  • Supports unwrapped modules, it can feel a little more close to the ES.next/Harmony specifications, freeing you of the define() wrapper that AMD enforces.
  • Only support objects as modules.

Variable declaration in a header file

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).

How do I make a transparent canvas in html5?

Iif you want a particular <canvas id="canvasID"> to be always transparent you just have to set

#canvasID{
    opacity:0.5;
}

Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.

context.fillStyle = "rgba(0, 0, 200, 0.5)";

Is it really impossible to make a div fit its size to its content?

You can use:

width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;

EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

ALSO: http://dev.w3.org/csswg/css-box-3/

Open Facebook Page in Facebook App (if installed) on Android

This works on the latest version:

Go to https://graph.facebook.com/ (https://graph.facebook.com/fsintents for instance).

Copy your id Use this method:

public static Intent getOpenFacebookIntent(Context context) {
    try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
    } catch (Exception e) {
        return new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.facebook.com/<user_name_here>"));
    }
}

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Replace all latters from any language in 'A', and if you wish for example all digits to 0:

return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

All you need to do is to go to the control panel > Computer Management > Services and manually start the SQL express or SQL server. It worked for me.

Good luck.

Creating runnable JAR with Gradle

Have you tried the 'installApp' task? Does it not create a full directory with a set of start scripts?

http://www.gradle.org/docs/current/userguide/application_plugin.html

Rename specific column(s) in pandas

A much faster implementation would be to use list-comprehension if you need to rename a single column.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

If the need arises to rename multiple columns, either use conditional expressions like:

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

Or, construct a mapping using a dictionary and perform the list-comprehension with it's get operation by setting default value as the old name:

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key?old name, value?new name

df.columns = [col_dict.get(x, x) for x in df.columns]

Timings:

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

UITableView - change section header color

You can do this if you want header with custom color:

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

This solution works great since iOS 6.0.

How to install a specific version of a ruby gem?

As others have noted, in general use the -v flag for the gem install command.

If you're developing a gem locally, after cutting a gem from your gemspec:

$ gem install gemname-version.gem

Assuming version 0.8, it would look like this:

$ gem install gemname-0.8.gem

HTML5 validation when the input type is not "submit"

2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.

The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.

Updated solution snippet:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.reportValidity()) {
    f.submit();
  }
}

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

You edit an element's value by editing it's .value property.

document.getElementById('DATE').value = 'New Value';

How can I implement a tree in Python?

I've implemented trees using nested dicts. It is quite easy to do, and it has worked for me with pretty large data sets. I've posted a sample below, and you can see more at Google code

  def addBallotToTree(self, tree, ballotIndex, ballot=""):
    """Add one ballot to the tree.

    The root of the tree is a dictionary that has as keys the indicies of all 
    continuing and winning candidates.  For each candidate, the value is also
    a dictionary, and the keys of that dictionary include "n" and "bi".
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.

    If candidate c is a winning candidate, then that portion of the tree is
    expanded to indicate the breakdown of the subsequently ranked candidates.
    In this situation, additional keys are added to the tree[c] dictionary
    corresponding to subsequently ranked candidates.
    tree[c]["n"] is the number of ballots that rank candidate c first.
    tree[c]["bi"] is a list of ballot indices where the ballots rank c first.
    tree[c][d]["n"] is the number of ballots that rank c first and d second.
    tree[c][d]["bi"] is a list of the corresponding ballot indices.

    Where the second ranked candidates is also a winner, then the tree is 
    expanded to the next level.  

    Losing candidates are ignored and treated as if they do not appear on the 
    ballots.  For example, tree[c][d]["n"] is the total number of ballots
    where candidate c is the first non-losing candidate, c is a winner, and
    d is the next non-losing candidate.  This will include the following
    ballots, where x represents a losing candidate:
    [c d]
    [x c d]
    [c x d]
    [x c x x d]

    During the count, the tree is dynamically updated as candidates change
    their status.  The parameter "tree" to this method may be the root of the
    tree or may be a sub-tree.
    """

    if ballot == "":
      # Add the complete ballot to the tree
      weight, ballot = self.b.getWeightedBallot(ballotIndex)
    else:
      # When ballot is not "", we are adding a truncated ballot to the tree,
      # because a higher-ranked candidate is a winner.
      weight = self.b.getWeight(ballotIndex)

    # Get the top choice among candidates still in the running
    # Note that we can't use Ballots.getTopChoiceFromWeightedBallot since
    # we are looking for the top choice over a truncated ballot.
    for c in ballot:
      if c in self.continuing | self.winners:
        break # c is the top choice so stop
    else:
      c = None # no candidates left on this ballot

    if c is None:
      # This will happen if the ballot contains only winning and losing
      # candidates.  The ballot index will not need to be transferred
      # again so it can be thrown away.
      return

    # Create space if necessary.
    if not tree.has_key(c):
      tree[c] = {}
      tree[c]["n"] = 0
      tree[c]["bi"] = []

    tree[c]["n"] += weight

    if c in self.winners:
      # Because candidate is a winner, a portion of the ballot goes to
      # the next candidate.  Pass on a truncated ballot so that the same
      # candidate doesn't get counted twice.
      i = ballot.index(c)
      ballot2 = ballot[i+1:]
      self.addBallotToTree(tree[c], ballotIndex, ballot2)
    else:
      # Candidate is in continuing so we stop here.
      tree[c]["bi"].append(ballotIndex)

Best way to update an element in a generic List

You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)
    matchingDog.Name = "New Dog Name";

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

How to play a sound using Swift?

Swift 3

import AVFoundation


var myAudio: AVAudioPlayer!

    let path = Bundle.main.path(forResource: "example", ofType: "mp3")!
    let url = URL(fileURLWithPath: path)
do {
    let sound = try AVAudioPlayer(contentsOf: url)
    myAudio = sound
    sound.play()
} catch {
    // 
}

//If you want to stop the sound, you should use its stop()method.if you try to stop a sound that doesn't exist your app will crash, so it's best to check that it exists.

if myAudio != nil {
    myAudio.stop()
    myAudio = nil
}

Android Recyclerview vs ListView with Viewholder

I used a ListView with Glide image loader, having memory growth. Then I replaced the ListView with a RecyclerView. It is not only more difficult in coding, but also leads to a more memory usage than a ListView. At least, in my project.

In another activity I used a complex list with EditText's. In some of them an input method may vary, also a TextWatcher can be applied. If I used a ViewHolder, how could I replace a TextWatcher during scrolling? So, I used a ListView without a ViewHolder, and it works.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Detect Click into Iframe using JavaScript

Just found this solution... I tried it, I loved it..

Works for cross domain iframes for desktop and mobile!

Don't know if it is foolproof yet

window.addEventListener('blur',function(){
      if(document.activeElement.id == 'CrossDomainiframeId'){
        //do something :-)
      }
});

Happy coding

How to open a page in a new window or tab from code-behind

Target= "_blank"

This does it in html, give it a try in C#

addClass and removeClass in jQuery - not removing class

Try this :

$('.close-button').on('click', function(){
  $('.element').removeClass('grown');
  $('.element').addClass('spot');
});

$('.element').on('click', function(){
  $(this).removeClass('spot');
  $(this).addClass('grown');
});

I hope I understood your question.

What's the default password of mariadb on fedora?

mariadb uses by defaults UNIX_SOCKET plugin to authenticate user root. https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/

"Because he has identified himself to the operating system, he does not need to do it again for the database"

so you need to login as the root user on unix to login as root in mysql/mariadb:

sudo mysql

if you want to login with root from your normal unix user, you can disable the authentication plugin for root.

Beforehand you can set the root password with mysql_secure_installation (default password is blank), then to let every user authenticate as root login with:

shell$ sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q

How to unstage large number of files without deleting the content

If you want to unstage all the changes use below command,

git reset --soft HEAD

In the case you want to unstage changes and revert them from the working directory,

git reset --hard HEAD

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Eclipse count lines of code

ProjectCodeMeter counts LLOC (logical lines of code) exactly as you described (only effective lines). it integrates into eclipse as external code metrics tool, it's not real-time though, it generates a report.actually it counts many source code metrics such as complexity, arithmetic intricacy, hard coded strings, numeric constants.. even estimates development time in hours.

Check if an element is a child of a parent

If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

Example: http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Or if you want to check to see if there are any ancestors that match, then use .parents().

Example: http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

Dismissing a Presented View Controller

This is for view controller reusability.

Your view controller shouldn't care if it is being presented as a modal, pushed on a navigation controller, or whatever. If your view controller dismisses itself, then you're assuming it is being presented modally. You won't be able to push that view controller onto a navigation controller.

By implementing a protocol, you let the parent view controller decide how it should be presented/pushed and dismissed/popped.

Get Return Value from Stored procedure in asp.net

Do it this way (make necessary changes in code)..

            SqlConnection con = new SqlConnection(GetConnectionString());
            con.Open();
            SqlCommand cmd = new SqlCommand("CheckUser", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter p1 = new SqlParameter("username", username.Text);
            SqlParameter p2 = new SqlParameter("password", password.Text);
            cmd.Parameters.Add(p1);
            cmd.Parameters.Add(p2);
            SqlDataReader rd = cmd.ExecuteReader();
            if(rd.HasRows)
            {
                //do the things
            }
            else
            {
                lblinfo.Text = "abc";
            }

Display all items in array using jquery

You can do it like this by iterating through the array in a loop, accumulating the new HTML into it's own array and then joining the HTML all together and inserting it into the DOM at the end:

var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
    newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));

Some people prefer to use jQuery's .each() method instead of the for loop which would work like this:

var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
    newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Or because the output of the array iteration is itself an array with one item derived from each item in the original array, jQuery's .map can be used like this:

var array = [...];
var newHTML = $.map(array, function(value) {
    return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with .map(). My guess is that the for loop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.

FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it's best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.


And, if you can live with IE9 or above (or install an ES5 polyfill for .map()), you can use the array version of .map like this:

var array = [...];
$(".element").html(array.map(function(value) {
    return('<span>' + value + '</span>');
}).join(""));

Note: this version also gets rid of the newHTML intermediate variable in the interest of compactness.

Importing modules from parent folder

Although it is against all rules, I still want to mention this possibility:

You can first copy the file from the parent directory to the child directory. Next import it and subsequently remove the copied file:

for example in life.py:

import os
import shutil

shutil.copy('../nib.py', '.')
import nib
os.remove('nib.py')

# now you can use it just fine:
nib.foo()

Of course there might arise several problems when nibs tries to import/read other files with relative imports/paths.

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

COPY is

Same as 'ADD', but without the tar and remote URL handling.

Reference straight from the source code.

Singletons vs. Application Context in Android?

Application is not the same as the Singleton.The reasons are:

  1. Application's method(such as onCreate) is called in the ui thread;
  2. singleton's method can be called in any thread;
  3. In the method "onCreate" of Application,you can instantiate Handler;
  4. If the singleton is executed in none-ui thread,you could not instantiate Handler;
  5. Application has the ability to manage the life cycle of the activities in the app.It has the method "registerActivityLifecycleCallbacks".But the singletons has not the ability.

Getting Python error "from: can't read /var/mail/Bio"

I got same error because I was trying to run on

XXX-Macmini:Python-Project XXX.XXX$ from classDemo import MyClass

from: can't read /var/mail/classDemo

To solve this, type command python and when you get these >>> then run any python commands

>>>from classDemo import MyClass
>>>f = MyClass()

How to change indentation mode in Atom?

If global tab/spaces indentation settings no longer fit your needs (I.E. you find yourself working with legacy codebases with varied indentation formats, and you need to quickly switch between them, and the auto-detect isn't working) you might try the tab-control plugin, which sort of duplicates the functionality of the menu in your screenshot.

Setting HttpContext.Current.Session in a unit test

I found the following simple solution for specifying a user in the HttpContext: https://forums.asp.net/post/5828182.aspx

How to use background thread in swift?

Dan Beaulieu's answer in swift5 (also working since swift 3.0.1).

Swift 5.0.1

extension DispatchQueue {

    static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
        DispatchQueue.global(qos: .background).async {
            background?()
            if let completion = completion {
                DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
                    completion()
                })
            }
        }
    }

}

Usage

DispatchQueue.background(delay: 3.0, background: {
    // do something in background
}, completion: {
    // when background job finishes, wait 3 seconds and do something in main thread
})

DispatchQueue.background(background: {
    // do something in background
}, completion:{
    // when background job finished, do something in main thread
})

DispatchQueue.background(delay: 3.0, completion:{
    // do something in main thread after 3 seconds
})

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

my_element = document.querySelector(#non_existing_id);

Now that element is null, this will result in mentioned error:

my_style = window.getComputedStyle(my_element);

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

if (my_element === null) return;

Make DateTimePicker work as TimePicker only in WinForms

You want to set its 'Format' property to be time and add a spin button control to it:

yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

Adding and removing style attribute from div with jquery

Remove style attribute from div using J query:

$("#TableDiv").removeAttr("style");

Add style to div using J query:

$("#TableDiv").attr("style", "display: none;");

Add style using html:

<div class="row" id="TableDiv" style="display: none;">
</div>

Hope it will helpful :)

Override body style for content in an iframe

Perhaps it's changed now, but I have used a separate stylesheet with this element:

.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}

to successfully style embedded youtube iframes...see the blog posts on this page.

How to build a query string for a URL in C#?

Here is an implementation which uses very basic language features. It's part of a class which we have to port and maintain in Objective C so we choose to have more lines of code but easier to port and understand by a programmer that isn't very familiar with C#.

        /// <summary>
        /// Builds a complete http url with query strings.
        /// </summary>
        /// <param name="pHostname"></param>
        /// <param name="pPort"></param>
        /// <param name="pPage">ex "/index.html" or index.html</param>
        /// <param name="pGetParams">a Dictionary<string,string> collection containing the key value pairs.  Pass null if there are none.</param>
        /// <returns>a string of the form: http://[pHostname]:[pPort/[pPage]?key1=val1&key2=val2...</returns>

  static public string buildURL(string pHostname, int pPort, string pPage, Dictionary<string,string> pGetParams)
        {
            StringBuilder sb = new StringBuilder(200);
            sb.Append("http://");
            sb.Append(pHostname);
            if( pPort != 80 ) {
                sb.Append(pPort);
            }
            // Allows page param to be passed in with or without leading slash.
            if( !pPage.StartsWith("/") ) {
                sb.Append("/");
            }
            sb.Append(pPage);

            if (pGetParams != null && pGetParams.Count > 0)
            {
                sb.Append("?");
                foreach (KeyValuePair<string, string> kvp in pGetParams)
                {
                    sb.Append(kvp.Key);
                    sb.Append("=");
                    sb.Append( System.Web.HttpUtility.UrlEncode(kvp.Value) );
                    sb.Append("&");
                }
                sb.Remove(sb.Length - 1, 1); // Remove the final '&'
            }
            return sb.ToString();
        }

Git merge with force overwrite

Not really related to this answer, but I'd ditch git pull, which just runs git fetch followed by git merge. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:

git fetch origin   # update all our origin/* remote-tracking branches

git checkout demo         # if needed -- your example assumes you're on it
git merge origin/demo     # if needed -- see below

git checkout master
git merge origin/master

git merge -X theirs demo   # but see below

git push origin master     # again, see below

Controlling the trickiest merge

The most interesting part here is git merge -X theirs. As root545 noted, the -X options are passed on to the merge strategy, and both the default recursive strategy and the alternative resolve strategy take -X ours or -X theirs (one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.

A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours) version and the other (also called remote or --theirs) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.

These changes are what you see in git diff output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).

If the changes happen on different lines—for instance, we change color to colour on line 17 and they change fred to barney on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.

The -X ours and -X theirs options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo (theirs) into master (ours) and want the changes from demo, you would want -X theirs.

Blindly applying -X, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:

int i;

In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X option is no help here since the changes are on different lines.

If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit to the git merge command. We'll leave the details for all of this to other postings.


1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X arguments.


Doing fewer merges and/or smarter merges and/or using rebase

There are three merges in both of our command sequences. The first is to bring origin/demo into the local demo (yours uses git pull which, if your Git is very old, will fail to update origin/demo but will produce the same end result). The second is to bring origin/master into master.

It's not clear to me who is updating demo and/or master. If you write your own code on your own demo branch, and others are writing code and pushing it to the demo branch on origin, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase instead. On the other hand, if you never do any of your own commits on demo, you don't even need a demo branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo: this will fast-forward your demo to match the updated origin/demo if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).

This same logic applies to master, although you are doing the merge on master, so you definitely do need a master. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master.

Let's say that you never do your own commits on demo. In this case we can ditch the name demo entirely:

git fetch origin   # update origin/*

git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"

git merge -X theirs origin/demo || die "complex merge conflict"

git push origin master

If you are doing your own demo branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).

Python debugging tips

Defining useful repr() methods for your classes (so you can see what an object is) and using repr() or "%r" % (...) or "...{0!r}..".format(...) in your debug messages/logs is IMHO a key to efficient debugging.

Also, the debuggers mentioned in other answers will make use of the repr() methods.

How to pass extra variables in URL with WordPress

One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.

See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.

What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.

add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );

function add_custom_setcookie_rewrite_endpoints() {
    //add ?c=123 endpoint with
    //EP_ALL so endpoint is present across all places
    //no effect on the query vars
    add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}

This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.

Remember to flush your rewrite rules after adding/modifying this.

Background color for Tk in Python

widget['bg'] = '#000000'

or

widget['background'] = '#000000'

would also work as hex-valued colors are also accepted.

How to load npm modules in AWS Lambda?

You can now use Lambda Layers for this matters. Simply add a layer containing the package you need and it will run perfectly.

Follow this post: https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

Hook up Raspberry Pi via Ethernet to laptop without router?

You could use a cross-over ethernet cable - http://en.wikipedia.org/wiki/Ethernet_crossover_cable

Assuming your RPi is a DCHP Client, then best to run a simple DHCP server on your notebook to assign the RPi an IP address.

Pretty-Print JSON Data to a File using Python

You should use the optional argument indent.

header, output = client.request(twitterRequest, method="GET", body=None,
                            headers=None, force_auth_header=True)

# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()

Vuejs and Vue.set(), update array

As stated before - VueJS simply can't track those operations(array elements assignment). All operations that are tracked by VueJS with array are here. But I'll copy them once again:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

During development, you face a problem - how to live with that :).

push(), pop(), shift(), unshift(), sort() and reverse() are pretty plain and help you in some cases but the main focus lies within the splice(), which allows you effectively modify the array that would be tracked by VueJs. So I can share some of the approaches, that are used the most working with arrays.

You need to replace Item in Array:

// note - findIndex might be replaced with some(), filter(), forEach() 
// or any other function/approach if you need 
// additional browser support, or you might use a polyfill
const index = this.values.findIndex(item => {
          return (replacementItem.id === item.id)
        })
this.values.splice(index, 1, replacementItem)

Note: if you just need to modify an item field - you can do it just by:

this.values[index].itemField = newItemFieldValue

And this would be tracked by VueJS as the item(Object) fields would be tracked.

You need to empty the array:

this.values.splice(0, this.values.length)

Actually you can do much more with this function splice() - w3schools link You can add multiple records, delete multiple records, etc.

Vue.set() and Vue.delete()

Vue.set() and Vue.delete() might be used for adding field to your UI version of data. For example, you need some additional calculated data or flags within your objects. You can do this for your objects, or list of objects(in the loop):

 Vue.set(plan, 'editEnabled', true) //(or this.$set)

And send edited data back to the back-end in the same format doing this before the Axios call:

 Vue.delete(plan, 'editEnabled') //(or this.$delete)

How many socket connections possible?

A limit on the number of open sockets is configurable in the /proc file system

cat /proc/sys/fs/file-max

Max for incoming connections in the OS defined by integer limits.

Linux itself allows billions of open sockets.

To use the sockets you need an application listening, e.g. a web server, and that will use a certain amount of RAM per socket.

RAM and CPU will introduce the real limits. (modern 2017, think millions not billions)

1 millions is possible, not easy. Expect to use X Gigabytes of RAM to manage 1 million sockets.

Outgoing TCP connections are limited by port numbers ~65000 per IP. You can have multiple IP addresses, but not unlimited IP addresses. This is a limit in TCP not Linux.

Loading/Downloading image from URL on Swift

Swift 2 with error Handle and custom request header

Simply add extension to UIImageView:

extension UIImageView {
    public func imageFromUrl(urlString: String) {
        if let url = NSURL(string: urlString) {
            let request = NSMutableURLRequest(URL: url)
            request.setValue("<YOUR_HEADER_VALUE>", forHTTPHeaderField: "<YOUR_HEADER_KEY>")
            NSURLSession.sharedSession().dataTaskWithRequest(request) {
                (data, response, error) in
                guard let data = data where error == nil else{
                    NSLog("Image download error: \(error)")
                    return
                }

                if let httpResponse = response as? NSHTTPURLResponse{
                    if httpResponse.statusCode > 400 {
                        let errorMsg = NSString(data: data, encoding: NSUTF8StringEncoding)
                        NSLog("Image download error, statusCode: \(httpResponse.statusCode), error: \(errorMsg!)")
                        return
                    }
                }

            dispatch_async(dispatch_get_main_queue(), {
                NSLog("Image download success")
                self.image = UIImage(data: data)
            })
            }.resume()
        }
    }
}

And then, use the new imageFromUrl(urlString: String) to download image

Usage:

imageView.imageFromUrl("https://i.imgur.com/ONaprQV.png")

How merge two objects array in angularjs?

Simple

var a=[{a:4}], b=[{b:5}]

angular.merge(a,b) // [{a:4, b:5}]

Tested on angular 1.4.1

Any implementation of Ordered Set in Java?

Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.

You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.

Also, you can't insert at a certain position.

Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.

Get user input from textarea

<pre>
  <input type="text"  #titleInput>
  <button type="submit" (click) = 'addTodo(titleInput.value)'>Add</button>
</pre>

{
  addTodo(title:string) {
    console.log(title);
  }
}    

How do you get the Git repository's name in some Git repository?

I think this is a better way to unambiguously identify a clone of a repository.

git config --get remote.origin.url and checking to make sure that the origin matches ssh://your/repo.

Initializing a dictionary in python with a key value and no corresponding values

It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.

1) If you want to count the number of occurrences of keys, you can just do:

Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1

2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:

Definition.get(key)  # returns None if key not stored
Definition.get(key, default_other_than_none)

3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.

For example, if you only want to store values for those keys:

expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
    Definition[key_found] = value

Or if you want to make sure all expected keys were found:

assert(all(key in Definition for key in expected_keys))

Save plot to image file instead of displaying it using Matplotlib

I used the following:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png

How do I change the android actionbar title and icon

The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle().

To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.

Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon in your manifest's application or activity element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png, and place it in your drawable-* directories.

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

Using jQuery to test if an input has focus

Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

How to read the output from git diff?

On my mac:

info diff then select: Output formats -> Context -> Unified format -> Detailed Unified :

Or online man diff on gnu following the same path to the same section:

File: diff.info, Node: Detailed Unified, Next: Example Unified, Up: Unified Format

Detailed Description of Unified Format ......................................

The unified output format starts with a two-line header, which looks like this:

 --- FROM-FILE FROM-FILE-MODIFICATION-TIME
 +++ TO-FILE TO-FILE-MODIFICATION-TIME

The time stamp looks like `2002-02-21 23:30:39.942229878 -0800' to indicate the date, time with fractional seconds, and time zone.

You can change the header's content with the `--label=LABEL' option; see *Note Alternate Names::.

Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:

 @@ FROM-FILE-RANGE TO-FILE-RANGE @@
  LINE-FROM-EITHER-FILE
  LINE-FROM-EITHER-FILE...

The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:

`+' A line was added here to the first file.

`-' A line was removed here from the first file.

How do you determine the size of a file in C?

Here's a simple and clean function that returns the file size.

long get_file_size(char *path)
{
    FILE *fp;
    long size = -1;
    /* Open file for reading */
    fp = fopen(path, "r");
    fseek(fp, 0, SEEK_END);
    size = ftell(fp); 
    fp.close();
    return 
}

How to generate .env file for laravel?

In windows OS, you can open command prompt, change directory to your project directory.
Example,
My project directory

E:\xampp\htdocs\my_project


You can type into your Command prompt like this (hit enter each line):

E:

cd xampp\htdocs\my_project

Then you can type,

copy .env.example .env

If you are using Linux, you can type cp, instead of copy

C# Macro definitions in Preprocessor

I would suggest you to write extension, something like below.

public static class WriteToConsoleExtension
{
   // Extension to all types
   public static void WriteToConsole(this object instance, 
                                     string format, 
                                     params object[] data)
   {
       Console.WriteLine(format, data);
   }
}

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        // Usage of extension
        p.WriteToConsole("Test {0}, {1}", DateTime.Now, 1);
    }
}

Hope this helps (and not too late :) )

A CSS selector to get last visible div

The real answer to this question is, you can't do it. Alternatives to CSS-only answers are not correct answers to this question, but if JS solutions are acceptable to you, then you should pick one of the JS or jQuery answers here. However, as I said above, the true, correct answer is that you cannot do this in CSS reliably unless you're willing to accept the :not operator with the [style*=display:none] and other such negated selectors, which only works on inline styles, and is an overall poor solution.

In DB2 Display a table's definition

Try the following:

DESCRIBE SELECT * FROM TABLE_name

Python logging not outputting anything

Maybe try this? It seems the problem is solved after remove all the handlers in my case.

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

logging.basicConfig(filename='output.log', level=logging.INFO)

How to reload current page?

It will work 100%. The following lines of code are responsible for page reload in my project.

load(val) {
if (val == this.router.url) {
  this.spinnerService.show();
  this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };
 }
}

Just use the following part in your code.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };

How to avoid HTTP error 429 (Too Many Requests) python

if response.status_code == 429:
  time.sleep(int(response.headers["Retry-After"]))

How to redirect both stdout and stderr to a file

Use:

command >>log_file 2>>log_file

Why do I get "'property cannot be assigned" when sending an SMTP email?

smtp.Host = "smtp.gmail.com"; // the host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;

Go through this article for more details

Output to the same line overwriting previous output?

If all you want to do is change a single line, use \r. \r means carriage return. It's effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly, \b can be used to go one character backward. (some terminals may not support all those features)

import sys

def process(data):
    size_str = os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
    sys.stdout.write('%s\r' % size_str)
    sys.stdout.flush()
    file.write(data)

React Native add bold or italics to single words in <Text> field

<Text>
    <Text style={{fontWeight: "bold"}}>bold</Text>
    normal text
    <Text style={{fontStyle: "italic"}}> italic</Text>
</Text>

Xcode 6 iPhone Simulator Application Support location

The simulator directory has been moved with Xcode 6 beta to...

~/Library/Developer/CoreSimulator

Browsing the directory to your app's Documents folder is a bit more arduous, e.g.,

~/Library/Developer/CoreSimulator/Devices/4D2D127A-7103-41B2-872B-2DB891B978A2/data/Containers/Data/Application/0323215C-2B91-47F7-BE81-EB24B4DA7339/Documents/MyApp.sqlite

TypeError: Router.use() requires middleware function but got a Object

In any one of your js pages you are missing

module.exports = router;

Check and verify all your JS pages

What are the alternatives now that the Google web search API has been deprecated?

There's a note on top of the docs:

Note: The Google Web Search API has been officially deprecated as of November 1, 2010. It will continue to work as per our deprecation policy, but the number of requests you may make per day will be limited. Therefore, we encourage you to move to the new Custom Search API.

The deprecation policy says that they will continue to run the API for 3 years. So if you already have an application that uses the old API, you don't have to rush to change things just yet. If you're writing a new application, use the Custom Search API. See my answer here for how to do this in Python, but the idea's the same for any language.

How to copy data from one HDFS to another HDFS?

It's also useful to note that you can run the underlying MapReduce jobs with either the source or target cluster like so:

hadoop --config /path/to/hadoop/config distcp <src> <dst>

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

-didSelectRowAtIndexPath: not being called

If your table view is in editing mode (eg. [tableView setEditing:YES animated:NO];), you need to set tableView.allowsSelectionDuringEditing = YES;

System.Drawing.Image to stream C#

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

What is difference between Lightsail and EC2?

Lightsail VPSs are bundles of existing AWS products, offered through a significantly simplified interface. The difference is that Lightsail offers you a limited and fixed menu of options but with much greater ease of use. Other than the narrower scope of Lightsail in order to meet the requirements for simplicity and low cost, the underlying technology is the same.

The pre-defined bundles can be described:

% aws lightsail --region us-east-1 get-bundles
{
    "bundles": [
        {
            "name": "Nano",
            "power": 300,
            "price": 5.0,
            "ramSizeInGb": 0.5,
            "diskSizeInGb": 20,
            "transferPerMonthInGb": 1000,
            "cpuCount": 1,
            "instanceType": "t2.nano",
            "isActive": true,
            "bundleId": "nano_1_0"
        },
        ...
    ]
}

It's worth reading through the Amazon EC2 T2 Instances documentation, particularly the CPU Credits section which describes the base and burst performance characteristics of the underlying instances.

Importantly, since your Lightsail instances run in VPC, you still have access to the full spectrum of AWS services, e.g. S3, RDS, and so on, as you would from any EC2 instance.

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Converting from signed char to unsigned char and back again?

There are two ways to interpret the input data; either -128 is the lowest value, and 127 is the highest (i.e. true signed data), or 0 is the lowest value, 127 is somewhere in the middle, and the next "higher" number is -128, with -1 being the "highest" value (that is, the most significant bit already got misinterpreted as a sign bit in a two's complement notation.

Assuming you mean the latter, the formally correct way is

signed char in = ...
unsigned char out = (in < 0)?(in + 256):in;

which at least gcc properly recognizes as a no-op.

How to get absolute path to file in /resources folder of your project

You can use ClassLoader.getResource method to get the correct resource.

URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();

OR

Although this may not work all the time, a simpler solution -

You can create a File object and use getAbsolutePath method:

File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();

How can I access a hover state in reactjs?

ReactJs defines the following synthetic events for mouse events:

onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp

As you can see there is no hover event, because browsers do not define a hover event natively.

You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.

ReactJS Docs - Events

What is better, adjacency lists or adjacency matrices for graph problems in C++?

To add to keyser5053's answer about memory usage.

For any directed graph, an adjacency matrix (at 1 bit per edge) consumes n^2 * (1) bits of memory.

For a complete graph, an adjacency list (with 64 bit pointers) consumes n * (n * 64) bits of memory, excluding list overhead.

For an incomplete graph, an adjacency list consumes 0 bits of memory, excluding list overhead.


For an adjacency list, you can use the follow formula to determine the maximum number of edges (e) before an adjacency matrix is optimal for memory.

edges = n^2 / s to determine the maximum number of edges, where s is the pointer size of the platform.

If you're graph is dynamically updating, you can maintain this efficiency with an average edge count (per node) of n / s.


Some examples with 64 bit pointers and dynamic graph (A dynamic graph updates the solution of a problem efficiently after changes, rather than recomputing it from scratch each time after a change has been made.)

For a directed graph, where n is 300, the optimal number of edges per node using an adjacency list is:

= 300 / 64
= 4

If we plug this into keyser5053's formula, d = e / n^2 (where e is the total edge count), we can see we are below the break point (1 / s):

d = (4 * 300) / (300 * 300)
d < 1/64
aka 0.0133 < 0.0156

However, 64 bits for a pointer can be overkill. If you instead use 16bit integers as pointer offsets, we can fit up to 18 edges before breaking point.

= 300 / 16
= 18

d = ((18 * 300) / (300^2))
d < 1/16
aka 0.06 < 0.0625

Each of these examples ignore the overhead of the adjacency lists themselves (64*2 for a vector and 64 bit pointers).

Java heap terminology: young, old and permanent generations?

Memory in SunHotSpot JVM is organized into three generations: young generation, old generation and permanent generation.

  • Young Generation : the newly created objects are allocated to the young gen.
  • Old Generation : If the new object requests for a larger heap space, it gets allocated directly into the old gen. Also objects which have survived a few GC cycles gets promoted to the old gen i.e long lived objects house in old gen.
  • Permanent Generation : The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

FYI: The permanent gen is not considered a part of the Java heap.

How does the three generations interact/relate to each other? Objects(except the large ones) are first allocated to the young generation. If an object remain alive after x no. of garbage collection cycles it gets promoted to the old/tenured gen. Hence we can say that the young gen contains the short lived objects while the old gen contains the objects having a long life. The permanent gen does not interact with the other two generations.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

Get most recent row for given ID

SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Update for 2016

A lot of great editors have come out since my original answer. I currently use the following text editors: Sublime Text 3 (Mac/Windows), Visual Studio Code (Mac/Windows) and Atom (Mac/Windows). I also use the following IDEs: Visual Studio 2015 (Windows/Paid & Free Versions) and Jetrbrains WebStorm (Windows/Paid, tried the demo and liked it).

My preference is using Sublime Text 3.

Original Answer

Microsoft Web Matrix and Dreamweaver are great.

Visual Studio and Expression Web are also great but may be overkill for you.

For just plain text editors, Sublime Text 2 is really cool

Java, How to specify absolute value and square roots

import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

Is Python strongly typed?

I just discovered a superb concise way to memorize it:

Dynamic/static typed experssion; strongly/weakly typed value.

Using the "animated circle" in an ImageView while loading stuff

You can do this by using the following xml

<RelativeLayout
    style="@style/GenericProgressBackground"
    android:id="@+id/loadingPanel"
    >
    <ProgressBar
        style="@style/GenericProgressIndicator"/>
</RelativeLayout>

With this style

<style name="GenericProgressBackground" parent="android:Theme">
    <item name="android:layout_width">fill_parent</item>    
    <item name="android:layout_height">fill_parent</item>
    <item name="android:background">#DD111111</item>    
    <item name="android:gravity">center</item>  
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:indeterminate">true</item> 
</style>

To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE) on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE) to hide the loading animation.

If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.

How to make for loops in Java increase by increments other than 1

for(j = 0; j<=90; j = j+3)
{

}

j+3 will not assign the new value to j, add j=j+3 will assign the new value to j and the loop will move up by 3.

j++ is like saying j = j+1, so in that case your assigning the new value to j just like the one above.

How can I delete a file from a Git repository?

First, if you are using git rm, especially for multiple files, consider any wildcard will be resolved by the shell, not by the git command.

git rm -- *.anExtension
git commit -m "remove multiple files"

But, if your file is already on GitHub, you can (since July 2013) directly delete it from the web GUI!

Simply view any file in your repository, click the trash can icon at the top, and commit the removal just like any other web-based edit.

Then "git pull" on your local repo, and that will delete the file locally too.
Which makes this answer a (roundabout) way to delete a file from git repo?
(Not to mention that a file on GitHub is in a "git repo")


delete button

(the commit will reflect the deletion of that file):

commit a deletion

And just like that, it’s gone.

For help with these features, be sure to read our help articles on creating, moving, renaming, and deleting files.

Note: Since it’s a version control system, Git always has your back if you need to recover the file later.

The last sentence means that the deleted file is still part of the history, and you can restore it easily enough (but not yet through the GitHub web interface):

See "Restore a deleted file in a Git repo".

How do I get the current username in Windows PowerShell?

If you're used to batch, you can call

$user=$(cmd.exe /c echo %username%)

This basically steals the output from what you would get if you had a batch file with just "echo %username%".

Module not found: Error: Can't resolve 'core-js/es6'

The imports have changed for core-js version 3.0.1 - for example

import 'core-js/es6/array'; and import 'core-js/es7/array';

can now be provided simply by the following

import 'core-js/es/array';

if you would prefer not to bring in the whole of core-js

How to git reset --hard a subdirectory?

According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:

git checkout -- a

(where a is the directory you want to hard-reset). The original behavior can be accessed via

git checkout --ignore-skip-worktree-bits -- a

.trim() in JavaScript not working in IE

Add the following code to add trim functionality to the string.

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Initialize Array of Objects using NSArray

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

[persons addObject:[[[Person alloc] init] autorelease];

CKEditor, Image Upload (filebrowserUploadUrl)

May be it's too late. Your code is correct so please check again your url in filebrowserUploadUrl

CKEDITOR.replace( 'editor1', {
    filebrowserUploadUrl: "upload/upload.php" 
} );

And the Upload.php file

if (file_exists("images/" . $_FILES["upload"]["name"]))
{
 echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
 move_uploaded_file($_FILES["upload"]["tmp_name"],
 "images/" . $_FILES["upload"]["name"]);
 echo "Stored in: " . "images/" . $_FILES["upload"]["name"];
}

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

I've found the answer regarding how to do this myself. Inside the model code, just put:

For Rails <= 2:

include ActionController::UrlWriter

For Rails 3:

include Rails.application.routes.url_helpers

This magically makes thing_path(self) return the URL for the current thing, or other_model_path(self.association_to_other_model) return some other URL.

Is there a cross-domain iframe height auto-resizer that works?

I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.

  1. Suppose you have added iframe in "abc.com/page" web page

    <div> <iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe> </div>

  2. Next you have to bind windows "message" event under web page "abc.com/page"

window.addEventListener('message', function (event) {
//Here We have to check content of the message event  for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
        //Set height of the Iframe
        $("#IframeId").css("height", event.data.FrameHeight);        
    }
});

On iframe load you have to send message to iframe window content with "FrameHeight" message:

function setIframeHeight(ifrm) {
   var height = ifrm.contentWindow.postMessage("FrameHeight", "*");   
}
  1. On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
window.addEventListener('message', function (event) {

    // Need to check for safety as we are going to process only our messages
    // So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
   if (event.data == "FrameHeight") {

        //event.source contains parent page window object 
        //which we are going to use to send message back to main page here "abc.com/page"

        //parentSourceWindow = event.source;

        //Calculate the maximum height of the page
        var body = document.body, html = document.documentElement;
        var height = Math.max(body.scrollHeight, body.offsetHeight,
            html.clientHeight, html.scrollHeight, html.offsetHeight);

       // Send height back to parent page "abc.com/page"
        event.source.postMessage({ "FrameHeight": height }, "*");       
    }
});

What properties can I use with event.target?

event.target returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve nodeName, and you can retrieve href and id, provided the element has a href and id defined; otherwise undefined will be returned.

However, inside an event handler, you can use this, which is set to the DOM element as well; much easier.

$('foo').bind('click', function () {
    // inside here, `this` will refer to the foo that was clicked
});

Sequence Permission in Oracle

To grant a permission:

grant select on schema_name.sequence_name to user_or_role_name;

To check which permissions have been granted

select * from all_tab_privs where TABLE_NAME = 'sequence_name'

mongodb group values by multiple fields

TLDR Summary

In modern MongoDB releases you can brute force this with $slice just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push to an array.

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$project": {
        "books": { "$slice": [ "$books", 2 ] },
        "count": 1
    }}
])

MongoDB 3.6 Preview

Still not resolving SERVER-9377, but in this release $lookup allows a new "non-correlated" option which takes an "pipeline" expression as an argument instead of the "localFields" and "foreignFields" options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit in order to return the "top-n" results.

db.books.aggregate([
  { "$group": {
    "_id": "$addr",
    "count": { "$sum": 1 }
  }},
  { "$sort": { "count": -1 } },
  { "$limit": 2 },
  { "$lookup": {
    "from": "books",
    "let": {
      "addr": "$_id"
    },
    "pipeline": [
      { "$match": { 
        "$expr": { "$eq": [ "$addr", "$$addr"] }
      }},
      { "$group": {
        "_id": "$book",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1  } },
      { "$limit": 2 }
    ],
    "as": "books"
  }}
])

The other addition here is of course the ability to interpolate the variable through $expr using $match to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit each result separately.

This would be the next best option to running parallel queries, and actually would be better if the $match were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push" as the referenced issue asks, it actually delivers something that should work better.


Original Content

You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 }
])

Now that will give you a result like this:

{
    "result" : [
            {
                    "_id" : "address1",
                    "books" : [
                            {
                                    "book" : "book4",
                                    "count" : 1
                            },
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 3
                            }
                    ],
                    "count" : 5
            },
            {
                    "_id" : "address2",
                    "books" : [
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 2
                            }
                    ],
                    "count" : 3
            }
    ],
    "ok" : 1
}

So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.

This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$unwind": "$books" },
    { "$sort": { "count": 1, "books.count": -1 } },
    { "$group": {
        "_id": "$_id",
        "books": { "$push": "$books" },
        "count": { "$first": "$count" }
    }},
    { "$project": {
        "_id": {
            "_id": "$_id",
            "books": "$books",
            "count": "$count"
        },
        "newBooks": "$books"
    }},
    { "$unwind": "$newBooks" },
    { "$group": {
      "_id": "$_id",
      "num1": { "$first": "$newBooks" }
    }},
    { "$project": {
        "_id": "$_id",
        "newBooks": "$_id.books",
        "num1": 1
    }},
    { "$unwind": "$newBooks" },
    { "$project": {
        "_id": "$_id",
        "num1": 1,
        "newBooks": 1,
        "seen": { "$eq": [
            "$num1",
            "$newBooks"
        ]}
    }},
    { "$match": { "seen": false } },
    { "$group":{
        "_id": "$_id._id",
        "num1": { "$first": "$num1" },
        "num2": { "$first": "$newBooks" },
        "count": { "$first": "$_id.count" }
    }},
    { "$project": {
        "num1": 1,
        "num2": 1,
        "count": 1,
        "type": { "$cond": [ 1, [true,false],0 ] }
    }},
    { "$unwind": "$type" },
    { "$project": {
        "books": { "$cond": [
            "$type",
            "$num1",
            "$num2"
        ]},
        "count": 1
    }},
    { "$group": {
        "_id": "$_id",
        "count": { "$first": "$count" },
        "books": { "$push": "$books" }
    }},
    { "$sort": { "count": -1 } }
])

So that will actually give you the top 2 "books" from the top two "address" entries.

But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.


Demonstration Code

The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.

index.js

const { MongoClient } = require('mongodb');
const fs = require('mz/fs');

const uri = 'mongodb://localhost:27017';

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {
    const client = await MongoClient.connect(uri);

    const db = client.db('bookDemo');
    const books = db.collection('books');

    let { version } = await db.command({ buildInfo: 1 });
    version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);

    // Clear and load books
    await books.deleteMany({});

    await books.insertMany(
      (await fs.readFile('books.json'))
        .toString()
        .replace(/\n$/,"")
        .split("\n")
        .map(JSON.parse)
    );

    if ( version >= 3.6 ) {

    // Non-correlated pipeline with limits
      let result = await books.aggregate([
        { "$group": {
          "_id": "$addr",
          "count": { "$sum": 1 }
        }},
        { "$sort": { "count": -1 } },
        { "$limit": 2 },
        { "$lookup": {
          "from": "books",
          "as": "books",
          "let": { "addr": "$_id" },
          "pipeline": [
            { "$match": {
              "$expr": { "$eq": [ "$addr", "$$addr" ] }
            }},
            { "$group": {
              "_id": "$book",
              "count": { "$sum": 1 },
            }},
            { "$sort": { "count": -1 } },
            { "$limit": 2 }
          ]
        }}
      ]).toArray();

      log({ result });
    }

    // Serial result procesing with parallel fetch

    // First get top addr items
    let topaddr = await books.aggregate([
      { "$group": {
        "_id": "$addr",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1 } },
      { "$limit": 2 }
    ]).toArray();

    // Run parallel top books for each addr
    let topbooks = await Promise.all(
      topaddr.map(({ _id: addr }) =>
        books.aggregate([
          { "$match": { addr } },
          { "$group": {
            "_id": "$book",
            "count": { "$sum": 1 }
          }},
          { "$sort": { "count": -1 } },
          { "$limit": 2 }
        ]).toArray()
      )
    );

    // Merge output
    topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
    log({ topaddr });

    client.close();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

books.json

{ "addr": "address1",  "book": "book1"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book5"  }
{ "addr": "address3",  "book": "book9"  }
{ "addr": "address2",  "book": "book5"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book1"  }
{ "addr": "address15", "book": "book1"  }
{ "addr": "address9",  "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4",  "book": "book3"  }
{ "addr": "address5",  "book": "book1"  }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1",  "book": "book1"  }

How to create a jQuery plugin with methods?

What about using triggers? Does anyone know any drawback using them? The benefit is that all internal variables are accessible via the triggers, and the code is very simple.

See on jsfiddle.

Example usage

<div id="mydiv">This is the message container...</div>

<script>
    var mp = $("#mydiv").messagePlugin();

    // the plugin returns the element it is called on
    mp.trigger("messagePlugin.saySomething", "hello");

    // so defining the mp variable is not needed...
    $("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>

Plugin

jQuery.fn.messagePlugin = function() {

    return this.each(function() {

        var lastmessage,
            $this = $(this);

        $this.on('messagePlugin.saySomething', function(e, message) {
            lastmessage = message;
            saySomething(message);
        });

        $this.on('messagePlugin.repeatLastMessage', function(e) {
            repeatLastMessage();
        });

        function saySomething(message) {
            $this.html("<p>" + message + "</p>");
        }

        function repeatLastMessage() {
            $this.append('<p>Last message was: ' + lastmessage + '</p>');
        }

    });

}

Pagination on a list using ng-repeat

Check out this directive: https://github.com/samu/angular-table

It automates sorting and pagination a lot and gives you enough freedom to customize your table/list however you want.

JQuery Ajax Post results in 500 Internal Server Error

Use a Try Catch block on your server side and in the catch block pass back the exception error to the client. This should give you a helpful error message.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

To add ANDROID_HOME value permanently,

gedit ~/.bashrc

and add the following lines

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools

Save the file and you need not update ANDROID_HOME value everytime.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

There's a great article on Mozilla's MDN docs that describes exactly this issue:

The "Unicode Problem" Since DOMStrings are 16-bit-encoded strings, in most browsers calling window.btoa on a Unicode string will cause a Character Out Of Range exception if a character exceeds the range of a 8-bit byte (0x00~0xFF). There are two possible methods to solve this problem:

  • the first one is to escape the whole string (with UTF-8, see encodeURIComponent) and then encode it;
  • the second one is to convert the UTF-16 DOMString to an UTF-8 array of characters and then encode it.

A note on previous solutions: the MDN article originally suggested using unescape and escape to solve the Character Out Of Range exception problem, but they have since been deprecated. Some other answers here have suggested working around this with decodeURIComponent and encodeURIComponent, this has proven to be unreliable and unpredictable. The most recent update to this answer uses modern JavaScript functions to improve speed and modernize code.

If you're trying to save yourself some time, you could also consider using a library:

Encoding UTF8 ? base64

function b64EncodeUnicode(str) {
    // first we use encodeURIComponent to get percent-encoded UTF-8,
    // then we convert the percent encodings into raw bytes which
    // can be fed into btoa.
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
            return String.fromCharCode('0x' + p1);
    }));
}

b64EncodeUnicode('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="

Decoding base64 ? UTF8

function b64DecodeUnicode(str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
b64DecodeUnicode('Cg=='); // "\n"

The pre-2018 solution (functional, and though likely better support for older browsers, not up to date)

Here is the the current recommendation, direct from MDN, with some additional TypeScript compatibility via @MA-Maddin:

// Encoding UTF8 ? base64

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    }))
}

b64EncodeUnicode('? à la mode') // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n') // "Cg=="

// Decoding base64 ? UTF8

function b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
}

b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU=') // "? à la mode"
b64DecodeUnicode('Cg==') // "\n"

The original solution (deprecated)

This used escape and unescape (which are now deprecated, though this still works in all modern browsers):

function utf8_to_b64( str ) {
    return window.btoa(unescape(encodeURIComponent( str )));
}

function b64_to_utf8( str ) {
    return decodeURIComponent(escape(window.atob( str )));
}

// Usage:
utf8_to_b64('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"

And one last thing: I first encountered this problem when calling the GitHub API. To get this to work on (Mobile) Safari properly, I actually had to strip all white space from the base64 source before I could even decode the source. Whether or not this is still relevant in 2017, I don't know:

function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(escape(window.atob( str )));
}

Button background as transparent

You can do it easily by adding below attribute in xml file. This code was tested plenty of time.

android:background="@android:color/transparent"

Generate random integers between 0 and 9

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

Clear form fields with jQuery

I use this :

$(".reset").click(function() {
  $('input[type=text]').each(function(){
     $(this).val('');
  });
});

And here is my button:

<a href="#" class="reset">
  <i class="fa fa-close"></i>
     Reset
</a>

Are there any style options for the HTML5 Date picker?

I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...

I am using styled-components to render a transparent date picker input as shown in the image below:

image of date picker input

const StyledInput = styled.input`
  appearance: none;
  box-sizing: border-box;
  border: 1px solid black;
  background: transparent;
  font-size: 1.5rem;
  padding: 8px;
  ::-webkit-datetime-edit-text { padding: 0 2rem; }
  ::-webkit-datetime-edit-month-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-day-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-year-field { text-transform: uppercase; }
  ::-webkit-inner-spin-button { display: none; }
  ::-webkit-calendar-picker-indicator { background: transparent;}
`

Google Maps API - Get Coordinates of address

Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps

https://nominatim.openstreetmap.org/search?q=Mumbai&format=json

Here is the API documentation for reference.

Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.

Load CSV file with Spark

If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.

I am also new to Pyspark and trying to read CSV file. Following code worked for me:

In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data

1. Without mentioning the schema:

from pyspark.sql import SparkSession  
scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()

Now check the columns: sdfData.columns

Output will be:

['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']

Check the datatype for each column:

sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))

This will give the data frame with all the columns with datatype as StringType

2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)

from pyspark.sql import SparkSession  
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
    schema = StructType([\
        StructField("InvoiceNo", IntegerType()),\
        StructField("StockCode", StringType()), \
        StructField("Description", StringType()),\
        StructField("Quantity", IntegerType()),\
        StructField("InvoiceDate", StringType()),\
        StructField("CustomerID", DoubleType()),\
        StructField("Country", StringType())\
    ])

scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL example: Reading CSV file with schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)

Now check the schema for datatype of each column:

sdfData.schema

StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))

Edited: We can use the following line of code as well without mentioning schema explicitly:

sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema

The output is:

StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))

The output will look like this:

sdfData.show()

+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode|         Description|Quantity|   InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
|   536365|   85123A|WHITE HANGING HEA...|       6|12/1/2010 8:26|      2.55|  17850|
|   536365|    71053| WHITE METAL LANTERN|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84406B|CREAM CUPID HEART...|       8|12/1/2010 8:26|      2.75|  17850|
|   536365|   84029G|KNITTED UNION FLA...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84029E|RED WOOLLY HOTTIE...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|    22752|SET 7 BABUSHKA NE...|       2|12/1/2010 8:26|      7.65|  17850|
|   536365|    21730|GLASS STAR FROSTE...|       6|12/1/2010 8:26|      4.25|  17850|
|   536366|    22633|HAND WARMER UNION...|       6|12/1/2010 8:28|      1.85|  17850|
|   536366|    22632|HAND WARMER RED P...|       6|12/1/2010 8:28|      1.85|  17850|
|   536367|    84879|ASSORTED COLOUR B...|      32|12/1/2010 8:34|      1.69|  13047|
|   536367|    22745|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22748|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22749|FELTCRAFT PRINCES...|       8|12/1/2010 8:34|      3.75|  13047|
|   536367|    22310|IVORY KNITTED MUG...|       6|12/1/2010 8:34|      1.65|  13047|
|   536367|    84969|BOX OF 6 ASSORTED...|       6|12/1/2010 8:34|      4.25|  13047|
|   536367|    22623|BOX OF VINTAGE JI...|       3|12/1/2010 8:34|      4.95|  13047|
|   536367|    22622|BOX OF VINTAGE AL...|       2|12/1/2010 8:34|      9.95|  13047|
|   536367|    21754|HOME BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21755|LOVE BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21777|RECIPE BOX WITH M...|       4|12/1/2010 8:34|      7.95|  13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows

Server certificate verification failed: issuer is not trusted

from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

Check if a string contains an element from a list (of strings)

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

If you were testing equality, it would be worth looking at HashSet etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.


update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use Array.BinarySearch to find each item - check by lookup to see if it is a full or partial match.

Execute CMD command from code

Using Process.Start:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("example.txt");
    }
}

How to call a VbScript from a Batch File without opening an additional command prompt

rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"

OR

rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"

You can also add the option //e:vbscript to make sure the scripting engine will recognize your script as a vbscript.

Windows/DOS batch files doesn't require escaping \ like *nix.

You can still use "C:\Users\guest\Desktop\123\MyScript.vbs", but this requires the user has *.vbs associated to wscript.

Difference between INNER JOIN and LEFT SEMI JOIN

Tried in Hive and got the below output

table1

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

4,yepie,newyork,USA

table2

1,wqe,chennai,india

2,stu,salem,india

3,mia,bangalore,india

5,chapie,Los angels,USA

Inner Join

SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

Left Join

SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india 1 wqe chennai india

2 stu salem india 2 stu salem india

3 mia bangalore india 3 mia bangalore india

4 yepie newyork USA NULL NULL NULL NULL

Left Semi Join

SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);

1 wqe chennai india

2 stu salem india

3 mia bangalore india

note: Only records in left table are displayed whereas for Left Join both the table records displayed

Passing structs to functions

First, the signature of your data() function:

bool data(struct *sampleData)

cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:

bool data(struct sampleData *samples)

But in C++, you don't need to use struct at all actually. So this can simply become:

bool data(sampleData *samples)

Second, the sampleData struct is not known to data() at that point. So you should declare it before that:

struct sampleData {
    int N;
    int M;
    string sample_name;
    string speaker;
};

bool data(sampleData *samples)
{
    samples->N = 10;
    samples->M = 20;
    // etc.
}

And finally, you need to create a variable of type sampleData. For example, in your main() function:

int main(int argc, char *argv[]) {
    sampleData samples;
    data(&samples);
}

Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.

However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:

// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
    samples.N = 10;
    samples.M = 20;
    // etc.
}

int main(int argc, char *argv[]) {
    sampleData samples;

    // No need to pass a pointer here, since data() takes the
    // passed argument by reference.
    data(samples);
}

jQuery remove selected option from this

This is a simpler one

$('#some_select_box').find('option:selected').remove().end();

how to remove key+value from hash in javascript

Why do you use new Array(); for hash? You need to use new Object() instead.

And i think you will get what you want.

Notepad++ add to every line

Notepad++ has a very powerful editing capability. (Today I'm searching for the similar function in Sublime Text), but for Notepad++, just hold Alt when you drag the mouse. What you type will then replace the selected column on every line. To insert without replacing existing text, use Alt-Shift.

enter image description here

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

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Compare dates with javascript

you can done this way also.

if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {
        console.log("done");
}

OR

if (dateFormat(first, "mm-dd-yyyy") >  dateFormat(second, "mm-dd-yyyy")) {
        console.log("done");
}

i use following plugin for dateFormat()

        var dateFormat = function () {
        var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
            timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
            timezoneClip = /[^-+\dA-Z]/g,
            pad = function (val, len) {
                val = String(val);
                len = len || 2;
                while (val.length < len) val = "0" + val;
                return val;
            };

        // Regexes and supporting functions are cached through closure
        return function (date, mask, utc) {
            var dF = dateFormat;

            // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
            if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                mask = date;
                date = undefined;
            }

            // Passing date through Date applies Date.parse, if necessary
            date = date ? new Date(date) : new Date;
            if (isNaN(date)) throw SyntaxError("invalid date");

            mask = String(dF.masks[mask] || mask || dF.masks["default"]);

            // Allow setting the utc argument via the mask
            if (mask.slice(0, 4) == "UTC:") {
                mask = mask.slice(4);
                utc = true;
            }

            var _ = utc ? "getUTC" : "get",
                d = date[_ + "Date"](),
                D = date[_ + "Day"](),
                m = date[_ + "Month"](),
                y = date[_ + "FullYear"](),
                H = date[_ + "Hours"](),
                M = date[_ + "Minutes"](),
                s = date[_ + "Seconds"](),
                L = date[_ + "Milliseconds"](),
                o = utc ? 0 : date.getTimezoneOffset(),
                flags = {
                    d:    d,
                    dd:   pad(d),
                    ddd:  dF.i18n.dayNames[D],
                    dddd: dF.i18n.dayNames[D + 7],
                    m:    m + 1,
                    mm:   pad(m + 1),
                    mmm:  dF.i18n.monthNames[m],
                    mmmm: dF.i18n.monthNames[m + 12],
                    yy:   String(y).slice(2),
                    yyyy: y,
                    h:    H % 12 || 12,
                    hh:   pad(H % 12 || 12),
                    H:    H,
                    HH:   pad(H),
                    M:    M,
                    MM:   pad(M),
                    s:    s,
                    ss:   pad(s),
                    l:    pad(L, 3),
                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                    t:    H < 12 ? "a"  : "p",
                    tt:   H < 12 ? "am" : "pm",
                    T:    H < 12 ? "A"  : "P",
                    TT:   H < 12 ? "AM" : "PM",
                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                };

            return mask.replace(token, function ($0) {
                return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
            });
        };
    }();

    // Some common format strings
    dateFormat.masks = {
        "default":      "ddd mmm dd yyyy HH:MM:ss",
        shortDate:      "m/d/yy",
        mediumDate:     "mmm d, yyyy",
        longDate:       "mmmm d, yyyy",
        fullDate:       "dddd, mmmm d, yyyy",
        shortTime:      "h:MM TT",
        mediumTime:     "h:MM:ss TT",
        longTime:       "h:MM:ss TT Z",
        isoDate:        "yyyy-mm-dd",
        isoTime:        "HH:MM:ss",
        isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
        isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
    };

    // Internationalization strings
    dateFormat.i18n = {
        dayNames: [
            "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
            "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
        ],
        monthNames: [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
            "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
        ]
    };

    // For convenience...
    Date.prototype.format = function (mask, utc) {
        return dateFormat(this, mask, utc);
    };

Why must wait() always be in synchronized block

@Rollerball is right. The wait() is called, so that the thread can wait for some condition to occur when this wait() call happens, the thread is forced to give up its lock.
To give up something, you need to own it first. Thread needs to own the lock first. Hence the need to call it inside a synchronized method/block.

Yes, I do agree with all the above answers regarding the potential damages/inconsistencies if you did not check the condition within synchronized method/block. However as @shrini1000 has pointed out, just calling wait() within synchronized block will not avert this inconsistency from happening.

Here is a nice read..

How to check if a character in a string is a digit or letter

This is the way how to check whether a given character is alphabet or not

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    char c = sc.next().charAt(0); 
    if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
         System.out.println(c + " is an alphabet.");
    else
        System.out.println(c + " is not an alphabet.");
}

Retrieve list of tasks in a queue in Celery

This worked for me in my application:

def get_celery_queue_active_jobs(queue_name):
    connection = <CELERY_APP_INSTANCE>.connection()

    try:
        channel = connection.channel()
        name, jobs, consumers = channel.queue_declare(queue=queue_name, passive=True)
        active_jobs = []

        def dump_message(message):
            active_jobs.append(message.properties['application_headers']['task'])

        channel.basic_consume(queue=queue_name, callback=dump_message)

        for job in range(jobs):
            connection.drain_events()

        return active_jobs
    finally:
        connection.close()

active_jobs will be a list of strings that correspond to tasks in the queue.

Don't forget to swap out CELERY_APP_INSTANCE with your own.

Thanks to @ashish for pointing me in the right direction with his answer here: https://stackoverflow.com/a/19465670/9843399

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Improve subplot size/spacing with many subplots in matplotlib

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()

Without Tight Layout

enter image description here


With Tight Layout enter image description here

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

How to redirect from one URL to another URL?

You can redirect anything or more URL via javascript, Just simple window.location.href with if else

Use this code,

<script>
if(window.location.href == 'old_url')
{
    window.location.href="new_url";
}


//Another url redirect
if(window.location.href == 'old_url2')
{
    window.location.href="new_url2";
}
</script>

You can redirect many URL's by this procedure. Thanks.

How to read a PEM RSA private key from .NET

You might take a look at JavaScience's source for OpenSSLKey

There's code in there that does exactly what you want to do.

In fact, they have a lot of crypto source code available here.


Source code snippet:

//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider  ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        MemoryStream  mem = new MemoryStream(privkey) ;
        BinaryReader binr = new BinaryReader(mem) ;    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();        //advance 1 byte
                else if (twobytes == 0x8230)
                        binr.ReadInt16();       //advance 2 bytes
                else
                        return null;

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                        return null;
                bt = binr.ReadByte();
                if (bt !=0x00)
                        return null;


                //------  all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems) ;

                Console.WriteLine("showing components ..");
                if (verbose) {
                        showBytes("\nModulus", MODULUS) ;
                        showBytes("\nExponent", E);
                        showBytes("\nD", D);
                        showBytes("\nP", P);
                        showBytes("\nQ", Q);
                        showBytes("\nDP", DP);
                        showBytes("\nDQ", DQ);
                        showBytes("\nIQ", IQ);
                }

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus =MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return RSA;
        }
        catch (Exception) {
                return null;
        }
        finally {
                binr.Close();
        }
}

Editor does not contain a main type

Follow the below steps:

  1. Backup all your .java files to some other location
  2. delete entire java project
  3. Create new java project by right click on root & click new
  4. restore all the files to new location !!

Hadoop cluster setup - java.net.ConnectException: Connection refused

For me it was that I could not cluster my zookeeper.

hdfs haadmin -getServiceState 1
active

hdfs haadmin -getServiceState 2
active

My hadoop-hdfs-zkfc-[hostname].log showed:

2017-04-14 11:46:55,351 WARN org.apache.hadoop.ha.HealthMonitor: Transport-level exception trying to monitor health of NameNode at HOST/192.168.1.55:9000: java.net.ConnectException: Connection refused Call From HOST/192.168.1.55 to HOST:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused

solution:

hdfs-site.xml
  <property>
    <name>dfs.namenode.rpc-bind-host</name>
      <value>0.0.0.0</value>
  </property>

before

netstat -plunt

tcp        0      0 192.168.1.55:9000        0.0.0.0:*               LISTEN      13133/java

nmap localhost -p 9000

Starting Nmap 6.40 ( http://nmap.org ) at 2017-04-14 12:15 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000047s latency).
Other addresses for localhost (not scanned): 127.0.0.1
PORT     STATE  SERVICE
9000/tcp closed cslistener

after

netstat -plunt
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      14372/java

nmap localhost -p 9000

Starting Nmap 6.40 ( http://nmap.org ) at 2017-04-14 12:28 EDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000039s latency).
Other addresses for localhost (not scanned): 127.0.0.1
PORT     STATE SERVICE
9000/tcp open  cslistener

Linux: copy and create destination dir if it does not exist

rsync file /path/to/copy/file/to/is/very/deep/there

This might work, if you have the right kind of rsync.

How to run test methods in specific order in JUnit4?

With JUnit 5.4, you can specify the order :

@Test
@Order(2)
public void sendEmailTestGmail() throws MessagingException {

you just need to annotate your class

@TestMethodOrder(OrderAnnotation.class)

https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-execution-order

i'm using this in my project and it works very well !

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

String Concatenation in EL

it also can be a great idea using concat for EL + MAP + JSON problem like in this example :

#{myMap[''.concat(myid)].content}

SQL QUERY replace NULL value in a row with a value from the previous known value

I know it is a very old forum, but I came across this while troubleshooting my problem :) just realised that the other guys have given bit complex solution to the above problem. Please see my solution below:

DECLARE @A TABLE(ID INT, Val INT)

INSERT INTO @A(ID,Val) SELECT 1, 3
INSERT INTO @A(ID,Val) SELECT 2, NULL
INSERT INTO @A(ID,Val) SELECT 3, 5
INSERT INTO @A(ID,Val) SELECT 4, NULL
INSERT INTO @A(ID,Val) SELECT 5, NULL
INSERT INTO @A(ID,Val) SELECT 6, 2

UPDATE D
    SET D.VAL = E.VAL
    FROM (SELECT A.ID C_ID, MAX(B.ID) P_ID
          FROM  @A AS A
           JOIN @A AS B ON A.ID > B.ID
          WHERE A.Val IS NULL
            AND B.Val IS NOT NULL
          GROUP BY A.ID) AS C
    JOIN @A AS D ON C.C_ID = D.ID
    JOIN @A AS E ON C.P_ID = E.ID

SELECT * FROM @A

Hope this may help someone:)

Calling a Javascript Function from Console

If it's inside a closure, i'm pretty sure you can't.

Otherwise you just do functionName(); and hit return.

Install a Python package into a different directory using pip?

Nobody seems to have mentioned the -t option but that the easiest:

pip install -t <direct directory> <package>

Create thumbnail image

This is the code I'm using. Also works for .NET Core > 2.0 using System.Drawing.Common NuGet.

https://www.nuget.org/packages/System.Drawing.Common/

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        const string input = "C:\\background1.png";
        const string output = "C:\\thumbnail.png";

        // Load image.
        Image image = Image.FromFile(input);

        // Compute thumbnail size.
        Size thumbnailSize = GetThumbnailSize(image);

        // Get thumbnail.
        Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
            thumbnailSize.Height, null, IntPtr.Zero);

        // Save thumbnail.
        thumbnail.Save(output);
    }

    static Size GetThumbnailSize(Image original)
    {
        // Maximum size of any dimension.
        const int maxPixels = 40;

        // Width and height.
        int originalWidth = original.Width;
        int originalHeight = original.Height;

        // Return original size if image is smaller than maxPixels
        if (originalWidth <= maxPixels || originalHeight <= maxPixels)
        {
            return new Size(originalWidth, originalHeight);
        }   

        // Compute best factor to scale entire image based on larger dimension.
        double factor;
        if (originalWidth > originalHeight)
        {
            factor = (double)maxPixels / originalWidth;
        }
        else
        {
            factor = (double)maxPixels / originalHeight;
        }

        // Return thumbnail size.
        return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
    }
}

Source:

https://www.dotnetperls.com/getthumbnailimage

jQuery find and replace string

Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.

HTML:

<div>
    <div>
        <p>
           <h1>
             <a class="swapText">lollipops</a>
           </h1>
        </p>
        <span class="swapText">lollipops</span>
    </div>
</div>
<p>
   <span class="lollipops">Hello, World!</span>
   <img src="/lollipops.jpg" alt="Cool image" />
</p>

jQuery:

$(document).ready(function() {
    $('.swapText').text("marshmallows");
});

Performance of Arrays vs. Lists

Here's one that uses Dictionaries, IEnumerable:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

static class Program
{
    static void Main()
    {
        List<int> list = new List<int>(6000000);

        for (int i = 0; i < 6000000; i++)
        {
                list.Add(i);
        }
        Console.WriteLine("Count: {0}", list.Count);

        int[] arr = list.ToArray();
        IEnumerable<int> Ienumerable = list.ToArray();
        Dictionary<int, bool> dict = list.ToDictionary(x => x, y => true);

        int chk = 0;
        Stopwatch watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            int len = list.Count;
            for (int i = 0; i < len; i++)
            {
                chk += list[i];
            }
        }
        watch.Stop();
        Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                chk += arr[i];
            }
        }
        watch.Stop();
        Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in Ienumerable)
            {
                chk += i;
            }
        }

        Console.WriteLine("Ienumerable/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in dict.Keys)
            {
                chk += i;
            }
        }

        Console.WriteLine("Dict/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);


        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in list)
            {
                chk += i;
            }
        }

        watch.Stop();
        Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in arr)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);



        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in Ienumerable)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Ienumerable/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in dict.Keys)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Dict/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        Console.ReadLine();
    }
}

How to convert string values from a dictionary, into int/float datatypes?

For python 3,

    for d in list:
        d.update((k, float(v)) for k, v in d.items())

Use .htaccess to redirect HTTP to HTTPs

None if this worked for me. First of all I had to look at my provider to see how they activate SSL in .htaccess my provider gives

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{HTTP:HTTPS} !on
   RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]
</IfModule>

But what took me days of research is I had to add to wp-config.php the following lines as my provided site is behind a proxy :

/**
 * Force le SSL
 */
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) $_SERVER['HTTPS']='on';

How can I set a UITableView to grouped style

You can also do this if you want to use it on a subclass you've already created in a separate swift file (probably not 100% correct but works)

override init(style: UITableViewStyle) {
    super.init(style: style)
    UITableViewStyle.Grouped
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

Now in you appdelegate.swift you can call:

let settingsController = SettingsViewController(style: .Grouped)

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

Is it possible to serialize and deserialize a class in C++?

I recommend using boost serialization as described by other posters. Here is a good detailed tutorial on how to use it which complements the boost tutorials nicely: http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/

How do you Sort a DataTable given column and direction?

Actually got the same problem. For me worked this easy way:

Adding the data to a Datatable and sort it:

dt.DefaultView.Sort = "columnname";
dt = dt.DefaultView.ToTable();

Parsing JSON array with PHP foreach

$user->data is an array of objects. Each element in the array has a name and value property (as well as others).

Try putting the 2nd foreach inside the 1st.

foreach($user->data as $mydata)
{
    echo $mydata->name . "\n";
    foreach($mydata->values as $values)
    {
        echo $values->value . "\n";
    }
}

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Another cause might be the fact that you're pointing to the wrong port.

Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.

Check the ports and run some query against the db.

Insert the same fixed value into multiple rows

What you're actually doing is adding rows. To update the content of existing rows use the UPDATE statement:

UPDATE table SET table_column = 'test';

Has an event handler already been added?

If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.

I think you can safely call -= on the event with your handler even if it's not added (if not, you could catch it) -- to make sure it isn't in there before adding.

How to create a custom exception type in Java?

Great answers about creating custom exception classes. If you intend to reuse the exception in question then I would follow their answers/advice. However, If you only need a quick exception thrown with a message then you can use the base exception class on the spot

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exeception*/
  throw new Exception("My one time exception with some message!");
}

How to horizontally center a floating element of a variable width?

The popular answer here does work sometimes, but other times it creates horizontal scroll bars that are tough to deal with - especially when dealing with wide horizontal navigations and large pull down menus. Here is an even lighter-weight version that helps avoid those edge cases:

#wrap {
    float: right;
    position: relative;
    left: -50%;
}
#content {
    left: 50%;
    position: relative;
}

Proof that it is working!

To more specifically answer your question, it is probably not possible to do without setting up some containing element, however it is very possible to do without specifying a width value. Hope that saves someone out there some headaches!

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

How do I find which process is leaking memory?

If you can't do it deductively, consider the Signal Flare debugging pattern: Increase the amount of memory allocated by one process by a factor of ten. Then run your program.

If the amount of the memory leaked is the same, that process was not the source of the leak; restore the process and make the same modification to the next process.

When you hit the process that is responsible, you'll see the size of your memory leak jump (the "signal flare"). You can narrow it down still further by selectively increasing the allocation size of separate statements within this process.

Format y axis as percent

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing.

Update

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

Convert sqlalchemy row object to python dict

With this code you can also to add to your query "filter" or "join" and this work!

query = session.query(User)
def query_to_dict(query):
        def _create_dict(r):
            return {c.get('name'): getattr(r, c.get('name')) for c in query.column_descriptions}

    return [_create_dict(r) for r in query]