Programs & Examples On #Gnupg

GNU Privacy Guard (GnuPG / GPG) is a cryptography suite implementing secret-key cryptography and public-key cryptography. GnuPG is the GNU project's complete and free implementation of the OpenPGP standard as defined by RFC4880. Use this tag for programmatic use of the GPG tool or its library. Questions about direct usage of the GPG tool or its graphical pendents belong on Super User.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

workmad3 is apparently out of date, at least for current gpg, as the --allow-secret-key-import is now obsolete and does nothing.

What happened to me was that I failed to export properly. Just doing gpg --export is not adequate, as it only exports the public keys. When exporting keys, you have to do

gpg --export-secret-keys >keyfile

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

How to display gpg key details without importing it?

The option --list-packets parses pgp data from a file and outputs its structure - in a very technical way, though. When parsing a public key, you can easily extract the user ids and the key ids of the signatures.

Be wary that this command only parses the data format, it does no validation of signatures or similar things.

How to Export Private / Secret ASC Key to Decrypt GPG Files

this ended up working for me:

   gpg -a --export-secret-keys > exportedKeyFilename.asc 

you can name keyfilename.asc by any name as long as you keep on the .asc extension.
this command copies all secret-keys on a user's computer to keyfilename.asc in the working directory of where the command was called.

To Export just 1 specific secret key instead of all of them:

   gpg -a --export-secret-keys keyIDNumber > exportedKeyFilename.asc

keyIDNumber is the number of the key id for the desired key you are trying to export.

gpg decryption fails with no secret key error

I have solved this problem, try to use root privileges, such as sudo gpg ... I think that gpg elevated without permissions does not refer to file permissions, but system

Can't check signature: public key not found

There is a similar problem.it is a tomcat digital signature.

$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc apache-tomcat-9.0.16-windows- 
x64.zip
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Can't check signature: No public key

but then I use the RSA key it provided to receive the public key to verify.

$ gpg --receive-keys A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: key 10C01C5A2F6059E7: 38 signatures not checked due to missing keys
gpg: key 10C01C5A2F6059E7: public key "Mark E D Thomas <[email protected]>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1

Then successfully.

$ gpg --verify apache-tomcat-9.0.16-windows-x64.zip.asc
gpg: assuming signed data in 'apache-tomcat-9.0.16-windows-x64.zip'
gpg: Signature made 2019?02? 5?  0:32:50
gpg:                using RSA key A9C5DF4D22E99998D9875A5110C01C5A2F6059E7
gpg: Good signature from "Mark E D Thomas <[email protected]>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: A9C5 DF4D 22E9 9998 D987  5A51 10C0 1C5A 2F60 59E7

What method in the String class returns only the first N characters?

I added this in my project just because where I'm using it is a high chance of it being used in loops, in a project hosted online hence I didn't want any crashes if I could manage it. The length fits a column I have. It's C#7

Just a one line:

 public static string SubStringN(this string Message, int Len = 499) => !String.IsNullOrEmpty(Message) ? (Message.Length >= Len ? Message.Substring(0, Len) : Message) : "";

How to dynamically add a style for text-align using jQuery

Is correct?

<script>
$( "#box" ).one( "click", function() {
  $( this ).css( "width", "+=200" );
});
</script>

How to get selenium to wait for ajax response?

For those who is using primefaces, just do:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().$.active==0", defaultWaitingPeriod);

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

How do I get the AM/PM value from a DateTime?

its pretty simple

  Date someDate = new DateTime();
  string timeOfDay = someDate.ToString("hh:mm tt"); 
  // hh - shows hour and mm - shows minute - tt - shows AM or PM

How to add text to a WPF Label in code?

You can use the Content property on pretty much all visual WPF controls to access the stuff inside them. There's a heirarchy of classes that the controls belong to, and any descendants of ContentControl will work in this way.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Can enums be subclassed to add new elements?

The recommended solution to this is the extensible enum pattern.

This involves creating an interface and using that where you currently use the enum. Then make the enum implement the interface. You can add more constants by making that new enum also extend the interface.

Which programming languages can be used to develop in Android?

I made good experiences with Scala.

I use the simple build tool (sbt: http://code.google.com/p/simple-build-tool/) with the Android-Plugin (http://github.com/jberkel/android-plugin)

How to include CSS file in Symfony 2 and Twig?

In case you are using Silex add the Symfony Asset as a dependency:

composer require symfony/asset

Then you may register Asset Service Provider:

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.version_format' => '%s?version=%s',
    'assets.named_packages' => array(
        'css' => array(
            'version' => 'css2',
            'base_path' => __DIR__.'/../public_html/resources/css'
        ),
        'images' => array(
            'base_urls' => array(
                'https://img.example.com'
            )
        ),
    ),
));

Then in your Twig template file in head section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% block head %}
    <link rel="stylesheet" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>

</body>
</html>

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

JQuery select2 set default value from an option in list?

Step 1: You need to append one blank option with a blank value in your select tag.

Step 2: Add data-placeholder attribute in select tag with a placeholder value

HTML

<select class="select2" data-placeholder='--Select--'>
  <option value=''>--Select--</option>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
</select>

Jquery

$('.select2').select2({
    placeholder: $(this).data('placeholder')
});

OR

$('.select2').select2({
    placeholder: 'Custom placeholder text'
});

Check with jquery if div has overflowing elements

Here's a pure jQuery solution, but it's rather messy:

var div_height = $(this).height();
var vertical_div_top_position = $(this).offset().top;
var lastchild_height = $(this).children('p:last-child').height();
var vertical_lastchild_top_position = $(this).children('p:last-child').offset().top;
var vertical_lastchild_bottom_position = lastchild_height + vertical_lastchild_top_position;
var real_height = vertical_lastchild_bottom_position - vertical_div_top_position;

if (real_height > div_height){
    //overflow div
}

PHP - Session destroy after closing browser

If you are confused what to do, just refer to the manual of session_destroy() function:

http://php.net/manual/en/function.session-destroy.php

There you can find some more features of session_destroy().

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

The Problem might be from the driver name for example instead of DRIVER={MySQL ODBC 5.3 Driver} try DRIVER={MySQL ODBC 5.3 Unicode Driver} you can see the name of the driver from administration tool

How to check if an email address exists without sending an email?

Some issues:

  1. I'm sure some SMTP servers will let you know immediately if an address you give them does not exist, but some won't as a privacy measure. They'll just accept whatever addresses you give them and silently ignore the ones that don't exist.
  2. As the article says, if you do this too often with some servers, they will blacklist you.
  3. For some SMTP servers (like gmail), you need to use SSL in order to do anything. This is only true when using gmail's SMTP server to send email.

Where does git config --global get written to?

It might be useful to note (for *nix platforms): some types of global git configuration/information are stored in /usr/share/git-core/, such as git autocompletion scripts and the following (default) hooks:

  • applypatch-msg
  • post-update
  • pre-commit
  • prepare-commit-msg
  • commit-msg
  • pre-applypatch
  • pre-rebase
  • update

Each of these can contain their own set of commands to execute, at the time described by their respective filenames.

How can I hash a password in Java?

In addition to bcrypt and PBKDF2 mentioned in other answers, I would recommend looking at scrypt

MD5 and SHA-1 are not recommended as they are relatively fast thus using "rent per hour" distributed computing (e.g. EC2) or a modern high end GPU one can "crack" passwords using brute force / dictionary attacks in relatively low costs and reasonable time.

If you must use them, then at least iterate the algorithm a predefined significant amount of times (1000+).

Calling ASP.NET MVC Action Methods from JavaScript

Javascript Function

function AddToCart(id) {
 $.ajax({
   url: '@Url.Action("AddToCart", "ControllerName")',
   type: 'GET',
   dataType: 'json',
   cache: false,
   data: { 'id': id },
   success: function (results) {
        alert(results)
   },
   error: function () {
    alert('Error occured');
   }
   });
   }

Controller Method to call

[HttpGet]
  public JsonResult AddToCart(string id)
  {
    string newId = id;
     return Json(newId, JsonRequestBehavior.AllowGet);
  }

How to provide password to a command that prompts for one in bash?

Simply use :

echo "password" | sudo -S mount -t vfat /dev/sda1 /media/usb/;
if [ $? -eq 0 ]; then
    echo -e '[ ok ] Usb key mounted'
else
    echo -e '[warn] The USB key is not mounted'
fi

This code is working for me, and its in /etc/init.d/myscriptbash.sh

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

i have solve my same problem

i update my android studio, and i choose not to import my setting from my previous version than that problem appear.

than i realize that i have 2 AndroidStudio folder on my windows account (.AndroidStudio and .AndroidStudio1.2) and on my new .AndroidStudio1.2 folder there are no other.xml file.

than i copy other.xml file from C:\Users\my windows account name.AndroidStudio\config\options to C:\Users\my windows account name.AndroidStudio1.2\config\options

and that how i solve my problem.

Checking cin input stream produces an integer

You could use :

int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}

I'm pretty sure it works.

jquery datatables default sort

Here is the actual code that does it...

$(document).ready(function()
{
  var oTable = $('#myTable').dataTable();

  // Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
  oTable.fnSort( [ [1,'asc'] ] );

  // And to sort another column descending (at position 2 in the array (base 0).
  oTable.fnSort( [ [2,'desc'] ] );
} );

To not have the column highlighted, modify the CSS like so:

table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

How can I do a line break (line continuation) in Python?

Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

or

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

How to disable Google Chrome auto update?

After wrestling a lot, found an uncomplicated solution for Mac. Hope this will help.

  1. Leave it to upgrade.

  2. Then go to application, right click on chrome app and open package contents.

  3. Navigate further as /Applications/Google Chrome old.app/Contents/Frameworks/Google Chrome Framework.framework/Versions

  4. You will find a current folder. Delete this :)

  5. Restart chrome and enjoy..

Replacing characters in Ant property

Here is the solution without scripting and no external jars like ant-conrib:

The trick is to use ANT's resources:

  • There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
  • There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
