Programs & Examples On #Numeric keypad

keyCode values for numeric keypad?

The keycodes are different. Keypad 0-9 is Keycode 96 to 105

Your if statement should be:

if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) { 
  // 0-9 only
}

Here's a reference guide for keycodes


-- UPDATE --

This is an old answer and keyCode has been deprecated. There are now alternative methods to achieve this, such as using key:

if ((e.key >= 48 && e.key <= 57) || (e.key >= 96 && e.key <= 105)) { 
  // 0-9 only
}

Here's an output tester for event.key, thanks to @Danziger for the link.

Mercurial undo last commit

after you have pulled and updated your workspace do a thg and right click on the change set you want to get rid of and then click modify history -> strip, it will remove the change set and you will point to default tip.

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

How to use the toString method in Java?

From the Object.toString docs:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Example:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());

output:- mystr.toString: [Ljava.lang.String;@13aaa14a

How to make/get a multi size .ico file?

Visual Studio Resource Editor (free as VS 2013 Community edition) can import PNG (and other formats) and export ICO.

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

When to use .First and when to use .FirstOrDefault with LINQ?

This type of the function belongs to element operators. Some useful element operators are defined below.

  1. First/FirstOrDefault
  2. Last/LastOrDefault
  3. Single/SingleOrDefault

We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.

  List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };

First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.

int result = items.Where(item => item == 2).First();

FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.

int result1 = items.Where(item => item == 2).FirstOrDefault();

How do I find out my python path using python?

PYTHONPATH is an environment variable whose value is a list of directories. Once set, it is used by Python to search for imported modules, along with other std. and 3rd-party library directories listed in Python's "sys.path".

As any other environment variables, you can either export it in shell or in ~/.bashrc, see here. You can query os.environ['PYTHONPATH'] for its value in Python as shown below:

$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"

IF defined in shell as

$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite

THEN result =>

/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

ELSE result =>

PYTHONPATH is not defined

To set PYTHONPATH to multiple paths, see here.

Note that one can add or delete a search path via sys.path.insert(), del or remove() at run-time, but NOT through os.environ[]. Example:

>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> 

In summary, PYTHONPATH is one way of specifying the Python search path(s) for imported modules in sys.path. You can also apply list operations directly to sys.path without the aid of PYTHONPATH.

Excel: How to check if a cell is empty with VBA?

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

How to initialize a two-dimensional array in Python?

This way is faster than the nested list comprehensions

[x[:] for x in [[foo] * 10] * 10]    # for immutable foo!

Here are some python3 timings, for small and large lists

$python3 -m timeit '[x[:] for x in [[1] * 10] * 10]'
1000000 loops, best of 3: 1.55 usec per loop

$ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]'
100000 loops, best of 3: 6.44 usec per loop

$ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]'
100 loops, best of 3: 5.5 msec per loop

$ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]'
10 loops, best of 3: 27 msec per loop

Explanation:

[[foo]*10]*10 creates a list of the same object repeated 10 times. You can't just use this, because modifying one element will modify that same element in each row!

x[:] is equivalent to list(X) but is a bit more efficient since it avoids the name lookup. Either way, it creates a shallow copy of each row, so now all the elements are independent.

All the elements are the same foo object though, so if foo is mutable, you can't use this scheme., you'd have to use

import copy
[[copy.deepcopy(foo) for x in range(10)] for y in range(10)]

or assuming a class (or function) Foo that returns foos

[[Foo() for x in range(10)] for y in range(10)]

How to set Status Bar Style in Swift 3

To add to the great asnwer by @Krunal https://stackoverflow.com/a/49552326/4697535

In case you are using a UINavigationController, the preferredStatusBarStyle will have no effect on the UIViewController.

Xcode 10 and Swift 4.

Set a custom UINavigationController

Example:

class LightNavigationController: UINavigationController {

   open override var preferredStatusBarStyle: UIStatusBarStyle {
       return .lightContent
   }
}

Use an extension for an app level solution:

extension UINavigationController {

  open override var preferredStatusBarStyle: UIStatusBarStyle {
      guard let index = tabBarController?.selectedIndex else { return .default }
      switch index {
      case 0, 1, 2: return .lightContent // set lightContent for tabs 0-2
      default: return .default // set dark for tab 3
      }
  }
}

How to set custom header in Volley Request

try this

{
    @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           String bearer = "Bearer ".concat(token);
            Map<String, String> headersSys = super.getHeaders();
            Map<String, String> headers = new HashMap<String, String>();
            headersSys.remove("Authorization");
            headers.put("Authorization", bearer);
            headers.putAll(headersSys);
            return headers;
       }
};

Response.Redirect with POST instead of Get?

PostbackUrl can be set on your asp button to post to a different page.

if you need to do it in codebehind, try Server.Transfer.

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

You have the wrong URL.

I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the Microsoft SQL Server JDBC Driver 2.0. You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is JDBC 4.0]

Check the release notes. For this driver, you want:

URL:  jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver

It seems you have the class name correct, but the URL wrong.

Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.

For all subsequent drivers, the URL changed to the form I have here.

This is in the release notes for the JDBC driver.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

When to use static keyword before global variables?

Yes, use static

Always use static in .c files unless you need to reference the object from a different .c module.

Never use static in .h files, because you will create a different object every time it is included.

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

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

javascript change background color on click

you can do this---

<input type="button" onClic="changebackColor">

function changebackColor(){
document.body.style.backgroundColor = "black";
document.getElementByID("divID").style.backgroundColor = "black";      
window.setTimeout("yourFunction()",10000);
}

How to convert a String to CharSequence?

CharSequence is an interface and String is its one of the implementations other than StringBuilder, StringBuffer and many other.

So, just as you use InterfaceName i = new ItsImplementation(), you can use CharSequence cs = new String("string") or simply CharSequence cs = "string";

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

SQL Server Restore Error - Access is Denied

lost a couple of hours to this problem too. got it going though:

"access denied" in my case really did mean "access denied". mssqlstudio's user account on my windows device did NOT have full control of the folder specified in the error message. i gave it full control. access was no longer denied and the restore succeeded.

why was the folder locked up for studio ? who knows ? i got enough questions to deal with as it is without trying to answer more.

VBA test if cell is in a range

Determine if a cell is within a range using VBA in Microsoft Excel:

From the linked site (maintaining credit to original submitter):

VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    ' returns True if Range1 is within Range2
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function


Sub TestInRange()
    If InRange(ActiveCell, Range("A1:D100")) Then
        ' code to handle that the active cell is within the right range
        MsgBox "Active Cell In Range!"
    Else
        ' code to handle that the active cell is not within the right range
        MsgBox "Active Cell NOT In Range!"
    End If
End Sub

Ruby, remove last N characters from a string?

You can always use something like

 "string".sub!(/.{X}$/,'')

Where X is the number of characters to remove.

Or with assigning/using the result:

myvar = "string"[0..-X]

where X is the number of characters plus one to remove.

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

After a lot of googling and trying all above...the only thing that solved my problem was this command:

$install_name_tool -id /usr/local/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

I am using a macbook pro, OSX 10 El Capitan. Darwin xxxx-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 23 18:25:34 PDT 2016; XXX:xnu-3248.60.10~1/RELEASE_X86_64 x86_64 Perl:v5.18.2 Mysql:5.6.19

Python `if x is not None` or `if not x is None`?

Personally, I use

if not (x is None):

which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.

Delete specific values from column with where condition?

UPDATE YourTable SET columnName = null WHERE YourCondition

Is there a simple way to use button to navigate page as a link does in angularjs

 <a type="button" href="#/new-page.html" class="btn btn-lg btn-success" >New Page</a>

Simple...

Inserting a tab character into text using C#

When using literal strings (start with @") this might be easier

char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);

Would result in Apple:<tab>Bob

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

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

same example

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

with

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

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

TS1086: An accessor cannot be declared in ambient context

Setting "skipLibCheck": true in tsconfig.json solved my problem

"compilerOptions": {
    "skipLibCheck": true
}

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

android: stretch image in imageview to fit screen

Trying using :

imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_CENTER);

This will fit your imageview to the screen with the correct ratio.

How to merge two PDF files into one in Java?

Multiple pdf merged method using org.apache.pdfbox:

public void mergePDFFiles(List<File> files,
                          String mergedFileName) {
    try {
        PDFMergerUtility pdfmerger = new PDFMergerUtility();
        for (File file : files) {
            PDDocument document = PDDocument.load(file);
            pdfmerger.setDestinationFileName(mergedFileName);
            pdfmerger.addSource(file);
            pdfmerger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
            document.close();
        }
    } catch (IOException e) {
        logger.error("Error to merge files. Error: " + e.getMessage());
    }
}

From main program, call mergePDFFiles method using list of files and target file name.

        String mergedFileName = "Merged.pdf";
        mergePDFFiles(files, mergedFileName);

After calling mergePDFFiles, load merged file

        File mergedFile = new File(mergedFileName);

How to check radio button is checked using JQuery?


//the following code checks if your radio button having name like 'yourRadioName' 
//is checked or not
$(document).ready(function() {
  if($("input:radio[name='yourRadioName']").is(":checked")) {
      //its checked
  }
});

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

How to get substring from string in c#?

var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";

var result = data.Split(new[] {'.'}, 1)[0];

Output:

Retrieves a substring from this instance. The substring starts at a specified character position.

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

How to show what a commit did?

Does

$ git log -p

do what you need?

Check out the chapter on Git Log in the Git Community Book for more examples. (Or look at the the documentation.)

Update: As others (Jakub and Bombe) already pointed out: although the above works, git show is actually the command that is intended to do exactly what was asked for.

Can I pass a JavaScript variable to another browser window?

Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".

How to insert data into elasticsearch

You have to install the curl binary in your PC first. You can download it from here.

After that unzip it into a folder. Lets say C:\curl. In that folder you'll find curl.exe file with several .dll files.

Now open a command prompt by typing cmd from the start menu. And type cd c:\curl on there and it will take you to the curl folder. Now execute the curl command that you have.

One thing, windows doesn't support single quote around around the fields. So you have to use double quotes. For example I have converted your curl command like appropriate one.

curl -H "Content-Type: application/json" -XPOST "http://localhost:9200/indexname/typename/optionalUniqueId" -d "{ \"field\" : \"value\"}"

How to split an integer into an array of digits?

return array as string

>>> list(str(12345))
['1', '2', '3', '4', '5']

return array as integer

>>> map(int,str(12345))
[1, 2, 3, 4, 5]

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

Popup window in PHP?

For a popup javascript is required. Put this in your header:

<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>

And this in your body:

<input type="button" onclick="myFunction()" value="Show alert box">

When the button is pressed a box pops up with the message set in the header.

This can be put in any html or php file without the php tags.

-----EDIT-----

To display it using php try this:

<?php echo '<script>myfunction()</script>'; ?>

It may not be 100% correct but the principle is the same.

To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

How to change facebook login button with my custom image

The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -

  1. Create a simple anchor tag link with the image you want to show. Have a onclick method on anchor tag which would actually do the real job.
<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
  1. Next, we create the Javascript function which will show the actual popup and will fetch the complete user information, if user allows. We also handle the scenario if user disallows our facebook app.
window.fbAsyncInit = function() {
    FB.init({
        appId   : 'YOUR_APP_ID',
        oauth   : true,
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
    });

  };

function fb_login(){
    FB.login(function(response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function(response) {
                user_email = response.email; //get user email
          // you can store this data into your database             
            });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'public_profile,email'
    });
}
(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());
  1. We are done.

Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.

Alternate table with new not null Column in existing table in SQL

There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

Remove end of line characters from Java string

You can either directly pass line terminator e.g. \n, if you know the line terminator in Windows, Mac or UNIX. Alternatively you can use following code to replace line breaks in either of three major operating system.

str = str.replaceAll("\\r\\n|\\r|\\n", " ");

Above code line will replace line breaks with space in Mac, Windows and Linux. Also you can use line-separator. It will work for all OS. Below is the code snippet for line-separator.

String lineSeparator=System.lineSeparator();
String newString=yourString.replace(lineSeparator, "");

Multiple radio button groups in MVC 4 Razor

I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No

How do write IF ELSE statement in a MySQL query

You're looking for case:

case when action = 2 and state = 0 then 1 else 0 end as state

MySQL has an if syntax (if(action=2 and state=0, 1, 0)), but case is more universal.

Note that the as state there is just aliasing the column. I'm assuming this is in the column list of your SQL query.

How to get unique values in an array

These days, you can use ES6's Set data type to convert your array to a unique Set. Then, if you need to use array methods, you can turn it back into an Array:

var arr = ["a", "a", "b"];
var uniqueSet = new Set(arr); // {"a", "b"}
var uniqueArr = Array.from(uniqueSet); // ["a", "b"]
//Then continue to use array methods:
uniqueArr.join(", "); // "a, b"

How to delete Project from Google Developers Console

I found when I accessed here https://console.cloud.google.com/home/dashboard

Then I got redirected to my active project, which was something like https://console.cloud.google.com/home/dashboard?project={THE_ID_OF_YOUR_PROJECT}

Then right bellow the project info, there was this Manage Options (note: I'm using Portuguese language here "Gerenciar as configurações do projeto" means "Manage project settings")

enter image description here

Then, finally, the delete option ("Excluir Projeto" means Delete Project)

enter image description here

Yep, it was hard

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

I experienced the same problem as the OP after right-clicking on my project and selecting Close Unrelated Projects.

In my case, I resolved the problem by re-opening the appcompat_v7 project and cleaning/rebuilding both projects.

Java URL encoding of query string parameters

URL url= new URL("http://example.com/query?q=random word £500 bank $");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String correctEncodedURL=uri.toASCIIString(); 
System.out.println(correctEncodedURL);

Prints

http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$

What is happening here?

1. Split URL into structural parts. Use java.net.URL for it.

2. Encode each structural part properly!

3. Use IDN.toASCII(putDomainNameHere) to Punycode encode the host name!

4. Use java.net.URI.toASCIIString() to percent-encode, NFC encoded unicode - (better would be NFKC!). For more info see: How to encode properly this URL

In some cases it is advisable to check if the url is already encoded. Also replace '+' encoded spaces with '%20' encoded spaces.

Here are some examples that will also work properly

{
      "in" : "http://???????.com/",
     "out" : "http://xn--mgba3gch31f.com/"
},{
     "in" : "http://www.example.com/?/foo",
     "out" : "http://www.example.com/%E2%80%A5/foo"
},{
     "in" : "http://search.barnesandnoble.com/booksearch/first book.pdf", 
     "out" : "http://search.barnesandnoble.com/booksearch/first%20book.pdf"
}, {
     "in" : "http://example.com/query?q=random word £500 bank $", 
     "out" : "http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$"
}

The solution passes around 100 of the testcases provided by Web Plattform Tests.

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How to upload a project to Github

What you need it an SSH connection and GitHub init into your project. I will explain under Linux machine.

Let's start with some easy stuff: navigate into your project in the terminal, and use:

git init
git add .
git commit 

now let's add SSH into your machine: use ssh-keygen -t rsa -C "[email protected]" and copy the public key, then add it to your GitHub repo Deploy keys -> add one back to your machine project now launch: git push origin master if there is an error config your .github/config by nano .github/config and change the URL to ssh one by url = [email protected]:username/repo.... and that's it

App store link for "rate/review this app"

Starting in iOS 10.3:

import StoreKit

func someFunction() {
 SKStoreReviewController.requestReview()
}

but its has been just released with 10.3, so you will still need some fallback method for older versions as described above

How to open a new tab in GNOME Terminal from command line?

#!/bin/sh

WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID

This will auto determine the corresponding terminal and opens the tab accordingly.

Create XML file using java

Have look at dom4j or jdom. Both libraries allow creating a Document and allow printing the document as xml. Both are widly used, pretty easy to use and you'll find a lot of examples and snippets.

dom4j - Quick start guide

How to get the Full file path from URI

  public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

Using this method we can get string filepath from Uri.

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

How do you generate a random double uniformly distributed between 0 and 1 from C++?

In C++11 and C++14 we have much better options with the random header. The presentation rand() Considered Harmful by Stephan T. Lavavej explains why we should eschew the use of rand() in C++ in favor of the random header and N3924: Discouraging rand() in C++14 further reinforces this point.

The example below is a modified version of the sample code on the cppreference site and uses the std::mersenne_twister_engine engine and the std::uniform_real_distribution which generates numbers in the [0,1) range (see it live):

#include <iostream>
#include <iomanip>
#include <map>
#include <random>

int main()
{
    std::random_device rd;


    std::mt19937 e2(rd());

    std::uniform_real_distribution<> dist(0, 1);

    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::round(dist(e2))];
    }

    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}

output will be similar to the following:

0 ************************
1 *************************

Since the post mentioned that speed was important then we should consider the cppreference section that describes the different random number engines (emphasis mine):

The choice of which engine to use involves a number of tradeoffs*: the **linear congruential engine is moderately fast and has a very small storage requirement for state. The lagged Fibonacci generators are very fast even on processors without advanced arithmetic instruction sets, at the expense of greater state storage and sometimes less desirable spectral characteristics. The Mersenne twister is slower and has greater state storage requirements but with the right parameters has the longest non-repeating sequence with the most desirable spectral characteristics (for a given definition of desirable).

So if there is a desire for a faster generator perhaps ranlux24_base or ranlux48_base are better choices over mt19937.

rand()

If you forced to use rand() then the C FAQ for a guide on How can I generate floating-point random numbers?, gives us an example similar to this for generating an on the interval [0,1):

#include <stdlib.h>

double randZeroToOne()
{
    return rand() / (RAND_MAX + 1.);
}

and to generate a random number in the range from [M,N):

double randMToN(double M, double N)
{
    return M + (rand() / ( RAND_MAX / (N-M) ) ) ;  
}