<loadresource property="propB">
  <propertyresource name="propA"/>
  <filterchain>
    <tokenfilter>
      <filetokenizer/>
      <replacestring from=" " to="_"/>
    </tokenfilter>
  </filterchain>
</loadresource>

This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.

You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html

How to deal with persistent storage (e.g. databases) in Docker

When using Docker Compose, simply attach a named volume, for example:

version: '2'
services:
  db:
    image: mysql:5.6
    volumes:
      - db_data:/var/lib/mysql:rw
    environment:
      MYSQL_ROOT_PASSWORD: root
volumes:
  db_data:

Excluding directory when creating a .tar.gz file

Yes, remove the trailing / and (at least in ubuntu 11.04) all the paths given must be relative or full path. You can't mix absolute and relative paths in the same command.

sudo tar -czvf 2011.10.24.tar.gz ./start-directory --exclude "home/user/start-directory/logs"

will not exclude logs directory but

sudo tar -czvf 2011.10.24.tar.gz ./start-directory --exclude "./start-directory/logs"

will work

Why a function checking if a string is empty always returns true?

Well here is the short method to check whether the string is empty or not.

$input; //Assuming to be the string


if(strlen($input)==0){
return false;//if the string is empty
}
else{
return true; //if the string is not empty
}

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

SSRS will not accept duplicated columns so ensure that your query or store procedure is returning unique column names.

How to import a SQL Server .bak file into MySQL?

The .bak file from SQL Server is specific to that database dialect, and not compatible with MySQL.

Try using etlalchemy to migrate your SQL Server database into MySQL. It is an open-sourced tool that I created to facilitate easy migrations between different RDBMS's.

Quick installation and examples are provided here on the github page, and a more detailed explanation of the project's origins can be found here.

Printing 2D array in matrix format

you can do like this also

        long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 }};

        for (int i = 0; i < arr.GetLength(0); i++)
        {
            for (int j = 0; j < arr.GetLength(1); j++)
            {
                Console.Write(arr[i,j]+" ");
            }
            Console.WriteLine();
        }

Guzzlehttp - How get the body of a response from Guzzle 6?

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Stream that uses PHP temp streams. To retrieve all the data, you can use casting operator:

$contents = (string) $response->getBody();

You can also do it with

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContents returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewind or seek .

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

Import Libraries in Eclipse?

For the Android library projects, I do it as in the attached screenshot:

Right click the project, select Properties->Android and in the library section click Add. From here you can select the available libraries.

If you are importing a jar file, then importing them as jar or external jar, as other posters posted would work. I prefer to copy/paste jar file in the libs folder (create one if it doesn't exist) and then import as jar.

Adding a library

Regex how to match an optional character

Use

[A-Z]?

to make the letter optional. {1} is redundant. (Of course you could also write [A-Z]{0,1} which would mean the same, but that's what the ? is there for.)

You could improve your regex to

^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})

And, since in most regex dialects, \d is the same as [0-9]:

^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})

But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?

is of a type that is invalid for use as a key column in an index

A unique constraint can't be over 8000 bytes per row and will only use the first 900 bytes even then so the safest maximum size for your keys would be:

create table [misc_info]
( 
    [id] INTEGER PRIMARY KEY IDENTITY NOT NULL, 
    [key] nvarchar(450) UNIQUE NOT NULL, 
    [value] nvarchar(max) NOT NULL
)

i.e. the key can't be over 450 characters. If you can switch to varchar instead of nvarchar (e.g. if you don't need to store characters from more than one codepage) then that could increase to 900 characters.

How can I find out if an .EXE has Command-Line Options?

Unless the writer of the executable has specifically provided a way for you to display a list of all the command line switches that it offers, then there is no way of doing this.

As Marcin suggests, the typical switches for displaying all of the options are either /? or /help (some applications might prefer the Unix-style syntax, -? and -help, respectively). But those are just a common convention.

If those don't work, you're out of luck. You'll need to check the documentation for the application, or perhaps try decompiling the executable (if you know what you're looking for).

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

This situation occured if there are object in repository, which creates by current transaction.

Simple scenario:

  1. checkout some directory two times, as DIR1 and DIR2
  2. make 'svn mkdir test' in both
  3. make commit from DIR1
  4. try to make commit DIR2 (without svn up), SVN shall return this error

Same thing when adding same files from two working copies.

Add key value pair to all objects in array

You can do this with map()

_x000D_
_x000D_
var arrOfObj = [{_x000D_
  name: 'eve'_x000D_
}, {_x000D_
  name: 'john'_x000D_
}, {_x000D_
  name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(o) {_x000D_
  o.isActive = true;_x000D_
  return o;_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

If you want to keep original array you can clone objects with Object.assign()

_x000D_
_x000D_
var arrOfObj = [{_x000D_
  name: 'eve'_x000D_
}, {_x000D_
  name: 'john'_x000D_
}, {_x000D_
  name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(el) {_x000D_
  var o = Object.assign({}, el);_x000D_
  o.isActive = true;_x000D_
  return o;_x000D_
})_x000D_
_x000D_
console.log(arrOfObj);_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

AngularJS : The correct way of binding to a service properties

Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.

In the example below changes to the Controller $scope.count variable will automatically be reflected in the Service count variable.

In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.

The code below can be seen working at http://jsfiddle.net/xuUHS/163/

View:

<div ng-controller="ServiceCtrl">
    <p> This is my countService variable : {{count}}</p>
    <input type="number" ng-model="count">
    <p> This is my updated after click variable : {{countS}}</p>

    <button ng-click="clickC()" >Controller ++ </button>
    <button ng-click="chkC()" >Check Controller Count</button>
    </br>

    <button ng-click="clickS()" >Service ++ </button>
    <button ng-click="chkS()" >Check Service Count</button>
</div>

Service/Controller:

var app = angular.module('myApp', []);

app.service('testService', function(){
    var count = 10;

    function incrementCount() {
      count++;
      return count;
    };

    function getCount() { return count; }

    return {
        get count() { return count },
        set count(val) {
            count = val;
        },
        getCount: getCount,
        incrementCount: incrementCount
    }

});

function ServiceCtrl($scope, testService)
{

    Object.defineProperty($scope, 'count', {
        get: function() { return testService.count; },
        set: function(val) { testService.count = val; },
    });

    $scope.clickC = function () {
       $scope.count++;
    };
    $scope.chkC = function () {
        alert($scope.count);
    };

    $scope.clickS = function () {
       ++testService.count;
    };
    $scope.chkS = function () {
        alert(testService.count);
    };

}

Difference between InvariantCulture and Ordinal string comparison

Pointing to Best Practices for Using Strings in the .NET Framework:

  • Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance.
  • Use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase values instead of string operations based on CultureInfo.InvariantCulture when the comparison is linguistically irrelevant (symbolic, for example).

And finally:

  • Do not use string operations based on StringComparison.InvariantCulture in most cases. One of the few exceptions is when you are persisting linguistically meaningful but culturally agnostic data.

Python: Pandas Dataframe how to multiply entire column with a scalar

A bit old, but I was still getting the same SettingWithCopyWarning. Here was my solution:

df.loc[:, 'quantity'] = df['quantity'] * -1

Singleton: How should it be used

Anti-Usage:

One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.

Tomcat base URL redirection

In Tomcat 8 you can also use the rewrite-valve

RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/(.*)$         /somethingelse/index.jsp

To setup the rewrite-valve look here:

http://tonyjunkes.com/blog/a-brief-look-at-the-rewrite-valve-in-tomcat-8/

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

what is the use of Eval() in asp.net

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

How can I declare a Boolean parameter in SQL statement?

The same way you declare any other variable, just use the bit type:

DECLARE @MyVar bit
Set @MyVar = 1  /* True */
Set @MyVar = 0  /* False */

SELECT * FROM [MyTable] WHERE MyBitColumn = @MyVar

In Python script, how do I set PYTHONPATH?

PYTHONPATH ends up in sys.path, which you can modify at runtime.

import sys
sys.path += ["whatever"]

How do I translate an ISO 8601 datetime string into a Python datetime object?

Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]. If you want to use strptime, you need to strip out those variations first.

The goal is to generate a UTC datetime object.


If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z:

datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")

If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse.

import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )

If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z') then you need to manually offset the time from Z (UTC). Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).

import re
import datetime

# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)

# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
    sign = split_timestamp[1]
    offset = split_timestamp[2]
else:
    sign = None
    offset = None

# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
    # Create timedelta based on offset
    offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))

    # Offset datetime with timedelta
    output_datetime = output_datetime + offset_delta

How to run a cronjob every X minutes?

You are setting your cron to run on 10th minute in every hour.
To set it to every 5 mins change to */5 * * * * /usr/bin/php /mydomain.in/cronmail.php > /dev/null 2>&1

how to get param in method post spring mvc?

It also works if you change the content type

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

In the controller also add the header value as follows:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at http://www.webqr.com/index.html

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

Get a DataTable Columns DataType

You can get column type of DataTable with DataType attribute of datatable column like below:

var type = dt.Columns[0].DataType

dt : DataTable object.

0 : DataTable column index.

Hope It Helps

Ty :)

How do I use HTML as the view engine in Express?

Try out this simple solution, it worked for me

app.get('/', function(req, res){
    res.render('index.html')
  });

Date only from TextBoxFor()

Sure you can use Html.EditorFor. But if you want to use TextBoxFor and use format from DisplayFormat attribute you can use it in this way:

@Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)

or create next extension:

public static class HtmlExtensions
{
    public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
    }
}

mcrypt is deprecated, what is the alternative?

I am using this on PHP 7.2.x, it's working fine for me:

public function make_hash($userStr){
        try{
            /** 
             * Used and tested on PHP 7.2x, Salt has been removed manually, it is now added by PHP 
             */
             return password_hash($userStr, PASSWORD_BCRYPT);
            }catch(Exception $exc){
                $this->tempVar = $exc->getMessage();
                return false;
            }
        }

and then authenticate the hash with the following function:

public function varify_user($userStr,$hash){
        try{
            if (password_verify($userStr, $hash)) {
                 return true;
                }
            else {
                return false;
                }
            }catch(Exception $exc){
                $this->tempVar = $exc->getMessage();
                return false;
            }
        }

Example:

  //create hash from user string

 $user_password = $obj->make_hash2($user_key);

and to authenticate this hash use the following code:

if($obj->varify_user($key, $user_key)){
      //this is correct, you can proceed with  
    }

That's all.

Write values in app.config file

Yes you can - see ConfigurationManager

The ConfigurationManager class includes members that enable you to perform the following tasks:

  • Read and write configuration files as a whole.

Learn to use the docs, they should be your first port-of call for a question like this.

Execute the setInterval function without delay the first time

For someone needs to bring the outer this inside as if it's an arrow function.

(function f() {
    this.emit("...");
    setTimeout(f.bind(this), 1000);
}).bind(this)();

If the above producing garbage bothers you, you can make a closure instead.

(that => {
    (function f() {
        that.emit("...");
        setTimeout(f, 1000);
    })();
})(this);

Or maybe consider using the @autobind decorator depending on your code.

Java RegEx meta character (.) and ordinary dot?

If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes e.g. \\.

How to detect when cancel is clicked on file input?

/* Tested on Google Chrome */
$("input[type=file]").bind("change", function() {
    var selected_file_name = $(this).val();
    if ( selected_file_name.length > 0 ) {
        /* Some file selected */
    }
    else {
        /* No file selected or cancel/close
           dialog button clicked */
        /* If user has select a file before,
           when they submit, it will treated as
           no file selected */
    }
});

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

Order discrete x scale by frequency/value

The best way for me was using vector with categories in order I need as limits parameter to scale_x_discrete. I think it is pretty simple and straightforward solution.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))

enter image description here

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

sp_executesql is more likely to promote query plan reuse. When using sp_executesql, parameters are explicitly identified in the calling signature. This excellent article descibes this process.

The oft cited reference for many aspects of dynamic sql is Erland Sommarskog's must read: "The Curse and Blessings of Dynamic SQL".

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

I recommend two steps to address the bloated SDK problem.

First, I removed all but two versions of Android:

  1. The current version, e.g. 6.0 Marshmallow as of this writing. This version is to test and develop to the latest and greatest that the current Nexus handsets are running plus a couple of other brands.

  2. An older version, e.g. 4.04 Ice Cream Sandwich. This is to provide compatibility for the vast majority of handsets. You lose some functionality of the newer versions, but you gain a lowest common denominator of compatibility.

Second, I removed the emulators, and kept only the above two. I told it not to store the complete system state to disk, which it does indeed warn you will take up a lot of space, though it does make start-up faster. Just start up the emulator before you go make your coffee in the morning :)

If that's too much space, remove the emulators completely. Pick up a couple of older handsets off Ebay that will provide you with all the test platforms you need. They don't even have to be completely functional -- many apps don't need a SIM and cellular connectivity, for example.

My Android environment was taking up 32 gigs on my 128-gig Macbook Air. Couldn't keep doing this. Some day they'll make terabyte Macbook Airs but until then, got to slim down.

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

The problem is that there is an in-browser print dialogue within the popup window. If you call window.close() immediately then the dialogue is not seen by the user. The user needs to click "Print" within the dialogue. This is not the same as on other browsers where the print dialogue is part of the OS, and blocks the window.close() until dismissed - on Chrome, it's part of Chrome, not the OS.

This is the code I used, in a little popup window that is created by the parent window:

var is_chrome = function () { return Boolean(window.chrome); }
window.onload = function() {
    if(is_chrome){
        /*
         * These 2 lines are here because as usual, for other browsers,
         * the window is a tiny 100x100 box that the user will barely see.
         * On Chrome, it needs to be big enough for the dialogue to be read
         * (NB, it also includes a page preview).
        */
        window.moveTo(0,0);
        window.resizeTo(640, 480);

        // This line causes the print dialogue to appear, as usual:
        window.print();

        /*
         * This setTimeout isn't fired until after .print() has finished
         * or the dialogue is closed/cancelled.
         * It doesn't need to be a big pause, 500ms seems OK.
        */
        setTimeout(function(){
            window.close();
        }, 500);
    } else {
        // For other browsers we can do things more briefly:
        window.print();
        window.close();
    }
}

How to test an Internet connection with bash?

The top answer misses the fact that you can have a perfectly stable connection to your default gateway but that does not automatically mean you can actually reach something on the internet. The OP asks how he/she can test a connection with the world. So I suggest to alter the top answer by changing the gateway IP to a known IP (x.y.z.w) that is outside your LAN.

So the answer would become:

ping -q -w 1 -c 1 x.y.z.w > /dev/null && echo ok || echo error

Also removing the unfavored backticks for command substitution[1].

If you just want to make sure you are connected to the world before executing some code you can also use:

if ping -q -w 1 -c 1 x.y.z.w > /dev/null; then
    # more code
fi

How to split a string in Ruby and get all items except the first one?

Try split(",")[i] where i is the index in result array. split gives array below

["test1", " test2", " test3", " test4", " test5"] 

whose element can be accessed by index.

Using if elif fi in shell scripts

sh is interpreting the && as a shell operator. Change it to -a, that’s [’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]

Also, you should always quote the variables, because [ gets confused when you leave off arguments.

Access restriction on class due to restriction on required library rt.jar?

for me this how I solve it:

  • go to the build path of the current project

under Libraries

  • select the "JRE System Library [jdk1.8xxx]"
  • click edit
  • and select either "Workspace default JRE(jdk1.8xx)" OR Alternate JRE
  • Click finish
  • Click OK

enter image description here

Note: make sure that in Eclipse / Preferences (NOT the project) / Java / Installed JRE ,that the jdk points to the JDK folder not the JRE C:\Program Files\Java\jdk1.8.0_74

enter image description here

How to convert SecureString to System.String?

I think it would be best for SecureString dependent functions to encapsulate their dependent logic in an anonymous function for better control over the decrypted string in memory (once pinned).

The implementation for decrypting SecureStrings in this snippet will:

  1. Pin the string in memory (which is what you want to do but appears to be missing from most answers here).
  2. Pass its reference to the Func/Action delegate.
  3. Scrub it from memory and release the GC in the finally block.

This obviously makes it a lot easier to "standardize" and maintain callers vs. relying on less desirable alternatives:

  • Returning the decrypted string from a string DecryptSecureString(...) helper function.
  • Duplicating this code wherever it is needed.

Notice here, you have two options:

  1. static T DecryptSecureString<T> which allows you to access the result of the Func delegate from the caller (as shown in the DecryptSecureStringWithFunc test method).
  2. static void DecryptSecureString is simply a "void" version which employ an Action delegate in cases where you actually don't want/need to return anything (as demonstrated in the DecryptSecureStringWithAction test method).

Example usage for both can be found in the StringsTest class included.

Strings.cs

using System;
using System.Runtime.InteropServices;
using System.Security;

namespace SecurityUtils
{
    public partial class Strings
    {
        /// <summary>
        /// Passes decrypted password String pinned in memory to Func delegate scrubbed on return.
        /// </summary>
        /// <typeparam name="T">Generic type returned by Func delegate</typeparam>
        /// <param name="action">Func delegate which will receive the decrypted password pinned in memory as a String object</param>
        /// <returns>Result of Func delegate</returns>
        public static T DecryptSecureString<T>(SecureString secureString, Func<string, T> action)
        {
            var insecureStringPointer = IntPtr.Zero;
            var insecureString = String.Empty;
            var gcHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);

            try
            {
                insecureStringPointer = Marshal.SecureStringToGlobalAllocUnicode(secureString);
                insecureString = Marshal.PtrToStringUni(insecureStringPointer);

                return action(insecureString);
            }
            finally
            {
                //clear memory immediately - don't wait for garbage collector
                fixed(char* ptr = insecureString )
                {
                    for(int i = 0; i < insecureString.Length; i++)
                    {
                        ptr[i] = '\0';
                    }
                }

                insecureString = null;

                gcHandler.Free();
                Marshal.ZeroFreeGlobalAllocUnicode(insecureStringPointer);
            }
        }

        /// <summary>
        /// Runs DecryptSecureString with support for Action to leverage void return type
        /// </summary>
        /// <param name="secureString"></param>
        /// <param name="action"></param>
        public static void DecryptSecureString(SecureString secureString, Action<string> action)
        {
            DecryptSecureString<int>(secureString, (s) =>
            {
                action(s);
                return 0;
            });
        }
    }
}

StringsTest.cs

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Security;

namespace SecurityUtils.Test
{
    [TestClass]
    public class StringsTest
    {
        [TestMethod]
        public void DecryptSecureStringWithFunc()
        {
            // Arrange
            var secureString = new SecureString();

            foreach (var c in "UserPassword123".ToCharArray())
                secureString.AppendChar(c);

            secureString.MakeReadOnly();

            // Act
            var result = Strings.DecryptSecureString<bool>(secureString, (password) =>
            {
                return password.Equals("UserPassword123");
            });

            // Assert
            Assert.IsTrue(result);
        }

        [TestMethod]
        public void DecryptSecureStringWithAction()
        {
            // Arrange
            var secureString = new SecureString();

            foreach (var c in "UserPassword123".ToCharArray())
                secureString.AppendChar(c);

            secureString.MakeReadOnly();

            // Act
            var result = false;

            Strings.DecryptSecureString(secureString, (password) =>
            {
                result = password.Equals("UserPassword123");
            });

            // Assert
            Assert.IsTrue(result);
        }
    }
}

Obviously, this doesn't prevent abuse of this function in the following manner, so just be careful not to do this:

[TestMethod]
public void DecryptSecureStringWithAction()
{
    // Arrange
    var secureString = new SecureString();

    foreach (var c in "UserPassword123".ToCharArray())
        secureString.AppendChar(c);

    secureString.MakeReadOnly();

    // Act
    string copyPassword = null;

    Strings.DecryptSecureString(secureString, (password) =>
    {
        copyPassword = password; // Please don't do this!
    });

    // Assert
    Assert.IsNull(copyPassword); // Fails
}

Happy coding!