Moving from one activity to another Activity in Android

Below code is working fine with Android 4.3:

Intent i = new Intent(this,MainActivity2.class);
startActivity(i);

MySql : Grant read only options?

If you want the view to be read only after granting the read permission you can use the ALGORITHM = TEMPTABLE in you view DDL definition.

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

How to select between brackets (or quotes or ...) in Vim?

For selecting within single quotes use vi'.

For selecting within parenthesis use vi(.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

Custom style to jquery ui dialogs

You can specify a custom class to the top element of the dialog via the option dialogClass

$("#success").dialog({
    ...
    dialogClass:"myClass",
    ...
});

Then you can target this class in CSS via .myClass.ui-dialog.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Found a likely answer in /jstillwell's posts here: https://github.com/stefanocudini/leaflet-gps/issues/15 basically this feature will not be supported (in Chrome only?) in the future, but only for HTTP sites. HTTPS will still be ok, and there are no plans to create an equivalent replacement for HTTP use.

Combine or merge JSON on node.js without jQuery

Use spread operator. It is supported in Node since version 8.6

_x000D_
_x000D_
const object1 = {name: "John"};_x000D_
const object2 = {location: "San Jose"};_x000D_
_x000D_
const obj = {...object1, ...object2}_x000D_
_x000D_
console.log(obj)_x000D_
//   {_x000D_
//     "name": "John",_x000D_
//     "location": "San Jose"_x000D_
//   }
_x000D_
_x000D_
_x000D_

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

Java Embedded Databases Comparison

If I am correct H2 is from the same guys who wrote HSQLDB. Its a lot better if you trust the benchmarks on their site. Also, there is some notion that sun community jumped too quickly into Derby.

Get data from JSON file with PHP

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Using Express Middleware works great for me. If you are already using Express, just add the following middleware rules. It should start working.

app.all("/api/*", function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
  return next();
});

app.all("/api/*", function(req, res, next) {
  if (req.method.toLowerCase() !== "options") {
    return next();
  }
  return res.send(204);
});

Reference

Cookie blocked/not saved in IFRAME in Internet Explorer

Anyone having this problem in node.js.

Then add this p3p module, and enable this module at middleware.

npm install p3p

I am using express so I add it in app.js

First require that module in app.js

var express = require('express');
var app = express();
var p3p = require('p3p');

then use it as middleware

app.use(p3p(p3p.recommended));

It will add p3p headers at res object. No need to do any extra things.

You will get more info at:

https://github.com/troygoode/node-p3p

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

I suffered from this recently, and in my case I traced the problem back to something I was doing when testing: changing the system time. I'm not suggesting this is the case for everyone, but thought I'd mention it since it hasn't been mentioned already. It appears if you start moving the clock around between debug builds then it can get very confused about what order various files have been created it - I can only assume it is using file modified dates to determine if the source code is valid or not, and which binaries it needs to recompile.

It is also an option to re-save web.config to bump its modification time.

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

How to delete all data from solr and hbase

Use the "match all docs" query in a delete by query command: :

You must also commit after running the delete so, to empty the index, run the following two commands:

curl http://localhost:8983/solr/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'

curl http://localhost:8983/solr/update --data '<commit/>' -H 'Content-type:text/xml; charset=utf-8'

What's the best way to add a drop shadow to my UIView

On viewWillLayoutSubviews:

override func viewWillLayoutSubviews() {
    sampleView.layer.masksToBounds =  false
    sampleView.layer.shadowColor = UIColor.darkGrayColor().CGColor;
    sampleView.layer.shadowOffset = CGSizeMake(2.0, 2.0)
    sampleView.layer.shadowOpacity = 1.0
}

Using Extension of UIView:

extension UIView {

    func addDropShadowToView(targetView:UIView? ){
        targetView!.layer.masksToBounds =  false
        targetView!.layer.shadowColor = UIColor.darkGrayColor().CGColor;
        targetView!.layer.shadowOffset = CGSizeMake(2.0, 2.0)
        targetView!.layer.shadowOpacity = 1.0
    }
}

Usage:

sampleView.addDropShadowToView(sampleView)

Custom sort function in ng-repeat

The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.

e.g. Given the following assignment:

$scope.cards = {
  "card2": {
    values: {
      opt1: 9,
      opt2: 12
    }
  },
  "card1": {
    values: {
      opt1: 9,
      opt2: 11
    }
  }
};

and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.

To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.

myApp.filter('orderByValue', function () {
  // custom value function for sorting
  function myValueFunction(card) {
    return card.values.opt1 + card.values.opt2;
  }

  return function (obj) {
    var array = [];
    Object.keys(obj).forEach(function (key) {
      // inject key into each object so we can refer to it from the template
      obj[key].name = key;
      array.push(obj[key]);
    });
    // apply a custom sorting function
    array.sort(function (a, b) {
      return myValueFunction(b) - myValueFunction(a);
    });
    return array;
  };
});

We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.

<ul ng-repeat="card in cards | orderByValue">
    <li>{{card.name}} {{value(card)}}</li>
</ul>

Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/

Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332

Python unexpected EOF while parsing

What you can try is writing your code as normal for python using the normal input command. However the trick is to add at the beginning of you program the command input=raw_input.

Now all you have to do is disable (or enable) depending on if you're running in Python/IDLE or Terminal. You do this by simply adding '#' when needed.

Switched off for use in Python/IDLE

    #input=raw_input 

And of course switched on for use in terminal.

    input=raw_input 

I'm not sure if it will always work, but its a possible solution for simple programs or scripts.

Min and max value of input in angular4 application

[I assume the reader has basic knowledge of Angular2+ and Forms]

It is easy to show a numerical input and put the limits, but you have to also take care of things may happen out of your predictions.

  1. Implement the tag in your 'html':
<input type="number" [min]="0.00" [max]="100.00" [step]="0.01" formControlName="rateFC">
  1. But as Adrien said, still user can enter manually a wrong number. You can validate input by Validators easily. In your '.ts':
import { FormGroup, FormControl, Validators } from '@angular/forms';

//many other things...

this.myFG = new FormGroup({
   //other form controls...,
   rateFC  : new FormControl(0, [Validators.min(0), Validators.max(100)])
});
  1. Up to now everything is ok, but it is better to let the user know the input is wrong, then draw a red line around the invalid input element by adding to your style:
.form-control.ng-touched.ng-invalid{
    border:2px solid red;
}
  1. And to make it perfect, prevent the user to submit the wrong data.
<button type="submit" [disabled]="!myFG.valid">Submit</button>

How to convert .crt to .pem

I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.

openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text

Is it possible to start activity through adb shell?

adb shell am broadcast -a android.intent.action.xxx

Mention xxx as the action that you mentioned in the manifest file.

Text Editor For Linux (Besides Vi)?

Alternative text editors? Try Diakonos, "a Linux editor for the masses". The default keyboard mapping is as expected for cut, copy, paste, undo, open, save, etc.

Remove a child with a specific attribute, in SimpleXML for PHP

Your initial approach was right, but you forgot one little thing about foreach. It doesn't work on the original array/object, but creates a copy of each element as it iterates, so you did unset the copy. Use reference like this:

foreach($doc->seg as &$seg) 
{
    if($seg['id'] == 'A12')
    {
        unset($seg);
    }
}

Check if url contains string with JQuery

if(window.location.href.indexOf("?added-to-cart=555") >= 0)

It's window.location.href, not window.location.

Looping through the content of a file in Bash

I like to use xargs instead of while. xargs is powerful and command line friendly

cat peptides.txt | xargs -I % sh -c "echo %"

With xargs, you can also add verbosity with -t and validation with -p

"undefined" function declared in another file?

If you're using go run, do go run *.go. It will automatically find all go files in the current working directory, compile and then run your main function.

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Count the cells with same color in google spreadsheet

The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells. You can find a detailed description here: Google Script count coloured with reference, but the code is below:

function countColoured(reference) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
  try {
    if (args.length == 1) {
      var range = sheet.getRange(args[0]);
    }
    else {
      sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
      range = sheet.getRange(args[1]);
    }
  }
  catch(e) {
    throw new Error(args.join('!') + ' is not a valid range');
  }
  var c = 0;
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
    }
  }
  return c > 0 ? c : "" ;
}

OpenCV & Python - Image too big to display

Looks like opencv lib is pretty sensitive to parameters passed to the methods. The following code worked for me using opencv 4.3.0:

win_name = "visualization"  #  1. use var to specify window name everywhere
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)  #  2. use 'normal' flag
img = cv2.imread(filename)
h,w = img.shape[:2]  #  suits for image containing any amount of channels
h = int(h / resize_factor)  #  one must compute beforehand
w = int(w / resize_factor)  #  and convert to INT
cv2.resizeWindow(win_name, w, h)  #  use variables defined/computed BEFOREHAND
cv2.imshow(win_name, img)

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

Push to GitHub without a password using ssh-key

Using the command line:

Enter ls -al ~/.ssh to see if existing SSH keys are present.

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

ssh-keygen -t rsa -b 4096 -C "[email protected]"

step 2.

Enter a file in which to save the key (/Users/you/.ssh/id_rsa): <here is file name and enter the key>

step 3.

Enter passphrase (empty for no passphrase): [Type a password]

Enter same passphrase again: [Type password again]

How can I check the extension of a file?

os.path provides many functions for manipulating paths/filenames. (docs)

os.path.splitext takes a path and splits the file extension from the end of it.

import os

filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]

for fp in filepaths:
    # Split the extension from the path and normalise it to lowercase.
    ext = os.path.splitext(fp)[-1].lower()

    # Now we can simply use == to check for equality, no need for wildcards.
    if ext == ".mp3":
        print fp, "is an mp3!"
    elif ext == ".flac":
        print fp, "is a flac file!"
    else:
        print fp, "is an unknown file format."

Gives:

/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!

rand() returns the same number each time the program is run

random functions like borland complier

using namespace std;

int sys_random(int min, int max) {
   return (rand() % (max - min+1) + min);
}

void sys_randomize() {
    srand(time(0));
}

How can I delete a newline if it is the last character in a file?

I had a similar problem, but was working with a windows file and need to keep those CRLF -- my solution on linux:

sed 's/\r//g' orig | awk '{if (NR>1) printf("\r\n"); printf("%s",$0)}' > tweaked

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

Add the following to your /etc/bashrc file. This script adds a resident "function" instead of an alias called "confirm".


function confirm( )
{
#alert the user what they are about to do.
echo "About to $@....";
#confirm with the user
read -r -p "Are you sure? [Y/n]" response
case "$response" in
    [yY][eE][sS]|[yY]) 
              #if yes, then execute the passed parameters
               "$@"
               ;;
    *)
              #Otherwise exit...
              echo "ciao..."
              exit
              ;;
esac
}

Visual Studio Code Search and Replace with Regular Expressions

So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:

Visual studio code's search & replace tab If you mean to disable the code, you just have to put <h1> in search, and replace to ####.

But if you want to use this regex instead, you may enable it in the icon: .* and use the regex: <h1>(.+?)<\/h1> and replace to: #### $1.

And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:

Value cannot be null. Parameter name: source

And, in my case, I mistakenly define my two different columns as identities on DbContext configurations like below,

builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.Id).UseSqlServerIdentityColumn(); //History Id should use identity column in this example

When I correct it like below,

builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.HistoryId).UseSqlServerIdentityColumn();

I have also got rid of this error.

How to link to apps on the app store

According to Apple's latest document You need to use

appStoreLink = "https://itunes.apple.com/us/app/apple-store/id375380948?mt=8"  

or

SKStoreProductViewController 

Tooltip with HTML content without JavaScript

This one is very interesting,

HTML and CSS only

_x000D_
_x000D_
.help-tip {_x000D_
  position: absolute;_x000D_
  top: 18px;_x000D_
  left: 18px;_x000D_
  text-align: center;_x000D_
  background-color: #BCDBEA;_x000D_
  border-radius: 50%;_x000D_
  width: 24px;_x000D_
  height: 24px;_x000D_
  font-size: 14px;_x000D_
  line-height: 26px;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.help-tip:before {_x000D_
  content: '?';_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.help-tip:hover span {_x000D_
  display: block;_x000D_
  transform-origin: 100% 0%;_x000D_
  -webkit-animation: fadeIn 0.3s ease-in-out;_x000D_
  animation: fadeIn 0.3s ease-in-out;_x000D_
}_x000D_
_x000D_
.help-tip span {_x000D_
  display: none;_x000D_
  text-align: left;_x000D_
  background-color: #1E2021;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  position: absolute;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);_x000D_
  left: -4px;_x000D_
  color: #FFF;_x000D_
  font-size: 13px;_x000D_
  line-height: 1.4;_x000D_
}_x000D_
_x000D_
.help-tip span:before {_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border: 6px solid transparent;_x000D_
  border-bottom-color: #1E2021;_x000D_
  left: 10px;_x000D_
  top: -12px;_x000D_
}_x000D_
_x000D_
.help-tip span:after {_x000D_
  width: 100%;_x000D_
  height: 40px;_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: -40px;_x000D_
  left: 0;_x000D_
}
_x000D_
<span class="help-tip">_x000D_
     <span > This is the inline help tip! </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How can I get a precise time, for example in milliseconds in Objective-C?

Also, here is how to calculate a 64-bit NSNumber initialized with the Unix epoch in milliseconds, in case that is how you want to store it in CoreData. I needed this for my app which interacts with a system that stores dates this way.

  + (NSNumber*) longUnixEpoch {
      return [NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970] * 1000];
  }

Is it possible to auto-format your code in Dreamweaver?

ctrl+a->(click)commands->cleanup word HTML

Carousel with Thumbnails in Bootstrap 3.0

@Skelly 's answer is correct. It won't let me add a comment (<50 rep)... but to answer your question on his answer: In the example he linked, if you add

col-xs-3 

class to each of the thumbnails, like this:

class="col-md-3 col-xs-3"

then it should stay the way you want it when sized down to phone width.

Is returning out of a switch statement considered a better practice than using break?

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.

How to get the number of characters in a std::string?

Simplest way to get length of string without bothering about std namespace is as follows

string with/without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    getline(cin,str);
    cout<<"Length of given string is"<<str.length();
    return 0;
}

string without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<"Length of given string is"<<str.length();
    return 0;
}

What do these three dots in React do?

The spread operator is three dots (...) that perform several different tasks. First, the spread operator allows us to combine the contents of arrays.

var peaks = ["Tallac", "Ralston", "Rose"]
var canyons = ["Ward", "Blackwood"]
var tahoe = [...peaks, ...canyons]
console.log(tahoe.join(', ')) // Tallac, Ralston, Rose, Ward, Blackwood

The spread operator can also be used to get some, or the rest, of the items in the array:

var lakes = ["Donner", "Marlette", "Fallen Leaf", "Cascade"]
var [first, ...rest] = lakes
console.log(rest.join(", ")) // "Marlette, Fallen Leaf, Cascade"

We can also use the spread operator to collect function arguments as an array.

function directions(...args) {
    var [start, ...remaining] = args
    var [finish, ...stops] = remaining.reverse()
    console.log(start, finish)
}

The spread operator can also be used for objects.

var morning = {
    breakfast: "oatmeal",
    lunch: "peanut butter and jelly"
}
var dinner = "mac and cheese"
var backpackingMeals = {
    ...morning,
    dinner
}
console.log(backpackingMeals) // {breakfast: "oatmeal", lunch: "peanut butter and jelly", dinner: "mac and cheese"}

Ref: Learning React: Functional Web Development with React and Redux by Alex Banks, Eve Porcello

Android Fragments and animation

I solve this the way Below

Animation anim = AnimationUtils.loadAnimation(this, R.anim.slide);
fg.startAnimation(anim);
this.fg.setVisibility(View.VISIBLE); //fg is a View object indicate fragment

Trim spaces from start and end of string

Here is my current code, the 2nd line works if I comment the 3rd line, but don't work if I leave it how it is.

var page_title = $(this).val().replace(/[^a-zA-Z0-9\s]/g, '');
page_title = page_title.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
page_title = page_title.replace(/([\s]+)/g, '-');

how to check if input field is empty

if you are using jquery-validate.js in your application then use below expression.

if($("#spa").is(":blank"))
{
  //code
}

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

How do you close/hide the Android soft keyboard using Java?

If you want to hide keyboard using Java code, then use this:

  InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(fEmail.getWindowToken(), 0);

Or if you want to hide the keyboard always, then use this in your AndroidManifest:

 <activity
 android:name=".activities.MyActivity"
 android:configChanges="keyboardHidden"  />

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

I'm looking at PostgreSQL full-text search right now, and it has all the right features of a modern search engine, really good extended character and multilingual support, nice tight integration with text fields in the database.

But it doesn't have user-friendly search operators like + or AND (uses & | !) and I'm not thrilled with how it works on their documentation site. While it has bolding of match terms in the results snippets, the default algorithm for which match terms is not great. Also, if you want to index rtf, PDF, MS Office, you have to find and integrate a file format converter.

OTOH, it's way better than the MySQL text search, which doesn't even index words of three letters or fewer. It's the default for the MediaWiki search, and I really think it's no good for end-users: http://www.searchtools.com/analysis/mediawiki-search/

In all cases I've seen, Lucene/Solr and Sphinx are really great. They're solid code and have evolved with significant improvements in usability, so the tools are all there to make search that satisfies almost everyone.

for SHAILI - SOLR includes the Lucene search code library and has the components to be a nice stand-alone search engine.

.gitignore exclude folder but include specific subfolder

This worked for me:

**/.idea/**
!**/.idea/copyright/
!.idea/copyright/profiles_settings.xml
!.idea/copyright/Copyright.xml

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

What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts. Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts". Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.