Mongoose, update values in array of objects

Having tried other solutions which worked fine, but the pitfall of their answers is that only fields already existing would update adding upsert to it would do nothing, so I came up with this.

 Person.update({'items.id': 2}, {$set: {
    'items': { "item1",  "item2",  "item3",  "item4" } }, {upsert: 
true })

What is two way binding?

Worth mentioning that there are many different solutions which offer two way binding and play really nicely.

I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.

There is a more extended list of backbone extensions/plugins on github

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

Round a double to 2 decimal places

Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.

For example:

round(200.3456, 2); // returns 200.35

Original version; watch out with this

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.

I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.

So, use this instead

(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = BigDecimal.valueOf(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

Note that HALF_UP is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.

Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()

And in every case

Always remember that floating point representations using float and double are inexact. For example, consider these expressions:

999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001

For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:

System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));

Some excellent further reading on the topic:


If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.

Specifically, note that round(200, 0) returns 200.0. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).

How do I open a URL from C++?

Your question may mean two different things:

1.) Open a web page with a browser.

#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );

This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.


2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read this or/and this.


I hope it's at least a little helpful.

EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.

How to serialize Joda DateTime with Jackson JSON processor?

In the object you're mapping:

@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }

In CustomDateSerializer:

public class CustomDateSerializer extends JsonSerializer<DateTime> {

    private static DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd-MM-yyyy");

    @Override
    public void serialize(DateTime value, JsonGenerator gen, 
                          SerializerProvider arg2)
        throws IOException, JsonProcessingException {

        gen.writeString(formatter.print(value));
    }
}

getResourceAsStream() is always returning null

I had a similar problem and I searched for the solution for quite a while: It appears that the string parameter is case sensitive. So if your filename is abc.TXT but you search for abc.txt, eclipse will find it - the executable JAR file won't.

How can I replace text with CSS?

This isn't really possible without tricks. Here is a way that works by replacing the text with an image of text.

.pvw-title{
    text-indent: -9999px;
    background-image: url(text_image.png)
}

This type of thing is typically done with JavaScript. Here is how it can be done with jQuery:

$('.pvw-title').text('new text');

How to know the size of the string in bytes?

System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);

Or

System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);

Input Type image submit form value?

I was in the same place as you, finally I found a neat answer :

<form action="xx/xx" method="POST">
  <input type="hidden" name="what you want" value="what you want">
  <input type="image" src="xx.xx">
</form>

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

From my experience, sudo apt-get install gcc-multilib g++-multilib helps. But my another issue is that I FORGET to clean the directory so I still get the same error. It is the first time to use clang or cmake. So I just delete my original directory and re-compile and it works. Hope it helps someone like me.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

python multithreading wait till all threads finished

From the threading module documentation

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. They are never deleted, since it is impossible to detect the termination of alien threads.

So, to catch those two cases when you are not interested in keeping a list of the threads you create:

import threading as thrd


def alter_data(data, index):
    data[index] *= 2


data = [0, 2, 6, 20]

for i, value in enumerate(data):
    thrd.Thread(target=alter_data, args=[data, i]).start()

for thread in thrd.enumerate():
    if thread.daemon:
        continue
    try:
        thread.join()
    except RuntimeError as err:
        if 'cannot join current thread' in err.args[0]:
            # catchs main thread
            continue
        else:
            raise

Whereupon:

>>> print(data)
[0, 4, 12, 40]

How to convert buffered image to image and vice-versa?

You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.

EDIT:

try {
    // Retrieve Image
    BufferedImage buffer = ImageIO.read(new File("old.png"));;
    // Here you can rotate your image as you want (making your magic)
    File outputfile = new File("saved.png");
    ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}

Where is SQL Profiler in my SQL Server 2008?

first get the profiler Exe from: http://expressprofiler.codeplex.com

then you can add it simply to the Management studio:

Tools -> External tools... ->

a- locate the exe file on your disk (If installed, it's typically C:\Program Files (x86)\ExpressProfiler\ExpressProfiler.exe)

b- give it a name e.g. Express Profiler

that's it :) you have your Profiler with your sql express edition

enter image description here

Changing Font Size For UITableView Section Headers

This is my solution with swift 5.

To fully control the header section view, you need to use the tableView(:viewForHeaderInsection::) method in your controller, as the previous post showed. However, there is a further step: to improve performance, apple recommend not generate a new view every time but to re-use the header view, just like reuse table cell. This is by method tableView.dequeueReusableHeaderFooterView(withIdentifier: ). But the problem I had is once you start to use this re-use function, the font won't function as expected. Other things like color, alignment all fine but just font. There are some discussions but I made it work like the following.

The problem is tableView.dequeueReusableHeaderFooterView(withIdentifier:) is not like tableView.dequeneReuseCell(:) which always returns a cell. The former will return a nil if no one available. Even if it returns a reuse header view, it is not your original class type, but a UITableHeaderFooterView. So you need to do the judgement and act according in your own code. Basically, if it is nil, get a brand new header view. If not nil, force to cast so you can control.

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let reuse_header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "yourHeaderID")
        if (reuse_header == nil) {
            let new_sec_header = YourTableHeaderViewClass(reuseIdentifier:"yourHeaderID")
            new_section_header.label.text="yourHeaderString"
            //do whatever to set color. alignment, etc to the label view property
            //note: the label property here should be your custom label view. Not the build-in labelView. This way you have total control.
            return new_section_header
        }
        else {
            let new_section_header = reuse_section_header as! yourTableHeaderViewClass
            new_sec_header.label.text="yourHeaderString"
            //do whatever color, alignment, etc to the label property
            return new_sec_header}

    }

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

net::ERR_INSECURE_RESPONSE in Chrome

I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell and change the date manually.

How to change color of Android ListView separator line?

XML version for @Asher Aslan cool effect.

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

    <gradient
        android:angle="180"
        android:startColor="#00000000"
        android:centerColor="#FFFF0000"
        android:endColor="#00000000"/>

</shape>

Name for that shape as: list_driver.xml under drawable folder

<ListView
        android:id="@+id/category_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:divider="@drawable/list_driver"
        android:dividerHeight="5sp" />

Why do I get a warning icon when I add a reference to an MEF plugin project?

Encountered the same issue with a ASP.Net Web App and two library class projects which needed to be referenced within the Web App. I had no information provided on why the build failed and the references were invalid.

Solution was to ensure all projects had the same Target Framework:

In Visual Studio 2015- Right Click project > Properties > Application > Target Framework

Save, Clean and Rebuild solution. The project references should no longer appear as yellow warnings and the solution will compile.

My Web App was targeting .Net 4.5 whereas the other two dependent library class projects targeted .Net v4.5.2

How to detect if multiple keys are pressed at once using JavaScript?

Make the keydown even call multiple functions, with each function checking for a specific key and responding appropriately.

document.keydown = function (key) {

    checkKey("x");
    checkKey("y");
};

Is there an equivalent method to C's scanf in Java?

If one really wanted to they could make there own version of scanf() like so:

    import java.util.ArrayList;
    import java.util.Scanner;

public class Testies {

public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // get input
    System.out.println("Give me input:");
    scanf(strings, nums);

    System.out.println("Ints gathered:");
    // print numbers scanned in
    for(Integer num : nums){
        System.out.print(num + " ");
    }
    System.out.println("\nStrings gathered:");
    // print strings scanned in
    for(String str : strings){
        System.out.print(str + " ");
    }

    System.out.println("\nData:");
    for(int i=0; i<strings.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner getLine = new Scanner(System.in);
    Scanner input = new Scanner(getLine.nextLine());

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}

// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
    Scanner input = (new Scanner(in));

    while(input.hasNext()){
        // get integers
        if(input.hasNextInt()){
            nums.add(input.nextInt());
        }
        // get strings
        else if(input.hasNext()){
            strings.add(input.next());
        }
    }
}


}

Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

Output:

Give me input: apples 8 9 pears oranges 5 Ints gathered: 8 9 5 Strings gathered: apples pears oranges Data: 8 apples 9 pears 5 oranges

Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.

How to open Atom editor from command line in OS X?

With the Atom editor open, in the menu bar:

Click Atom >> Install Shell Commands

atom-add-shell-commands

You should expect to see:

atom-commands-installed

Potentially restart your terminal. (I did just out of habit, not sure if you need to)

Event listener for when element becomes visible?

my solution:

; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
    var cssFn = $.fn[ name ];
    $.fn[ name ] = function( speed, easing, callback ) {
        if(speed == null || typeof speed === "boolean"){
            var ret=cssFn.apply( this, arguments )
            $.fn.triggerVisibleEvent.apply(this,arguments)
            return ret
        }else{
            var that=this
            var new_callback=function(){
                callback.call(this)
                $.fn.triggerVisibleEvent.apply(that,arguments)
            }
            var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
            return ret
        }
    };
});

$.fn.triggerVisibleEvent=function(){
    this.each(function(){
        if($(this).is(':visible')){
            $(this).trigger('visible')
            $(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
        }
    })
}
})(jQuery);

for example:

if(!$info_center.is(':visible')){
    $info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
    processMoreLessButton()
}

function processMoreLessButton(){
//some logic
}

How to Toggle a div's visibility by using a button click

You can easily do it with jquery toggle. By this toggle or slideToggle you will get nice animation and effect also.

_x000D_
_x000D_
$(function(){_x000D_
  $("#details_content").css("display","none");_x000D_
  $(".myButton").click(function(){_x000D_
    $("#details_content").slideToggle(1000);_x000D_
  })  _x000D_
})
_x000D_
<div class="main">_x000D_
    <h2 class="myButton" style="cursor:pointer">Click Me</h2>_x000D_
    <div id="details_content">_x000D_
        <h1> Lorem Ipsum is simply dummy text</h1> _x000D_
        <p>    of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to view user privileges using windows cmd?

You can use the following commands:

whoami /priv
whoami /all

For more information, check whoami @ technet.

How to make exe files from a node.js app?

Since this question has been answered, another solution has been launched.

https://github.com/appjs/appjs

At the time of this writing, this is the end-all solution for packaging node.js apps through a stripped down chromium package compiled into an executable.

Edit: AppJS is no longer active, but itself suggests a fork called deskshell.

https://github.com/sihorton/appjs-deskshell/

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

That's probably useful for someone, who uses unittest, if imported modules use request library. To suppress warnings in requests' vendored urllib3, add

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

to setUp method in your testclass, i.e:

import unittest, warnings

class MyTests(unittest.TestCase):
    
    def setUp(self):
        warnings.filterwarnings('ignore', message='Unverified HTTPS request')
    
    (all test methods here)

How to check whether an object is a date?

For all types I cooked up an Object prototype function. It may be of use to you

Object.prototype.typof = function(chkType){
      var inp        = String(this.constructor),
          customObj  = (inp.split(/\({1}/))[0].replace(/^\n/,'').substr(9),
          regularObj = Object.prototype.toString.apply(this),
          thisType   = regularObj.toLowerCase()
                        .match(new RegExp(customObj.toLowerCase()))
                       ? regularObj : '[object '+customObj+']';
     return chkType
            ? thisType.toLowerCase().match(chkType.toLowerCase()) 
               ? true : false
            : thisType;
}

Now you can check any type like this:

var myDate     = new Date().toString(),
    myRealDate = new Date();
if (myRealDate.typof('Date')) { /* do things */ }
alert( myDate.typof() ); //=> String

[Edit march 2013] based on progressing insight this is a better method:

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im)
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Some = function(){ /* ... */}
   ,Other = function(){ /* ... */}
   ,some = new Some;
2..is(String,Function,RegExp);        //=> false
2..is(String,Function,Number,RegExp); //=> true
'hello'.is(String);                   //=> true
'hello'.is();                         //-> String
/[a-z]/i.is();                        //-> RegExp
some.is();                            //=> 'ANONYMOUS_CONSTRUCTOR'
some.is(Other);                       //=> false
some.is(Some);                        //=> true
// note: you can't use this for NaN (NaN === Number)
(+'ab2').is(Number);                 //=> true

Format the date using Ruby on Rails

Easiest is to use strftime (docs).

If it's for use on the view side, better to wrap it in a helper, though.

command/usr/bin/codesign failed with exit code 1- code sign error

Another reason you may see this error that I haven't seen posted yet, especially if you are using Jenkins, is that your certificate's private key needs "Allow all applications to access this item" selected.

  1. Open your Mac keychain
  2. Go to "Certificates" or "My Certificates" under "Category" on the left.
  3. Find the cert you're trying to sign with, and click the little grey triangle on the left of the certificate to reveal the associated private key.
  4. Left/ double-click the private key and select "Get Info."
  5. Toggle from "Attributes" to "Access control"
  6. Select "Allow all applications to access this item" and save changes.
    enter image description here I maintain a large cluster of Mac mini nodes as part of a centralized Jenkins CI system, and this can come up.

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

Run Button is Disabled in Android Studio

Just click the dropdown button on left side of RUN button (in your image the dropdown which is in red box) select 'app' option from that and RUN button will be enabled.

Please refer below screenshot.

enter image description here

Disable HttpClient logging

I had this same problem when running jwebunit integration tests. I fixed it by excluding logback and adding in slf4j-log4j12, like so:

<dependency>
  <groupId>net.sourceforge.jwebunit</groupId>
  <artifactId>jwebunit-htmlunit-plugin</artifactId>
  <version>3.0</version>
  <exclusions>
    <exclusion>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
</dependency>

How to pass a single object[] to a params object[]

The params parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params parameter:

1) Calling with an array of the parameter type, in which case the params keyword has no effect and the array is passed directly to the method:

object[] array = new[] { "1", "2" };

// Foo receives the 'array' argument directly.
Foo( array );

2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:

// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );

// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );


In order to pass in an object array to a method with a "params object[]" parameter, you can either:

1) Create a wrapper array manually and pass that directly to the method, as mentioned by lassevk:

Foo( new object[] { array } );  // Equivalent to calling convention 1.

2) Or, cast the argument to object, as mentioned by Adam, in which case the compiler will create the wrapper array for you:

Foo( (object)array );  // Equivalent to calling convention 2.


However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "params object[][]" parameter. This would allow you to pass multiple arrays as arguments:

void Foo( params object[][] arrays ) {
  foreach( object[] array in arrays ) {
    // process array
  }
}

...
Foo( new[] { "1", "2" }, new[] { "3", "4" } );

// Equivalent to:
object[][] arrays = new[] {
  new[] { "1", "2" },
  new[] { "3", "4" }
};
Foo( arrays );

Edit: Raymond Chen describes this behavior and how it relates to the C# specification in a new post.

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

How to customise file type to syntax associations in Sublime Text?

There is a quick method to set the syntax: Ctrl+Shift+P,then type in the input box

ss + (which type you want set)

eg: ss html +Enter

and ss means "set syntax"

it is really quicker than check in the menu's checkbox.

Java 8 Stream API to find Unique Object matching a property value

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.

Vue 'export default' vs 'new Vue'

export default is used to create local registration for Vue component.

Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e

Unit testing with mockito for constructors

Include this line on top of your test class

@PrepareForTest({ First.class })

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Android LinearLayout Gradient Background

Try removing android:gradientRadius="90". Here is one that works for me:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
>
    <gradient
        android:startColor="@color/purple"
        android:endColor="@color/pink"
        android:angle="270" />
</shape>

TypeError: can only concatenate list (not "str") to list

Let me fix your code

inventory=["sword", "potion", "armour", "bow"]
print(inventory)
print("\ncommands: use (remove) and pickup (add)")
selection=input("choose a command [use/pickup]")

if selection == "use":
    print(inventory)
    inventory.remove(input("What do you want to use? "))
    print(inventory)
elif selection == "pickup":
    print(inventory)
    add=input("What do you want to pickup? ")
    newinv=inventory+[str(add)] #use '[str(add)]' or list(str(add))
    print(newinv)

The error is you are adding string and list, you should use list or [] to make the string become list type

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

Best C++ IDE or Editor for Windows

Um, that's because Visual Studio is the best IDE. Come back to the darkside.

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

BLOB to String, SQL Server

It depends on how the data was initially put into the column. Try either of these as one should work:

SELECT CONVERT(NVarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

Or if it was just varchar...

SELECT CONVERT(VarChar(40), BLOBTextToExtract)
FROM [NavisionSQL$Customer];

I used this script to verify and test on SQL Server 2K8 R2:

DECLARE @blob VarBinary(MAX) = CONVERT(VarBinary(MAX), 'test');

-- show the binary representation
SELECT @blob;

-- this doesn't work
SELECT CONVERT(NVarChar(100), @blob);

-- but this does
SELECT CONVERT(VarChar(100), @blob);

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

Jquery Chosen plugin - dynamically populate list by Ajax

This might be helpful. You have to just trigger an event.

$("#DropDownID").trigger("liszt:updated");

Where "DropDownID" is ID of <select>.

More info here: http://harvesthq.github.com/chosen/

Android Studio and android.support.v4.app.Fragment: cannot resolve symbol

I was facing the same issue. As it turns out in my build.gradle file there was this :

configurations {
    all*.exclude group: 'com.android.support'
}

Removing that fixed my issue. So guys, if doing all that and still your issue is not fixed, look for any exclude keywords in your gradle file.

Use <Image> with a local file

You have to add to the source property an object with a property called "uri" where you can specify the path of your image as you can see in the following example:

<Image style={styles.image} source={{uri: "http://www.mysyte.com/myimage.jpg"}} />

remember then to set the width and height via the style property:

var styles = StyleSheet.create({
   image:{
    width: 360,
    height: 40,
  }
});

get the data of uploaded file in javascript

you can use the new HTML 5 file api to read file contents

https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

but this won't work on every browser so you probably need a server side fallback.

How to iterate over a JavaScript object?

I finally came up with a handy utility function with a unified interface to iterate Objects, Strings, Arrays, TypedArrays, Maps, Sets, (any Iterables).

const iterate = require('@a-z/iterate-it');
const obj = { a: 1, b: 2, c: 3 };

iterate(obj, (value, key) => console.log(key, value)); 
// a 1
// b 2
// c 3

https://github.com/alrik/iterate-javascript

There can be only one auto column

The full error message sounds:

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

So add primary key to the auto_increment field:

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

npx command not found

check versions of node, npm, npx as given below. if npx is not installed then use npm i -g npx

node -v
npm -v
npx -v

"Debug certificate expired" error in Eclipse Android plugins

On Vista, this worked:

  1. DOS: del c:\user\dad\.android\debug.keystore

  2. ECLIPSE: In Project, Clean the project. Close Eclipse. Re-open Eclipse.

  3. ECLIPSE: Start the Emulator. Remove the Application from the emulator.

You are good to go.

I was pretty worried when I say that error, but I fixed it from reading here and playing around for 10 minutes.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

It's better to use the actual (msi) installer from nodejs.org instead of downloading the node executable only. The installer includes npm and makes it easier to manage your node installation. There is an installer for both 32-bit and 64-bit Windows.

Also a couple of other tidbits:

  • Installing modules globally doesn't do what you might expect. The only modules you should install globally (the -g flag in npm) are ones that install commands. So to install Express you would just do npm install express and that will install Express to your current working directory. If you were instead looking for the Express project generator (command), you need to do npm install -g express-generator for Express 4.

  • You can use node anywhere from your command prompt to execute scripts. For example if you have already written a separate script: node foo.js. Or you can open up the REPL (as you've already found out) by just selecting the node.js (start menu) shortcut or by just typing node in a command prompt.

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

Rotating x axis labels in R for barplot

Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:

par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels

#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"

end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)

barplot(mtcars$qsec, col = "grey50", 
        main = "",
        ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
        xlab = "",
        space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25, 
     srt = 60, adj = 1, xpd = TRUE,
     labels = paste(rownames(mtcars)), cex = 0.65)

enter image description here

Unable to create Genymotion Virtual Device

We had the same issues, it was because we had wrong version of Oracle VM Virtual Box. Make sure you uninstall wrong version and re-install Compatible Oracle VM Virtual Box.

Shell equality operators (=, ==, -eq)

It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test.

If you use (()), you are testing arithmetic equality with == as in C:

$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1

(Note: 0 means true in the Unix sense and a failed test results in a non-zero number.)

Using -eq inside of double parentheses is a syntax error.

If you are using [] (or single brackets) or [[]] (or double brackets), or test you can use one of -eq, -ne, -lt, -le, -gt, or -ge as an arithmetic comparison.

$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0

The == inside of single or double brackets (or the test command) is one of the string comparison operators:

$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1

As a string operator, = is equivalent to ==. Also, note the whitespace around = or ==: it’s required.

While you can do [[ 1 == 1 ]] or [[ $(( 1+1 )) == 2 ]] it is testing the string equality — not the arithmetic equality.

So -eq produces the result probably expected that the integer value of 1+1 is equal to 2 even though the right-hand side is a string and has a trailing space:

$ [[ $(( 1+1 )) -eq  "2 " ]]; echo $?
0

While a string comparison of the same picks up the trailing space and therefore the string comparison fails:

$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1

And a mistaken string comparison can produce a completely wrong answer. 10 is lexicographically less than 2, so a string comparison returns true or 0. So many are bitten by this bug:

$ [[ 10 < 2 ]]; echo $?
0

The correct test for 10 being arithmetically less than 2 is this:

$ [[ 10 -lt 2 ]]; echo $?
1

In comments, there is a question about the technical reason why using the integer -eq on strings returns true for strings that are not the same:

$ [[ "yes" -eq "no" ]]; echo $?
0

The reason is that Bash is untyped. The -eq causes the strings to be interpreted as integers if possible including base conversion:

$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0

And 0 if Bash thinks it is just a string:

$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1

So [[ "yes" -eq "no" ]] is equivalent to [[ 0 -eq 0 ]]


Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]] and ((...)) or ==.