It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U(unmerged) flag for the files. So now, when you do a git pull, git is throwing up the error, because you have some version of the file, which is not correctly resolved.

To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull.

Sample reproduction and resolution of the issue:

# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test

First, let us create the repository structure

test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

Now we are in repo_clone, and if you do a git pull, it will throw up conflicts

repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
 * branch            master     -> FETCH_HEAD
   24d5b2e..1a1aa70  master     -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.

If we ignore the conflicts in the clone, and make more commits in the original repo now,

repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

And then we do a git pull, we get

repo_clone $ git pull
U   file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.

Note that the file now is in an unmerged state and if we do a git status, we can clearly see the same:

repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)

You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      file

So, to resolve this, we first need to resolve the merge conflict we ignored earlier

repo_clone $ vi file

and set its contents to

text2
text1
text1

and then add it and commit the changes

repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

My issue was that i had multiple versions of MS SQL express installed. I went to installation folder C:/ProgramFiles/MicrosoftSQL Server/ where i found 3 versions of it. I deleted 2 folders, and left only MSSQL13.SQLEXPRESS which solved the problem.

Reversing a string in C

That's a good question ant2009. You can use a standalone function to reverse the string. The code is...

#include <stdio.h>
#define MAX_CHARACTERS 99

int main( void );
int strlen( char __str );

int main() {
    char *str[ MAX_CHARACTERS ];
    char *new_string[ MAX_CHARACTERS ];
    int i, j;

    printf( "enter string: " );
    gets( *str );

    for( i = 0; j = ( strlen( *str ) - 1 ); i < strlen( *str ), j > -1; i++, j-- ) {
        *str[ i ] = *new_string[ j ];
    }
    printf( "Reverse string is: %s", *new_string" );
    return ( 0 );
}

int strlen( char __str[] ) {
    int count;
    for( int i = 0; __str[ i ] != '\0'; i++ ) {
         ++count;
    }
    return ( count );
}

How do you use MySQL's source command to import large files in windows

Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this

D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql

Option 1 for wampp

D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql

change your folder and mysql version

Option 2 Suppose your current path is which is showing command prompt

C:\Users\shafiq;

then change directory using cd.. then goto your mysql directory where your xampp installed. Then cd.. for change directory. then go to bin folder.

C:\xampp\mysql\bin;

C:\xampp\mysql\bin\mysql -u {username} -p {database password}.then please enter when you see enter password in command prompt.

choose database using

mysql->use test (where database name test) 

then put in source sql in bin folder.

then last command will be

mysql-> source test.sql (where test.sql is file name which need to import)

then press enter

This is full command

C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
 mysql-> use test
 mysql->source test.sql

Jquery checking success of ajax post

If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.

Instead of this:

$.post("/post/url.php", parameters, successFunction);

you would use this:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

There are lots of other options available too. The documentation lists all the options available.

Bootstrap date time picker

All scripts should be imported in order:

  1. jQuery and Moment.js
  2. Bootstrap js file
  3. Bootstrap datepicker js file

Bootstrap-datetimepicker requires moment.js to be loaded before datepicker.js.

Working snippet:

_x000D_
_x000D_
$(function() {_x000D_
  $('#datetimepicker1').datetimepicker();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class='col-sm-6'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker1'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Redirecting output to $null in PowerShell, but ensuring the variable remains set

I'd prefer this way to redirect standard output (native PowerShell)...

($foo = someFunction) | out-null

But this works too:

($foo = someFunction) > $null

To redirect just standard error after defining $foo with result of "someFunction", do

($foo = someFunction) 2> $null

This is effectively the same as mentioned above.

Or to redirect any standard error messages from "someFunction" and then defining $foo with the result:

$foo = (someFunction 2> $null)

To redirect both you have a few options:

2>&1>$null
2>&1 | out-null

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

How to pick an image from gallery (SD Card) for my app?

Updated answer, nearly 5 years later:

The code in the original answer no longer works reliably, as images from various sources sometimes return with a different content URI, i.e. content:// rather than file://. A better solution is to simply use context.getContentResolver().openInputStream(intent.getData()), as that will return an InputStream that you can handle as you choose.

For example, BitmapFactory.decodeStream() works perfectly in this situation, as you can also then use the Options and inSampleSize field to downsample large images and avoid memory problems.

However, things like Google Drive return URIs to images which have not actually been downloaded yet. Therefore you need to perform the getContentResolver() code on a background thread.


Original answer:

The other answers explained how to send the intent, but they didn't explain well how to handle the response. Here's some sample code on how to do that:

protected void onActivityResult(int requestCode, int resultCode, 
       Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(
                               selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();


            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
        }
    }
}

After this, you've got the selected image stored in "yourSelectedImage" to do whatever you want with. This code works by getting the location of the image in the ContentResolver database, but that on its own isn't enough. Each image has about 18 columns of information, ranging from its filepath to 'date last modified' to the GPS coordinates of where the photo was taken, though many of the fields aren't actually used.

To save time as you don't actually need the other fields, cursor search is done with a filter. The filter works by specifying the name of the column you want, MediaStore.Images.Media.DATA, which is the path, and then giving that string[] to the cursor query. The cursor query returns with the path, but you don't know which column it's in until you use the columnIndex code. That simply gets the number of the column based on its name, the same one used in the filtering process. Once you've got that, you're finally able to decode the image into a bitmap with the last line of code I gave.

Filter rows which contain a certain string

edit included the newer across() syntax

Here's another tidyverse solution, using filter(across()) or previously filter_at. The advantage is that you can easily extend to more than one column.

Below also a solution with filter_all in order to find the string in any column, using diamonds as example, looking for the string "V"

library(tidyverse)

String in only one column

# for only one column... extendable to more than one creating a column list in `across` or `vars`!
mtcars %>% 
  rownames_to_column("type") %>% 
  filter(across(type, ~ !grepl('Toyota|Mazda', .))) %>%
  head()
#>                type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1        Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#> 2    Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#> 3 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#> 4           Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#> 5        Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
#> 6         Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2

The now superseded syntax for the same would be:

mtcars %>% 
  rownames_to_column("type") %>% 
  filter_at(.vars= vars(type), all_vars(!grepl('Toyota|Mazda',.))) 

String in all columns:

# remove all rows where any column contains 'V'
diamonds %>%
  filter(across(everything(), ~ !grepl('V', .))) %>%
  head
#> # A tibble: 6 x 10
#>   carat cut     color clarity depth table price     x     y     z
#>   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#> 1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
#> 2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
#> 3  0.31 Good    J     SI2      63.3    58   335  4.34  4.35  2.75
#> 4  0.3  Good    J     SI1      64      55   339  4.25  4.28  2.73
#> 5  0.22 Premium F     SI1      60.4    61   342  3.88  3.84  2.33
#> 6  0.31 Ideal   J     SI2      62.2    54   344  4.35  4.37  2.71

The now superseded syntax for the same would be:

diamonds %>% 
  filter_all(all_vars(!grepl('V', .))) %>%
  head

I tried to find an across alternative for the following, but I didn't immediately come up with a good solution:

    #get all rows where any column contains 'V'
    diamonds %>%
    filter_all(any_vars(grepl('V',.))) %>%
      head
    #> # A tibble: 6 x 10
    #>   carat cut       color clarity depth table price     x     y     z
    #>   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
    #> 1 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31
    #> 2 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
    #> 3 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
    #> 4 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
    #> 5 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
    #> 6 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49

Update: Thanks to user Petr Kajzar in this answer, here also an approach for the above:

diamonds %>%
   filter(rowSums(across(everything(), ~grepl("V", .x))) > 0)

How to list active connections on PostgreSQL?

Following will give you active connections/ queries in postgres DB-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

ImportError: No module named scipy

For windows users:

I found this solution after days. Firstly which python version you want to install?

If you want for Python 2.7 version:

STEP 1:

scipy-0.19.0-cp27-cp27m-win32.whl

scipy-0.19.0-cp27-cp27m-win_amd64.whl

numpy-1.11.3+mkl-cp27-cp27m-win32.whl

numpy-1.11.3+mkl-cp27-cp27m-win_amd64.whl

If you want for Python 3.4 version:

scipy-0.19.0-cp34-cp34m-win32.whl

scipy-0.19.0-cp34-cp34m-win_amd64.whl

numpy-1.11.3+mkl-cp34-cp34m-win32.whl

numpy-1.11.3+mkl-cp34-cp34m-win_amd64.whl

If you want for Python 3.5 version:

scipy-0.19.0-cp35-cp35m-win32.whl

scipy-0.19.0-cp35-cp35m-win_amd64.whl

numpy-1.11.3+mkl-cp35-cp35m-win32.whl

numpy-1.11.3+mkl-cp35-cp35m-win_amd64.whl

If you want for Python 3.6 version:

scipy-0.19.0-cp36-cp36m-win32.whl

scipy-0.19.0-cp36-cp36m-win_amd64.whl

numpy-1.11.3+mkl-cp36-cp36m-win32.whl

numpy-1.11.3+mkl-cp36-cp36m-win_amd64.whl

Link: [click[1]

Once finish installation, go to your directory.

For example my directory:

cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip install [where/is/your/downloaded/scipy_whl.]

STEP 2:

Numpy+MKL

From same web site based on python version again:

After that use same thing again in Script folder

cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip3 install [where/is/your/downloaded/numpy_whl.]

And test it in python folder.

Python35>python 
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. 
>>>import scipy

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

Using GPU from a docker container?

Recent enhancements by NVIDIA have produced a much more robust way to do this.

Essentially they have found a way to avoid the need to install the CUDA/GPU driver inside the containers and have it match the host kernel module.

Instead, drivers are on the host and the containers don't need them. It requires a modified docker-cli right now.

This is great, because now containers are much more portable.

enter image description here

A quick test on Ubuntu:

# Install nvidia-docker and nvidia-docker-plugin
wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb

# Test nvidia-smi
nvidia-docker run --rm nvidia/cuda nvidia-smi

For more details see: GPU-Enabled Docker Container and: https://github.com/NVIDIA/nvidia-docker

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:

<configuration>

 <configSections>
    <section  name="DEV" type="System.Configuration.AppSettingsSection" />
    <section  name="TEST" type="System.Configuration.AppSettingsSection" />
 </configSections>

 <TEST>
    <add key="key" value="value1" />
 </TEST>

 <DEV>
    <add key="key" value="value2" />
 </DEV>

</configuration>

then in C# code:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");

btw NameValueSectionHandler is not supported any more in 2.0.

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

Magento addFieldToFilter: Two fields, match as OR, not AND

public function testAction()
{
        $filter_a = array('like'=>'a%');
        $filter_b = array('like'=>'b%');
        echo(
        (string) 
        Mage::getModel('catalog/product')
        ->getCollection()
        ->addFieldToFilter('sku',array($filter_a,$filter_b))
        ->getSelect()
        );
}

Result:

WHERE (((e.sku like 'a%') or (e.sku like 'b%')))

Source: http://alanstorm.com/magento_collections

How do you unit test private methods?

I use PrivateObject class. But as mentioned previously better to avoid testing private methods.

Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(retVal);

How to customize the back button on ActionBar

So you can change it programmatically easily by using homeAsUpIndicator() function that added in android API level 18 and upper.

ActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);

If you use support library

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);

Date format in the json output using spring boot

Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties to set a default date format to all of your classes spring.jackson.date-format.

For your date format example, you would add this line to your properties file:

spring.jackson.date-format=yyyy-MM-dd

Reference https://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/html/common-application-properties.html

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

How would I run an async Task<T> method synchronously?

The simplest way I have found to run task synchronously and without blocking UI thread is to use RunSynchronously() like:

Task t = new Task(() => 
{ 
   //.... YOUR CODE ....
});
t.RunSynchronously();

In my case, I have an event that fires when something occurs. I dont know how many times it will occur. So, I use code above in my event, so whenever it fires, it creates a task. Tasks are executed synchronously and it works great for me. I was just surprised that it took me so long to find out of this considering how simple it is. Usually, recommendations are much more complex and error prone. This was it is simple and clean.

Put content in HttpResponseMessage object?

No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

product = await response.Content.ReadAsAsync<Product>();

Could be replaced with:

response.Content = new StringContent(string product);

Open mvc view in new window from controller

You can use Tommy's method in forms as well:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get, new { target = "_blank" }))
{
//code
}

Converting ArrayList to Array in java

List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki"); 
String names[]=list.toArray(new String[0]);

if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

initializing a Guava ImmutableMap

Notice that your error message only contains five K, V pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of() methods, accepting between zero and five key-value pairings. There is not an of(...) overload accepting a varags parameter because K and V can be different types.

You want an ImmutableMap.Builder:

ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
    .put("key1", "value1") 
    .put("key2", "value2") 
    .put("key3", "value3") 
    .put("key4", "value4") 
    .put("key5", "value5") 
    .put("key6", "value6") 
    .put("key7", "value7") 
    .put("key8", "value8") 
    .put("key9", "value9")
    .build();

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Having spent lot of time trying to fix this. I had no luck with any solution provide here or elsewhere.

But then later realised it wasn't so much as just solving the issue. But you also need to RESTART the VSCODE for it to take affect.

Split a string into an array of strings based on a delimiter

You can make your own function which returns TArray of string:

function mySplit(input: string): TArray<string>;
var
  delimiterSet: array [0 .. 0] of char; 
     // split works with char array, not a single char
begin
  delimiterSet[0] := '&'; // some character
  result := input.Split(delimiterSet);
end;

What are the differences between Abstract Factory and Factory design patterns?

Understand the differences in the motivations:

Suppose you’re building a tool where you’ve objects and a concrete implementation of the interrelations of the objects. Since you foresee variations in the objects, you’ve created an indirection by assigning the responsibility of creating variants of the objects to another object (we call it abstract factory). This abstraction finds strong benefit since you foresee future extensions needing variants of those objects.

Another rather intriguing motivation in this line of thoughts is a case where every-or-none of the objects from the whole group will have a corresponding variant. Based on some conditions, either of the variants will be used and in each case all objects must be of same variant. This might be a bit counter intuitive to understand as we often tend think that - as long as the variants of an object follow a common uniform contract (interface in broader sense), the concrete implementation code should never break. The intriguing fact here is that, not always this is true especially when expected behavior cannot be modeled by a programming contract.

A simple (borrowing the idea from GoF) is any GUI applications say a virtual monitor that emulates look-an-feel of MS or Mac or Fedora OS’s. Here, for example, when all widget objects such as window, button, etc. have MS variant except a scroll-bar that is derived from MAC variant, the purpose of the tool fails badly.

These above cases form the fundamental need of Abstract Factory Pattern.

On the other hand, imagine you’re writing a framework so that many people can built various tools (such as the one in above examples) using your framework. By the very idea of a framework, you don’t need to, albeit you could not use concrete objects in your logic. You rather put some high level contracts between various objects and how they interact. While you (as a framework developer) remain at a very abstract level, each builders of the tool is forced to follow your framework-constructs. However, they (the tool builders) have the freedom to decide what object to be built and how all the objects they create will interact. Unlike the previous case (of Abstract Factory Pattern), you (as framework creator) don’t need to work with concrete objects in this case; and rather can stay at the contract level of the objects. Furthermore, unlike the second part of the previous motivations, you or the tool-builders never have the situations of mixing objects from variants. Here, while framework code remains at contract level, every tool-builder is restricted (by the nature of the case itself) to using their own objects. Object creations in this case is delegated to each implementer and framework providers just provide uniform methods for creating and returning objects. Such methods are inevitable for framework developer to proceed with their code and has a special name called Factory method (Factory Method Pattern for the underlying pattern).

Few Notes:

  • If you’re familiar with ‘template method’, then you’d see that factory methods are often invoked from template methods in case of programs pertaining to any form of framework. By contrast, template methods of application-programs are often simple implementation of specific algorithm and void of factory-methods.
  • Furthermore, for the completeness of the thoughts, using the framework (mentioned above), when a tool-builder is building a tool, inside each factory method, instead of creating a concrete object, he/she may further delegate the responsibility to an abstract-factory object, provided the tool-builder foresees variations of the concrete objects for future extensions.

Sample Code:

//Part of framework-code
BoardGame {
    Board createBoard() //factory method. Default implementation can be provided as well
    Piece createPiece() //factory method

    startGame(){        //template method
         Board borad = createBoard()
         Piece piece = createPiece()
         initState(board, piece)
    }
}


//Part of Tool-builder code
Ludo inherits  BoardGame {
     Board createBoard(){ //overriding of factory method
         //Option A: return new LudoBoard() //Lodu knows object creation
         //Option B: return LudoFactory.createBoard() //Lodu asks AbstractFacory
     }
….
}

//Part of Tool-builder code
Chess inherits  BoardGame {
    Board createBoard(){ //overriding of factory method
        //return a Chess board
    }
    ….
}

How do I bottom-align grid elements in bootstrap fluid layout

Here's also an angularjs directive to implement this functionality

    pullDown: function() {
      return {
        restrict: 'A',
        link: function ($scope, iElement, iAttrs) {
          var $parent = iElement.parent();
          var $parentHeight = $parent.height();
          var height = iElement.height();

          iElement.css('margin-top', $parentHeight - height);
        }
      };
    }

Static image src in Vue.js template

@Pantelis answer somehow steered me to a solution for a similar misunderstanding. A message board project I'm working on needs to show an optional image. I was having fits trying to get the src=imagefile to concatenate a fixed path and variable filename string until I saw the quirky use of "''" quotes :-)

<template id="symp-tmpl">
  <div>
    <div v-for="item in items" style="clear: both;">
      <div v-if="(item.imagefile !== '[none]')">
        <img v-bind:src="'/storage/userimages/' + item.imagefile">
      </div>
      sub: <span>@{{ item.subject }}</span>
      <span v-if="(login == item.author)">[edit]</span>
      <br>@{{ item.author }}
      <br>msg: <span>@{{ item.message }}</span>
    </div>
  </div>
</template>

Difference in Months between two dates in JavaScript

Number Of Months When Day & Time Doesn't Matter

In this case, I'm not concerned with full months, part months, how long a month is, etc. I just need to know the number of months. A relevant real world case would be where a report is due every month, and I need to know how many reports there should be.

Example:

  • January = 1 month
  • January - February = 2 months
  • November - January = 3 months

This is an elaborated code example to show where the numbers are going.

Let's take 2 timestamps that should result in 4 months

  • November 13, 2019's timestamp: 1573621200000
  • February 20, 2020's timestamp: 1582261140000

May be slightly different with your timezone / time pulled. The day, minutes, and seconds don't matter and can be included in the timestamp, but we will disregard it with our actual calculation.

Step 1: convert the timestamp to a JavaScript date

let dateRangeStartConverted = new Date(1573621200000);
let dateRangeEndConverted = new Date(1582261140000);

Step 2: get integer values for the months / years

let startingMonth = dateRangeStartConverted.getMonth();
let startingYear = dateRangeStartConverted.getFullYear();
let endingMonth = dateRangeEndConverted.getMonth();
let endingYear = dateRangeEndConverted.getFullYear();

This gives us

  • Starting month: 11
  • Starting Year: 2019
  • Ending month: 2
  • Ending Year: 2020

Step 3: Add (12 * (endYear - startYear)) + 1 to the ending month.

  • This makes our starting month stay at 11
  • This makes our ending month equal 15 2 + (12 * (2020 - 2019)) + 1 = 15

Step 4: Subtract the months

15 - 11 = 4; we get our 4 month result.

29 Month Example Example

November 2019 through March 2022 is 29 months. If you put these into an excel spreadsheet, you will see 29 rows.

  • Our starting month is 11
  • Our ending month is 40 3 + (12 * (2022-2019)) + 1

40 - 11 = 29

How to replace NaNs by preceding values in pandas DataFrame?

You could use the fillna method on the DataFrame and specify the method as ffill (forward fill):

>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df.fillna(method='ffill')
   0  1  2
0  1  2  3
1  4  2  3
2  4  2  9

This method...

propagate[s] last valid observation forward to next valid

To go the opposite way, there's also a bfill method.

This method doesn't modify the DataFrame inplace - you'll need to rebind the returned DataFrame to a variable or else specify inplace=True:

df.fillna(method='ffill', inplace=True)

Terminal Commands: For loop with echo

jot would work too (in bash shell)

for i in `jot 1000 1`; do echo "http://example.com/$i.jpg"; done

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

Just uninstall the previous Apk and install the updated APK

window.onload vs document.onload

In Chrome, window.onload is different from <body onload="">, whereas they are the same in both Firefox(version 35.0) and IE (version 11).

You could explore that by the following snippet:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!--import css here-->
        <!--import js scripts here-->

        <script language="javascript">

            function bodyOnloadHandler() {
                console.log("body onload");
            }

            window.onload = function(e) {
                console.log("window loaded");
            };
        </script>
    </head>

    <body onload="bodyOnloadHandler()">

        Page contents go here.

    </body>
</html>

And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()" in the consoles of IE & FF, you will see:

"function onload(event) { bodyOnloadHandler() }"

which means that the assignment "window.onload = function(e)..." is overwritten.

Combining COUNT IF AND VLOOK UP EXCEL

Try this:

=IF(NOT(ISERROR(MATCH(A3,worksheet2!A:A,0))),COUNTIF(worksheet2!A:A,A3),"No Match Found")

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

Truncate Decimal number not Round Off

A function to truncate an arbitrary number of decimals:

public decimal Truncate(decimal number, int digits)
{
  decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));
  int temp = (int)(stepper * number);
  return (decimal)temp / stepper;
}