Compress files while reading data from STDIN

gzip > stdin.gz perhaps? Otherwise, you need to flesh out your question.

How can I install a .ipa file to my iPhone simulator

I found an .ipa file that I wanted using iTunes and copied it over to my desktop.

After that I changed the extension to .zip and extracted it.

Next I found the Payload folder and moved the application inside to my desktop.

Finally I moved that application to my iPhone simulators applications folder found at:

  • HD
  • > Applications
  • > Xcode.app (right click - Show Package Contents)
  • > Contents
  • > Developer
  • > Platforms
  • > iPhoneSimulator.platform
  • > SDKs
  • > iPhoneSimulator6.0.sdk
  • > Applications

Hope this helps! (Note: Some apps crash more often than others.)

Which icon sizes should my Windows application's icon include?

In the case of Windows 10 this is not exactly accurate, in fact none of the answers on stackoverflow was, I found this out when I tried to use pixel art as an icon and it got rescaled when it was not supposed to(it was easy to see in this case cause of the interpolation and smoothing windows does) even thou I used the sizes from this post.

So I made an app and did the work on all DPI settings, see it here:
Windows 10 all icon resolutions on all DPI settings
You can also use my app to create icons, also with nearest neighbor interpolation with smoothing off, which is not done with any of the bad editors I have seen.

If you only want the resolutions:
16, 20, 24, 28, 30, 31, 32, 40, 42, 47, 48, 56, 60, 63, 84, 256
and you should use all PNG icons and anything you put in beside these it won't be displayed. See my post why.

Javascript - remove an array item by value

You'll want to use .indexOf() and .splice(). Something like:

tag_story.splice(tag_story.indexOf(90),1);

PHP foreach with Nested Array?

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I won't make such a big deal from this question.
It's not like choosing your new wife or car.
I'd never run any of these on a production server, so, to run just some quick tests any of them are equally good.

Can I edit an iPad's host file?

You can also make use of a proxy server on your iPhone or iPade via mobile internet (3G) by using a iPhone Mobile proxy generator:

http://iphonesettings.net/mobileproxygenerator.php

Just enter the apn of your carrier (with apn username/password if needed) and the proxy server you want to go through and tap Generate

Display encoded html with razor

I store encoded HTML in the database.

Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:

<div class='content'>
    @Model.Content
</div>

JavaScript Infinitely Looping slideshow with delays?

You can infinitely loop easily enough via recursion.

function it_keeps_going_and_going_and_going() {
  it_keeps_going_and_going_and_going();
}

it_keeps_going_and_going_and_going()

What is (x & 1) and (x >>= 1)?

x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

Argument list too long error for rm, cp, mv commands

i was facing same problem while copying form source directory to destination

source directory had files ~3 lakcs

i used cp with option -r and it's worked for me

cp -r abc/ def/

it will copy all files from abc to def without giving warning of Argument list too long

What is difference between @RequestBody and @RequestParam?

map HTTP request header Content-Type, handle request body.

  • @RequestParam ? application/x-www-form-urlencoded,

  • @RequestBody ? application/json,

  • @RequestPart ? multipart/form-data,


Why does Maven have such a bad rep?

I've struggled my way through most/all the negatives mentioned here, and similar objections from teammates, and agree with them all. But I've stuck it out and will continue to do so by holding firm to the one objective that only maven (or gradle perhaps) really delivers on.

If you're optimizing for peers (open source developers), ant/make/whatever will do. If you're delivering functionality to non-peers (users), only maven/gradle/etc will do.

Only maven lets you release a small bundle of source code + poms (no embedded lib/binary dependency jars with cryptic names and no dependency info) with a well documented standard project layout that can be loaded by any IDE by someone that hasn't absorbed the developers' idiosyncratic layout conventions. And there's a one-button install procedure (mvn install) that builds everything while acquiring any missing dependencies.

The result is an easy on-ramp those users can follow to find their way into the code, where the poms can point them to relevant documentation.

Apart from that (indispensible) requirement, I dislike maven as much as anyone.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

How much does it cost to develop an iPhone application?

River of News for the iPad took about 400 hours of development to get to version 1.0 and I don't know how many hours my designer spent (20-50?). At US labor rates that's at least $40,000. But that sort of tight development was only possible because it was a one man operation. There is an enormous amount of overhead added when you separate the person writing the code from the person deciding what the product is going to do.

If you are going to send it offshore you'd better know exactly what you want. With the language and time difference it's very hard to do iterative design where you are exploring what is possible.

Sorting an array of objects by property values

A simple code :

_x000D_
_x000D_
    var homes = [_x000D_
        {_x000D_
            "h_id": "3",_x000D_
            "city": "Dallas",_x000D_
            "state": "TX",_x000D_
            "zip": "75201",_x000D_
            "price": "162500"_x000D_
        }, {_x000D_
            "h_id": "4",_x000D_
            "city": "Bevery Hills",_x000D_
            "state": "CA",_x000D_
            "zip": "90210",_x000D_
            "price": "319250"_x000D_
        }, {_x000D_
            "h_id": "5",_x000D_
            "city": "New York",_x000D_
            "state": "NY",_x000D_
            "zip": "00010",_x000D_
            "price": "962500"_x000D_
        }_x000D_
    ];_x000D_
_x000D_
    let sortByPrice = homes.sort(function (a, b) _x000D_
    {_x000D_
      return parseFloat(b.price) - parseFloat(a.price);_x000D_
    });_x000D_
_x000D_
    for (var i=0; i<sortByPrice.length; i++)_x000D_
    {_x000D_
      document.write(sortByPrice[i].h_id+' '+sortByPrice[i].city+' '_x000D_
       +sortByPrice[i].state+' '_x000D_
       +sortByPrice[i].zip+' '+sortByPrice[i].price);_x000D_
      document.write("<br>");_x000D_
    }
_x000D_
_x000D_
_x000D_

Execute PowerShell Script from C# with Commandline Arguments

Mine is a bit more smaller and simpler:

/// <summary>
/// Runs a PowerShell script taking it's path and parameters.
/// </summary>
/// <param name="scriptFullPath">The full file path for the .ps1 file.</param>
/// <param name="parameters">The parameters for the script, can be null.</param>
/// <returns>The output from the PowerShell execution.</returns>
public static ICollection<PSObject> RunScript(string scriptFullPath, ICollection<CommandParameter> parameters = null)
{
    var runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    var cmd = new Command(scriptFullPath);
    if (parameters != null)
    {
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
    }
    pipeline.Commands.Add(cmd);
    var results = pipeline.Invoke();
    pipeline.Dispose();
    runspace.Dispose();
    return results;
}

Parenthesis/Brackets Matching using Stack algorithm

If you want to have a look at my code. Just for reference

public class Default {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int numOfString = Integer.parseInt(br.readLine());
        String s;
        String stringBalanced = "YES";
        Stack<Character> exprStack = new Stack<Character>();

        while ((s = br.readLine()) != null) {
            stringBalanced = "YES";
            int length = s.length() - 1;
            for (int i = 0; i <= length; i++) {
                char tmp = s.charAt(i);

                if(tmp=='[' || tmp=='{' || tmp=='('){
                    exprStack.push(tmp);
                }else if(tmp==']' || tmp=='}' || tmp==')'){
                    if(!exprStack.isEmpty()){
                        char peekElement = exprStack.peek();
                        exprStack.pop();
                        if(tmp==']' && peekElement!='['){
                            stringBalanced="NO";
                        }else if(tmp=='}' && peekElement!='{'){
                            stringBalanced="NO";
                        }else if(tmp==')' && peekElement!='('){
                            stringBalanced="NO";
                        }
                    }else{
                        stringBalanced="NO";
                        break;
                    }
                }

            }

            if(!exprStack.isEmpty()){
                stringBalanced = "NO";
            }

            exprStack.clear();
            System.out.println(stringBalanced);
        }
    }
}

jQuery-- Populate select from json

I would do something like this:

$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

Check if current directory is a Git repository

This answer provides a sample POSIX shell function and a usage example to complement @jabbie's answer.

is_inside_git_repo() {
    git rev-parse --is-inside-work-tree >/dev/null 2>&1
}