Improve INSERT-per-second performance of SQLite

Try using SQLITE_STATIC instead of SQLITE_TRANSIENT for those inserts.

SQLITE_TRANSIENT will cause SQLite to copy the string data before returning.

SQLITE_STATIC tells it that the memory address you gave it will be valid until the query has been performed (which in this loop is always the case). This will save you several allocate, copy and deallocate operations per loop. Possibly a large improvement.

Import an existing git project into GitLab?

I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:

To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named Kint (under namespace raveren) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.git

The commands are OS agnostic.

In a new directory:

git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror

Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:

git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all

*This assumes that you did not rename your remote master from origin, otherwise, change the first two lines to reflect it.

React Native Error: ENOSPC: System limit for number of file watchers reached

The meaning of this error is that the number of files monitored by the system has reached the limit!!

Result: The command executed failed! Or throw a warning (such as executing a react-native start VSCode)

Solution:

Modify the number of system monitoring files

Ubuntu

sudo gedit /etc/sysctl.conf

Add a line at the bottom

fs.inotify.max_user_watches=524288

Then save and exit!

sudo sysctl -p

to check it

Then it is solved!

Concatenate a NumPy array to another NumPy array

Actually one can always create an ordinary list of numpy arrays and convert it later.

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

In [3]: b = np.array([[1,2],[3,4]])

In [4]: l = [a]

In [5]: l.append(b)

In [6]: l = np.array(l)

In [7]: l.shape
Out[7]: (2, 2, 2)

In [8]: l
Out[8]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])

Why are only final variables accessible in anonymous class?

Maybe this trick gives u an idea

Boolean var= new anonymousClass(){
    private String myVar; //String for example
    @Overriden public Boolean method(int i){
          //use myVar and i
    }
    public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);

How to program a delay in Swift 3

//Runs function after x seconds

public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
    runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}

public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

//Use:-

runThisAfterDelay(seconds: x){
  //write your code here
}

Best way to store chat messages in a database?

There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.

Actually you can find here in Stack Overflow a link to an example schema for a chat: example

If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages

Best way to import Observable from rxjs

Update for RxJS 6 (April 2018)

It is now perfectly fine to import directly from rxjs. (As can be seen in Angular 6+). Importing from rxjs/operators is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6 and the new approach using pipe). Thanks to this treeshaking can now be used as well.

Sample code from rxjs repo:

import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';

range(1, 200)
  .pipe(filter(x => x % 2 === 1), map(x => x + x))
  .subscribe(x => console.log(x));

Backwards compatibility for rxjs < 6?

rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

How do I log errors and warnings into a file?

Use the following code:

ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "Hello, errors!" );

Then watch the file:

tail -f /tmp/php-error.log

Or update php.ini as described in this blog entry from 2008.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

You have not accepted the license agreements of the following SDK components

I ran across this error when i ran cordova build android

I solved this issue by firing ./sdkmanager --licenses and accepting all the licenses.

  1. You have a sdkmanager.bat under the android sdk folder in the path: android/sdk/tools/bin
  2. To trigger that open a command prompt in android/sdk/tools/bin
  3. type ./sdkmanager --licenses and enter
  4. Press y to review all licenses and then press y to accept all licenses

Add to python path mac os x

Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.

This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.

Where to download visual studio express 2005?

You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

Can you nest html forms?

About nesting forms: I spent 10 years one afternoon trying to debug an ajax script.

my previous answer/example didn't account for the html markup, sorry.

<form id='form_1' et al>
  <input stuff>
  <submit onClick='ajaxFunction(That_Puts_form_2_In_The_ajaxContainer)' >
  <td id='ajaxContainer></td>
</form>

form_2 constantly failed saying invalid form_2.

When I moved the ajaxContainer that produced form_2 <i>outside</i> of form_1, I was back in business. It the answer the question as to why one might nest forms. I mean, really, what's the ID for if not to define which form is to be used? There must be a better, slicker work around.

add/remove active class for ul list with jquery?

I used this:

$('.nav-list li.active').removeClass('active');
$(this).parent().addClass('active');

Since the active class is in the <li> element and what is clicked is the <a> element, the first line removes .active from all <li> and the second one (again, $(this) represents <a> which is the clicked element) adds .active to the direct parent, which is <li>.

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

insert echo into the specific html element like div which has an id or class

if yo want to place in an div like i have same work and i do it like

<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';  
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>

Detect IE version (prior to v9) in JavaScript

Conditional comments are no longer supported in IE as of Version 10 as noted on the Microsoft reference page.