git returns errorlevel 0 if it is inside a git repository, else it returns errorlevel 128. (It also returns true or false if it is inside a git repository.)

Usage example

for repo in *; do
    # skip files
    [ -d "$repo" ] || continue
    # run commands in subshell so each loop starts in the current dir
    (
        cd "$repo"
        # skip plain directories
        is_inside_git_repo || continue
        printf '== %s ==\n' "$repo"
        git remote update --prune 'origin' # example command
        # other commands here
    )
done

Finding duplicate rows in SQL Server

 /*To get duplicate data in table */

 SELECT COUNT(EmpCode),EmpCode FROM tbl_Employees WHERE Status=1 
  GROUP BY EmpCode HAVING COUNT(EmpCode) > 1

Chrome refuses to execute an AJAX script due to wrong MIME type

if application is hosted on IIS, make sure Static Content is installed. Control Panel > Programs > Turn Windows features on or off > Internet Information Services > World Wide Web Services > Common HTTP Features > Static Content.

I faced this problem when trying to run an existing application on a new IIS 10.0 installation

sql - insert into multiple tables in one query

Multiple SQL statements must be executed with the mysqli_multi_query() function.

Example (MySQLi Object-oriented):

    <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

How to read a CSV file into a .NET Datatable

I have been using OleDb provider. However, it has problems if you are reading in rows that have numeric values but you want them treated as text. However, you can get around that issue by creating a schema.ini file. Here is my method I used:

// using System.Data;
// using System.Data.OleDb;
// using System.Globalization;
// using System.IO;

static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
    string header = isFirstRowHeader ? "Yes" : "No";

    string pathOnly = Path.GetDirectoryName(path);
    string fileName = Path.GetFileName(path);

    string sql = @"SELECT * FROM [" + fileName + "]";

    using(OleDbConnection connection = new OleDbConnection(
              @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + 
              ";Extended Properties=\"Text;HDR=" + header + "\""))
    using(OleDbCommand command = new OleDbCommand(sql, connection))
    using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
    {
        DataTable dataTable = new DataTable();
        dataTable.Locale = CultureInfo.CurrentCulture;
        adapter.Fill(dataTable);
        return dataTable;
    }
}

PHP function use variable from outside

Do not forget that you also can pass these use variables by reference.

The use cases are when you need to change the use'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).

$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
    $newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);

Now $newarray will comprise (pseudocode here for brevity) [{times2:2},{times2:4}].

On the contrary, using $newarray with no & modifier would make outer $newarray variable be read-only accessible from within the closure scope. But $newarray within closure scope would be a completelly different newly created variable living only within the closure scope.

Despite both variables' names are the same these would be two different variables. The outer $newarray variable would comprise [] in this case after the code has finishes.

How To limit the number of characters in JTextField?

Just Try This :

textfield.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
        if(textfield.getText().length()>=5&&!(evt.getKeyChar()==KeyEvent.VK_DELETE||evt.getKeyChar()==KeyEvent.VK_BACK_SPACE)) {
            getToolkit().beep();
            evt.consume();
         }
     }
});

Where does Hive store files in HDFS?

If you look at the hive-site.xml file you will see something like this

<property>
   <name>hive.metastore.warehouse.dir</name>
   <value>/usr/hive/warehouse </value>
   <description>location of the warehouse directory</description>
 </property>

/usr/hive/warehouse is the default location for all managed tables. External tables may be stored at a different location.

describe formatted <table_name> is the hive shell command which can be use more generally to find the location of data pertaining to a hive table.

How to detect lowercase letters in Python?

import re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

Or you can use a list comprehension / generator expression:

slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

How to insert Records in Database using C# language?

You should change your code to make use of SqlParameters and adapt your insert statement to the following

string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// [ ] required as your fields contain spaces!!
string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";

using (SqlConnection cnn = new SqlConnection(connetionString))
{
    cnn.Open();
    SqlCommand insCmd = new SqlCommand(insStmt, cnn);
    // use sqlParameters to prevent sql injection!
    insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
    insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
    int affectedRows = insCmd.ExecuteNonQuery();
    MessageBox.Show (affectedRows + " rows inserted!");
}

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

Downgrade your version

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version><change this version></version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

Build and undo the version, Build. 2.1.6.RELEASE to 1.3.3.RELEASE Build Undo 1.3.3 to 2.1.6 Build (in my case problem solved) It helped us.

How to distinguish between left and right mouse click with jQuery

You can easily tell which mouse button was pressed by checking the which property of the event object on mouse events:

/*
  1 = Left   mouse button
  2 = Centre mouse button
  3 = Right  mouse button
*/

$([selector]).mousedown(function(e) {
    if (e.which === 3) {
        /* Right mouse button was clicked! */
    }
});

Case Statement Equivalent in R

If you got factor then you could change levels by standard method:

df <- data.frame(name = c('cow','pig','eagle','pigeon'), 
             stringsAsFactors = FALSE)
df$type <- factor(df$name) # First step: copy vector and make it factor
# Change levels:
levels(df$type) <- list(
    animal = c("cow", "pig"),
    bird = c("eagle", "pigeon")
)
df
#     name   type
# 1    cow animal
# 2    pig animal
# 3  eagle   bird
# 4 pigeon   bird

You could write simple function as a wrapper:

changelevels <- function(f, ...) {
    f <- as.factor(f)
    levels(f) <- list(...)
    f
}

df <- data.frame(name = c('cow','pig','eagle','pigeon'), 
                 stringsAsFactors = TRUE)

df$type <- changelevels(df$name, animal=c("cow", "pig"), bird=c("eagle", "pigeon"))

Unable to merge dex

Change you buildToolsVersion to some other version and sync, change it back and sync again. It will work again.

Adding an item to an associative array

For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this

 $data[$category]["test"] = $question

you can then call it (to test out the result by:

echo $data[$category]["test"];

which should print $question

Amazon S3 boto - how to create a folder?

Apparently you can now create folders in S3. I'm not sure since when, but I have a bucket in "Standard" zone and can choose Create Folder from Action dropdown.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

How to open the command prompt and insert commands using Java?

I know that people recommend staying away from rt.exec(String), but this works, and I don't know how to change it into the array version.

rt.exec("cmd.exe /c cd \""+new_dir+"\" & start cmd.exe /k \"java -flag -flag -cp terminal-based-program.jar\"");

How do I remove the old history from a git repository?

  1. remove git data, rm .git
  2. git init
  3. add a git remote
  4. force push

Force youtube embed to start in 720p

This is an embed example of video played in HD 1080.

<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

Let's break apart the code:http://youtube.com/v/ video_id &vq=hd1080

Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.

So far so good, this trick works for playing full HD videos directly on webpages!

You can change the quality to 720 too. &vq=hd720

How can I create an executable JAR with dependencies using Maven?

This is the best way i found:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <configuration>
      <archive>
        <manifest>
        <addClasspath>true</addClasspath>
        <mainClass>com.myDomain.etc.MainClassName</mainClass>
        <classpathPrefix>dependency-jars/</classpathPrefix>
        </manifest>
      </archive>
    </configuration>
  </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
            <goal>copy-dependencies</goal>
        </goals>
        <configuration>
            <outputDirectory>
               ${project.build.directory}/dependency-jars/
            </outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>

With this configuration, all dependencies will be located in /dependency-jars. My application has no Main class, just context ones, but one of my dependencies do have a Main class (com.myDomain.etc.MainClassName) that starts the JMX server, and receives a start or a stop parameter. So with this i was able to start my application like this:

java -jar ./lib/TestApp-1.0-SNAPSHOT.jar start

I wait it be useful for you all.

Kotlin - How to correctly concatenate a String

yourString += "newString"

This way you can concatenate a string

inject bean reference into a Quartz job in Spring?

All those solutions above doesn't work for me with Spring 5 and Hibernate 5 and Quartz 2.2.3 when I want to call transactional methods!

I therefore implemented this solution which automatically starts the scheduler and triggers the jobs. I found a lot of that code at dzone. Because I don't need to create triggers and jobs dynamically I wanted the static triggers to be pre defined via Spring Configuration and only the jobs to be exposed as Spring Components.

My basic configuration look like this

@Configuration
public class QuartzConfiguration {

  @Autowired
  ApplicationContext applicationContext;

  @Bean
  public SchedulerFactoryBean scheduler(@Autowired JobFactory jobFactory) throws IOException {
    SchedulerFactoryBean sfb = new SchedulerFactoryBean();

    sfb.setOverwriteExistingJobs(true);
    sfb.setAutoStartup(true);
    sfb.setJobFactory(jobFactory);

    Trigger[] triggers = new Trigger[] {
        cronTriggerTest().getObject()
    };
    sfb.setTriggers(triggers);
    return sfb;
  }

  @Bean
  public JobFactory cronJobFactory() {
    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    return jobFactory;
  }

  @Bean 
  public CronTriggerFactoryBean cronTriggerTest() {
    CronTriggerFactoryBean tfb = new CronTriggerFactoryBean();
    tfb.setCronExpression("0 * * ? * * *");

    JobDetail jobDetail = JobBuilder.newJob(CronTest.class)
                            .withIdentity("Testjob")
                            .build()
                            ;

    tfb.setJobDetail(jobDetail);
    return tfb;
  }

}

As you can see, you have the scheduler and a simple test trigger which is defined via a cron expression. You can obviously choose whatever scheduling expression you like. You then need the AutowiringSpringBeanJobFactory which goes like this

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {

  @Autowired
  private ApplicationContext applicationContext;

  private SchedulerContext schedulerContext;

  @Override
  public void setApplicationContext(final ApplicationContext context) {
    this.applicationContext = context;
  }


  @Override
  protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    Job job = applicationContext.getBean(bundle.getJobDetail().getJobClass());
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);

    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
    pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());

    if (this.schedulerContext != null)
    {
        pvs.addPropertyValues(this.schedulerContext);
    }
    bw.setPropertyValues(pvs, true);

    return job;
  }  

  public void setSchedulerContext(SchedulerContext schedulerContext) {
    this.schedulerContext = schedulerContext;
    super.setSchedulerContext(schedulerContext);
  }

}