_x000D_
_x000D_
var ieDetector = function() {_x000D_
  var browser = { // browser object_x000D_
_x000D_
      verIE: null,_x000D_
      docModeIE: null,_x000D_
      verIEtrue: null,_x000D_
      verIE_ua: null_x000D_
_x000D_
    },_x000D_
    tmp;_x000D_
_x000D_
  tmp = document.documentMode;_x000D_
  try {_x000D_
    document.documentMode = "";_x000D_
  } catch (e) {};_x000D_
_x000D_
  browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1");_x000D_
  try {_x000D_
    document.documentMode = tmp;_x000D_
  } catch (e) {};_x000D_
_x000D_
  // We only let IE run this code._x000D_
  if (browser.isIE) {_x000D_
    browser.verIE_ua =_x000D_
      (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\.?\d*)/i).test(navigator.userAgent || "") ?_x000D_
      parseFloat(RegExp.$1, 10) : null;_x000D_
_x000D_
    var e, verTrueFloat, x,_x000D_
      obj = document.createElement("div"),_x000D_
_x000D_
      CLASSID = [_x000D_
        "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer Help_x000D_
        "{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack_x000D_
        "{89820200-ECBD-11CF-8B85-00AA005B4383}"_x000D_
      ];_x000D_
_x000D_
    try {_x000D_
      obj.style.behavior = "url(#default#clientcaps)"_x000D_
    } catch (e) {};_x000D_
_x000D_
    for (x = 0; x < CLASSID.length; x++) {_x000D_
      try {_x000D_
        browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, ".");_x000D_
      } catch (e) {};_x000D_
_x000D_
      if (browser.verIEtrue) break;_x000D_
_x000D_
    };_x000D_
    verTrueFloat = parseFloat(browser.verIEtrue || "0", 10);_x000D_
    browser.docModeIE = document.documentMode ||_x000D_
      ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) ||_x000D_
      browser.verIE_ua;_x000D_
    browser.verIE = verTrueFloat || browser.docModeIE;_x000D_
  };_x000D_
_x000D_
  return {_x000D_
    isIE: browser.isIE,_x000D_
    Version: browser.verIE_x000D_
  };_x000D_
_x000D_
}();_x000D_
_x000D_
document.write('isIE: ' + ieDetector.isIE + "<br />");_x000D_
document.write('IE Version Number: ' + ieDetector.Version);
_x000D_
_x000D_
_x000D_

then use:

if((ieDetector.isIE) && (ieDetector.Version <= 9))
{

}

Including non-Python files with setup.py

Probably the best way to do this is to use the setuptools package_data directive. This does mean using setuptools (or distribute) instead of distutils, but this is a very seamless "upgrade".

Here's a full (but untested) example:

from setuptools import setup, find_packages

setup(
    name='your_project_name',
    version='0.1',
    description='A description.',
    packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']),
    package_data={'': ['license.txt']},
    include_package_data=True,
    install_requires=[],
)

Note the specific lines that are critical here:

package_data={'': ['license.txt']},
include_package_data=True,

package_data is a dict of package names (empty = all packages) to a list of patterns (can include globs). For example, if you want to only specify files within your package, you can do that too:

package_data={'yourpackage': ['*.txt', 'path/to/resources/*.txt']}

The solution here is definitely not to rename your non-py files with a .py extension.

See Ian Bicking's presentation for more info.

UPDATE: Another [Better] Approach

Another approach that works well if you just want to control the contents of the source distribution (sdist) and have files outside of the package (e.g. top-level directory) is to add a MANIFEST.in file. See the Python documentation for the format of this file.

Since writing this response, I have found that using MANIFEST.in is typically a less frustrating approach to just make sure your source distribution (tar.gz) has the files you need.

For example, if you wanted to include the requirements.txt from top-level, recursively include the top-level "data" directory:

include requirements.txt
recursive-include data *

Nevertheless, in order for these files to be copied at install time to the package’s folder inside site-packages, you’ll need to supply include_package_data=True to the setup() function. See Adding Non-Code Files for more information.

How to split a string into a list?

Split the words without without harming apostrophes inside words Please find the input_1 and input_2 Moore's law

def split_into_words(line):
    import re
    word_regex_improved = r"(\w[\w']*\w|\w)"
    word_matcher = re.compile(word_regex_improved)
    return word_matcher.findall(line)

#Example 1

input_1 = "computational power (see Moore's law) and "
split_into_words(input_1)

# output 
['computational', 'power', 'see', "Moore's", 'law', 'and']

#Example 2

input_2 = """Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad."""

split_into_words(input_2)
#output
['Oh',
 'you',
 "can't",
 'help',
 'that',
 'said',
 'the',
 'Cat',
 "we're",
 'all',
 'mad',
 'here',
 "I'm",
 'mad',
 "You're",
 'mad']

Remove all special characters except space from a string using JavaScript

You can do it specifying the characters you want to remove:

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g, '');

Redirect to external URI from ASP.NET MVC controller

Maybe the solution someone is looking for is this:

Response.Redirect("/Sucesso")

This work when used in the View as well.

Why does sudo change the PATH?

Looks like this bug has been around for quite a while! Here are some bug references you may find helpful (and may want to subscribe to / vote up, hint, hint...):


Debian bug #85123 ("sudo: SECURE_PATH still can't be overridden") (from 2001!)

It seems that Bug#20996 is still present in this version of sudo. The changelog says that it can be overridden at runtime but I haven't yet discovered how.

They mention putting something like this in your sudoers file:

Defaults secure_path="/bin:/usr/bin:/usr/local/bin"

but when I do that in Ubuntu 8.10 at least, it gives me this error:

visudo: unknown defaults entry `secure_path' referenced near line 10

Ubuntu bug #50797 ("sudo built with --with-secure-path is problematic")

Worse still, as far as I can tell, it is impossible to respecify secure_path in the sudoers file. So if, for example, you want to offer your users easy access to something under /opt, you must recompile sudo.


Yes. There needs to be a way to override this "feature" without having to recompile. Nothing worse then security bigots telling you what's best for your environment and then not giving you a way to turn it off.


This is really annoying. It might be wise to keep current behavior by default for security reasons, but there should be a way of overriding it other than recompiling from source code! Many people ARE in need of PATH inheritance. I wonder why no maintainers look into it, which seems easy to come up with an acceptable solution.


I worked around it like this:

mv /usr/bin/sudo /usr/bin/sudo.orig

then create a file /usr/bin/sudo containing the following:

#!/bin/bash
/usr/bin/sudo.orig env PATH=$PATH "$@"

then your regular sudo works just like the non secure-path sudo


Ubuntu bug #192651 ("sudo path is always reset")

Given that a duplicate of this bug was originally filed in July 2006, I'm not clear how long an ineffectual env_keep has been in operation. Whatever the merits of forcing users to employ tricks such as that listed above, surely the man pages for sudo and sudoers should reflect the fact that options to modify the PATH are effectively redundant.

Modifying documentation to reflect actual execution is non destabilising and very helpful.


Ubuntu bug #226595 ("impossible to retain/specify PATH")

I need to be able to run sudo with additional non-std binary folders in the PATH. Having already added my requirements to /etc/environment I was surprised when I got errors about missing commands when running them under sudo.....

I tried the following to fix this without sucess:

  1. Using the "sudo -E" option - did not work. My existing PATH was still reset by sudo

  2. Changing "Defaults env_reset" to "Defaults !env_reset" in /etc/sudoers -- also did not work (even when combined with sudo -E)

  3. Uncommenting env_reset (e.g. "#Defaults env_reset") in /etc/sudoers -- also did not work.

  4. Adding 'Defaults env_keep += "PATH"' to /etc/sudoers -- also did not work.

Clearly - despite the man documentation - sudo is completely hardcoded regarding PATH and does not allow any flexibility regarding retaining the users PATH. Very annoying as I can't run non-default software under root permissions using sudo.

How can I export a GridView.DataSource to a datatable or dataset?

Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

How can I check if a single character appears in a string?

You can use string.indexOf('a').

If the char a is present in string :

it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

How to declare std::unique_ptr and what is the use of it?

From cppreference, one of the std::unique_ptr constructors is

explicit unique_ptr( pointer p ) noexcept;

So to create a new std::unique_ptr is to pass a pointer to its constructor.

unique_ptr<int> uptr (new int(3));

Or it is the same as

int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);

The different is you don't have to clean up after using it. If you don't use std::unique_ptr (smart pointer), you will have to delete it like this

delete int_ptr;

when you no longer need it or it will cause a memory leak.

How can I store JavaScript variable output into a PHP variable?

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>

How do I solve this error, "error while trying to deserialize parameter"

In our case the problem was that we change the default root namespace name.

Project Configuration screen

This is the Project Configuration screen

We finally decided to back to the original name and the problem was solved.

The problem actually was the dots in the Root namespace. With two dots (Name.Child.Child) it doesnt work. But with one (Name.ChidChild) works.

Sort a list by multiple attributes?

There is a operator < between lists e.g.:

[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]

will give

False

Basic Ajax send/receive with node.js

I was facing following error with code (nodejs 0.10.13), provided by ampersand:

origin is not allowed by access-control-allow-origin

Issue was resolved changing

response.writeHead(200, {"Content-Type": "text/plain"});

to

response.writeHead(200, {
                 'Content-Type': 'text/html',
                 'Access-Control-Allow-Origin' : '*'});

How to view method information in Android Studio?

If you just need a shortcut, then it is Ctrl + Q on Linux (and Windows). Just hover the mouse on the method and press Ctrl + Q to see the doc.