In here you wire your normal application context and your job together. This is the important gap because normally Quartz starts it's worker threads which have no connection to your application context. That is the reason why you can't execute Transactional mehtods. The last thing missing is a job. It can look like that

@Component
public class CronTest implements Job {

  @Autowired
  private MyService s;

  public CronTest() {
  }

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    s.execute();
  }

}

It's not a perfect solution because you an extra class only for calling your service method. But nevertheless it works.

Using HttpClient and HttpPost in Android with post parameters

You can actually send it as JSON the following way:

// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);

Run function from the command line

We can write something like this. I have used with python-3.7.x

import sys

def print_fn():
    print("Hi")

def sum_fn(a, b):
    print(a + b)

if __name__ == "__main__":
    args = sys.argv
    # args[0] = current file
    # args[1] = function name
    # args[2:] = function args : (*unpacked)
    globals()[args[1]](*args[2:])

python demo.py print_fn
python demo.py sum_fn 5 8

Group by in LINQ

The following example uses the GroupBy method to return objects that are grouped by PersonID.

var results = persons.GroupBy(x => x.PersonID)
              .Select(x => (PersonID: x.Key, Cars: x.Select(p => p.car).ToList())
              ).ToList();

Or

 var results = persons.GroupBy(
               person => person.PersonID,
               (key, groupPerson) => (PersonID: key, Cars: groupPerson.Select(x => x.car).ToList()));

Or

 var results = from person in persons
               group person by person.PersonID into groupPerson
               select (PersonID: groupPerson.Key, Cars: groupPerson.Select(x => x.car).ToList());

Or you can use ToLookup, Basically ToLookup uses EqualityComparer<TKey>.Default to compare keys and do what you should do manually when using group by and to dictionary. i think it's excuted inmemory

 ILookup<int, string> results = persons.ToLookup(
            person => person.PersonID,
            person => person.car);

Create a string with n characters

Since Java 11 you can simply use String.repeat(count) to solve your problem.

Returns a string whose value is the concatenation of this string repeated count times.

If this string is empty or count is zero then the empty string is returned.

So instead of a loop your code would just look like this:

" ".repeat(length);

Python os.path.join() on a list

The problem is, os.path.join doesn't take a list as argument, it has to be separate arguments.

This is where *, the 'splat' operator comes into play...

I can do

>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'

Safest way to convert float to integer in python?

df['Column_Name']=df['Column_Name'].astype(int)

How to handle the click event in Listview in android?

First, the class must implements the click listenener :

implements OnItemClickListener

Then set a listener to the ListView

yourList.setOnItemclickListener(this);

And finally, create the clic method:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at ",   
 Toast.LENGTH_SHORT).show();
}

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

It looks like the cause of the errors are:

  1. You're currently loading the source file in the src directory instead of the built file in the dist directory (you can see what the intended distributed file is here). This means that you're using the native source code in an unaltered/unbundled state, leading to the following error: Uncaught SyntaxError: Cannot use import statement outside a module. This should be fixed by using the bundled version since the package is using rollup to create a bundle.

  2. The reason you're getting the Uncaught ReferenceError: ms is not defined error is because modules are scoped, and since you're loading the library using native modules, ms is not in the global scope and is therefore not accessible in the following script tag.

It looks like you should be able to load the dist version of this file to have ms defined on the window. Check out this example from the library author to see an example of how this can be done.

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

I faced a similar issue while copying a sheet to another workbook. I prefer to avoid using 'activesheet' though as it has caused me issues in the past. Hence I wrote a function to perform this inline with my needs. I add it here for those who arrive via google as I did:

The main issue here is that copying a visible sheet to the last index position results in Excel repositioning the sheet to the end of the visible sheets. Hence copying the sheet to the position after the last visible sheet sorts this issue. Even if you are copying hidden sheets.

Function Copy_WS_to_NewWB(WB As Workbook, WS As Worksheet) As Worksheet
    'Creates a copy of the specified worksheet in the specified workbook
    '   Accomodates the fact that there may be hidden sheets in the workbook
    
    Dim WSInd As Integer: WSInd = 1
    Dim CWS As Worksheet
    
    'Determine the index of the last visible worksheet
    For Each CWS In WB.Worksheets
        If CWS.Visible Then If CWS.Index > WSInd Then WSInd = CWS.Index
    Next CWS
    
    WS.Copy after:=WB.Worksheets(WSInd)
    Set Copy_WS_to_NewWB = WB.Worksheets(WSInd + 1)

End Function

To use this function for the original question (ie in the same workbook) could be done with something like...

Set test = Copy_WS_to_NewWB(Workbooks(1), Workbooks(1).Worksheets(1))
test.name = "test sheet name"

EDIT 04/11/2020 from –user3598756 Adding a slight refactoring of the above code

Function CopySheetToWorkBook(targetWb As Workbook, shToBeCopied As Worksheet, copiedSh As Worksheet) As Boolean
    'Creates a copy of the specified worksheet in the specified workbook
    '   Accomodates the fact that there may be hidden sheets in the workbook

    Dim lastVisibleShIndex As Long
    Dim iSh As Long

    On Error GoTo SafeExit
    
    With targetWb
        'Determine the index of the last visible worksheet
        For iSh = .Sheets.Count To 1 Step -1
            If .Sheets(iSh).Visible Then
                lastVisibleShIndex = iSh
                Exit For
            End If
        Next
    
        shToBeCopied.Copy after:=.Sheets(lastVisibleShIndex)
        Set copiedSh = .Sheets(lastVisibleShIndex + 1)
    End With
    
    CopySheetToWorkBook = True
    Exit Function
    
SafeExit:
    
End Function

other than using different (more descriptive?) variable names, the refactoring manily deals with:

  1. turning the Function type into a `Boolean while including returned (copied) worksheet within function parameters list this, to let the calling Sub hande possible errors, like

     Dim WB as Workbook: Set WB = ThisWorkbook ' as an example
     Dim sh as Worksheet: Set sh = ActiveSheet ' as an example
     Dim copiedSh as Worksheet
     If CopySheetToWorkBook(WB, sh, copiedSh) Then
         ' go on with your copiedSh sheet
     Else
         Msgbox "Error while trying to copy '" & sh.Name & "'" & vbcrlf & err.Description
     End If
    
  2. having the For - Next loop stepping from last sheet index backwards and exiting at first visible sheet occurence, since we're after the "last" visible one

GIT commit as different user without email / or only email

The specific format is:

git commit --author="John Doe <[email protected]>" -m "Impersonation is evil." 

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

"SSL certificate verify failed" using pip to install packages

It seems that Scrapy fails because installing Twisted fails, which fails because incremental fails. Running pip install --upgrade pip && pip install --upgrade incremental fixed this for me.

What are the differences between a multidimensional array and an array of arrays in C#?

Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.

If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.

Consider the following methods:

static void SetElementAt(int[][] array, int i, int j, int value)
{
    array[i][j] = value;
}

static void SetElementAt(int[,] array, int i, int j, int value)
{
    array[i, j] = value;
}

Their IL will be the following:

.method private hidebysig static void  SetElementAt(int32[][] 'array',
                                                    int32 i,
                                                    int32 j,
                                                    int32 'value') cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldelem.ref
  IL_0003:  ldarg.2
  IL_0004:  ldarg.3
  IL_0005:  stelem.i4
  IL_0006:  ret
} // end of method Program::SetElementAt

.method private hidebysig static void  SetElementAt(int32[0...,0...] 'array',
                                                    int32 i,
                                                    int32 j,
                                                    int32 'value') cil managed
{
  // Code size       10 (0xa)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldarg.2
  IL_0003:  ldarg.3
  IL_0004:  call       instance void int32[0...,0...]::Set(int32,
                                                           int32,
                                                           int32)
  IL_0009:  ret
} // end of method Program::SetElementAt

When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.

How do I do a HTTP GET in Java?

The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

Load and execute external js file in node.js with access to local variables?

Expanding on @Shripad's and @Ivan's answer, I would recommend that you use Node.js's standard module.export functionality.

In your file for constants (e.g. constants.js), you'd write constants like this:

const CONST1 = 1;
module.exports.CONST1 = CONST1;

const CONST2 = 2;
module.exports.CONST2 = CONST2;

Then in the file in which you want to use those constants, write the following code:

const {CONST1 , CONST2} = require('./constants.js');

If you've never seen the const { ... } syntax before: that's destructuring assignment.

Presenting a UIAlertController properly on an iPad using iOS 8

You can present a UIAlertController from a popover by using UIPopoverPresentationController.

In Obj-C:

UIViewController *self; // code assumes you're in a view controller
UIButton *button; // the button you want to show the popup sheet from

UIAlertController *alertController;
UIAlertAction *destroyAction;
UIAlertAction *otherAction;

alertController = [UIAlertController alertControllerWithTitle:nil
                                                      message:nil
                           preferredStyle:UIAlertControllerStyleActionSheet];
destroyAction = [UIAlertAction actionWithTitle:@"Remove All Data"
                                         style:UIAlertActionStyleDestructive
                                       handler:^(UIAlertAction *action) {
                                           // do destructive stuff here
                                       }];
otherAction = [UIAlertAction actionWithTitle:@"Blah"
                                       style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction *action) {
                                         // do something here
                                     }];
// note: you can control the order buttons are shown, unlike UIActionSheet
[alertController addAction:destroyAction];
[alertController addAction:otherAction];
[alertController setModalPresentationStyle:UIModalPresentationPopover];

UIPopoverPresentationController *popPresenter = [alertController 
                                              popoverPresentationController];
popPresenter.sourceView = button;
popPresenter.sourceRect = button.bounds;
[self presentViewController:alertController animated:YES completion:nil];

Editing for Swift 4.2, though there are many blogs available for the same but it may save your time to go and search for them.

if let popoverController = yourAlert.popoverPresentationController {
    popoverController.sourceView = self.view //to set the source of your alert
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // you can set this as per your requirement.
    popoverController.permittedArrowDirections = [] //to hide the arrow of any particular direction
}