Programs & Examples On #Mootools more

MooTools More is the official plugin repository of the MooTools JavaScript Library. These plugins extend and build upon the MooTools Core.

Find closing HTML tag in Sublime Text

None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.

Run ssh and immediately execute command

ssh -t 'command; bash -l'

will execute the command and then start up a login shell when it completes. For example:

ssh -t [email protected] 'cd /some/path; bash -l'

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

I'm running JMeter 2.8 (Windows 7) and received a message similar to that in the original post:

C:\>jmeter
Error: Unable to access jarfile C:\local\software\jMeter\apache-jmeter-2.8\binApacheJMeter.jar
errorlevel=1
Press any key to continue . . .

I'd created a Windows environment variable JMETER_BIN and set it to the JMeter path which I could see contained ApacheJMeter.jar (so it wasn't a question that the jar was missing).

I should have noticed at the time this portion of the error: "binApacheJMeter.jar"

When I went to the jmeter.bat file to troubleshoot, I noticed this line:

%JM_START% %JM_LAUNCH% %ARGS% %JVM_ARGS% -jar "%JMETER_BIN%ApacheJMeter.jar" %JMETER_CMD_LINE_ARGS%

and that caused me to revisit the "binApacheJMeter.jar" portion of the error.

What was happening was that the batch file was requiring a trailing slash on the end of the path in the JMETER_BIN environment variable to correctly specify the location of the .jar.

Once I corrected my environment variable, adding the trailing slash, all was wonderful.

YMMV, but this worked for me.

When should you use a class vs a struct in C++?

I use struct only when I need to hold some data without any member functions associated to it (to operate on the member data) and to access the data variables directly.

Eg: Reading/Writing data from files and socket streams etc. Passing function arguments in a structure where the function arguments are too many and function syntax looks too lengthy.

Technically there is no big difference between class and struture except default accessibility. More over it depends on programming style how you use it.

How do I change Android Studio editor's background color?

How do I change Android Studio editor's background color?

Changing Editor's Background

Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there

IDE will display a dialog like this, Press 'No'

Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?

Changing IDE's Theme

Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there

Press OK. Android Studio will ask you to restart the IDE.

How do I create executable Java program?

You could use GCJ to compile your Java program into native code.
At some time they even compiled Eclipse into a native version.

How to remove empty lines with or without whitespace in Python

Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):

>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n   Garply\n  \n"
>>> print a
Foo

Bar
Baz

        Garply


>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
        Garply

>>> 

How do I get an OAuth 2.0 authentication token in C#

This example get token thouth HttpWebRequest

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
        request.Method = "POST";
        string postData = "grant_type=password";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byte1 = encoding.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        request.ContentLength = byte1.Length;
        Stream newStream = request.GetRequestStream();
        newStream.Write(byte1, 0, byte1.Length);

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;            
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            getreaderjson = reader.ReadToEnd();
        }

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

Can I hide the HTML5 number input’s spin box?

Only add this css to remove spinner on input of number

/* For Firefox */

input[type='number'] {
    -moz-appearance:textfield;
}



/* Webkit browsers like Safari and Chrome */

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

How do I bind to list of checkbox values with AngularJS?

Take a look this: checklist-model.

It works with JavaScript arrays, and objects and it can use static HTML checkboxes, without ng-repeat

<label><input type="checkbox" checklist-model="roles" value="admin"> Administrator</label>
<label><input type="checkbox" checklist-model="roles" value="customer"> Customer</label>
<label><input type="checkbox" checklist-model="roles" value="guest"> Guest</label>
<label><input type="checkbox" checklist-model="roles" value="user"> User</label>

And the JavaScript side:

var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl4a', function($scope) {
    $scope.roles = [];
});

Python find elements in one list that are not in the other

Use a list comprehension like this:

main_list = [item for item in list_2 if item not in list_1]

Output:

>>> list_1 = ["a", "b", "c", "d", "e"]
>>> list_2 = ["a", "f", "c", "m"] 
>>> 
>>> main_list = [item for item in list_2 if item not in list_1]
>>> main_list
['f', 'm']

Edit:

Like mentioned in the comments below, with large lists, the above is not the ideal solution. When that's the case, a better option would be converting list_1 to a set first:

set_1 = set(list_1)  # this reduces the lookup time from O(n) to O(1)
main_list = [item for item in list_2 if item not in set_1]

How to set text color in submit button?

<button id="fwdbtn" style="color:red">Submit</button> 

Does HTTP use UDP?

Typically, no.

Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, RTP.

For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".

As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.

Accessing Objects in JSON Array (JavaScript)

You can loop the array with a for loop and the object properties with for-in loops.

for (var i=0; i<result.length; i++)
    for (var name in result[i]) {
        console.log("Item name: "+name);
        console.log("Source: "+result[i][name].sourceUuid);
        console.log("Target: "+result[i][name].targetUuid);
    }

Toggle visibility property of div

Using jQuery:

$('#play-pause').click(function(){
  if ( $('#video-over').css('visibility') == 'hidden' )
    $('#video-over').css('visibility','visible');
  else
    $('#video-over').css('visibility','hidden');
});

Get sum of MySQL column in PHP

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

Laravel: PDOException: could not find driver

Your database driver is missing. To solve the probelm

First install the driver

For ubuntu: For mysql database.

sudo apt-get install php5.6-mysql/php7.2-mysql

You also can search for other database systems.

You also can search for the driver:

sudo apt-cache search drivername

Then Run the cmd php artisan migrate

Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'

To configure IIS to run 32-bit applications you must follow these steps:

Open IIS
Go to current server – > Application Pools
Select the application pool your 32-bit application will run under
Click Advanced setting or Application Pool Default
Set Enable 32-bit Applications to True

If this option is not available to you, follow these next steps:

Go to %windir%\system32\inetsrv\
Execute the appcmd.exe tool:

How to pass html string to webview on android

To load your data in WebView. Call loadData() method of WebView

webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

How do I kill this tomcat process in Terminal?

kill -9 $(ps -ef | grep 8084 | awk 'NR==2{print $2}')

NR is for the number of records in the input file. awk can find or replaces text

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.

port 8080 is already in use and no process using 8080 has been listed

If no other process is using the port 8080, Eventhough eclipse shows the port 8080 is used while starting the server in eclipse, first you have to stop the server by hitting the stop button in "Configure Tomcat"(which you can find in your start menu under tomcat folder), then try to start the server in eclipse then it will be started.

If any other process is using the port 8080 and as well as you no need to disturb it. then you can change the port.

How to check that an element is in a std::set?

The typical way to check for existence in many STL containers such as std::map, std::set, ... is:

const bool is_in = container.find(element) != container.end();

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

Get Max value from List<myType>

Easiest way is to use System.Linq as previously described

using System.Linq;

public int GetHighestValue(List<MyTypes> list)
{
    return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}

This is also possible with a Dictionary

using System.Linq;

public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
    return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}

string to string array conversion in java

String array = array of characters ?

Or do you have a string with multiple words each of which should be an array element ?

String[] array = yourString.split(wordSeparator);

How to split strings into text and number?

Yet Another Option:

>>> [re.split(r'(\d+)', s) for s in ('foofo21', 'bar432', 'foobar12345')]
[['foofo', '21', ''], ['bar', '432', ''], ['foobar', '12345', '']]

Google Maps API v2: How to make markers clickable?

Below Kotlin code can help to you

Create Marker

        for (i in arrayList.indices) {
            val marker = googleMap!!.addMarker(
                MarkerOptions().position(
                    LatLng(
                        arrayList[i].location_latitude!!.toDoubleOrNull()!!,
                        arrayList[i].location_latitude!!.toDoubleOrNull()!!
                    )
                ).title(arrayList[i].business_name)
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
            )
            marker.tag = i
        }

Marker Click

        googleMap!!.setOnMarkerClickListener { marker ->
            Log.d(TAG, "Clicked on  ${marker.tag}")
            true
        }

How to easily consume a web service from PHP

I have used NuSOAP in the past. I liked it because it is just a set of PHP files that you can include. There is nothing to install on the web server and no config options to change. It has WSDL support as well which is a bonus.

Add / Change parameter of URL and redirect to the new URL

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

FTP/SFTP access to an Amazon S3 Bucket

Or spin Linux instance for SFTP Gateway in your AWS infrastructure that saves uploaded files to your Amazon S3 bucket.

Supported by Thorntech

jquery, selector for class within id

Just use the plain ol' class selector.

$('#my_id .my_class')

It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.

Regarding performance

According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:

$('#my_id').find('.my_class')

Here's the relevant part of the documentation:

ID-Based Selectors

// Fast:
$( "#container div.robotarm" );

// Super-fast:
$( "#container" ).find( "div.robotarm" );

The .find() approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.

Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById() which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.

How to quietly remove a directory with content in PowerShell

To delete content without a folder you can use the following:

Remove-Item "foldertodelete\*" -Force -Recurse

"Invalid signature file" when attempting to run a .jar

For those who have trouble with the accepted solution, there is another way to exclude resource from shaded jar with DontIncludeResourceTransformer:

https://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html#DontIncludeResourceTransformer

          <transformers>
            <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
                <resource>BC1024KE.DSA</resource>
            </transformer>
          </transformers>

From Shade 3.0, this transformer accepts a list of resources. Before that you just need to use multiple transformer each with one resource.

How to resize image (Bitmap) to a given size?

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

Calculate the center point of multiple latitude/longitude coordinate pairs

Here is the python Version for finding center point. The lat1 and lon1 are latitude and longitude lists. it will retuen the latitude and longitude of center point.

def GetCenterFromDegrees(lat1,lon1):    
    if (len(lat1) <= 0):
    return false;

num_coords = len(lat1)

X = 0.0
Y = 0.0
Z = 0.0

for i in range (len(lat1)):
    lat = lat1[i] * np.pi / 180
    lon = lon1[i] * np.pi / 180

    a = np.cos(lat) * np.cos(lon)
    b = np.cos(lat) * np.sin(lon)
    c = np.sin(lat);

    X += a
    Y += b
    Z += c


X /= num_coords
Y /= num_coords
Z /= num_coords

lon = np.arctan2(Y, X)
hyp = np.sqrt(X * X + Y * Y)
lat = np.arctan2(Z, hyp)

newX = (lat * 180 / np.pi)
newY = (lon * 180 / np.pi)
return newX, newY

Structs data type in php?

Only associative arrays are structs in PHP.

And you can't make them strict on their own.

But you can sort of fake structure strictness with classes and interfaces, but beware that unlike structures, class instances are not passed in arguments, their identifiers are!


You can define a struct through an interface (or at least close to it)

Structs enforce a certain structure on an object.

PHP (<= 7.3) does not have native structs, but you can get around it with interfaces and type hinting:

interface FooStruct 
{
    public function name() : string;
}
interface BarStruct 
{
    public function id() : int;
}
interface MyStruct 
{
   public function foo() : FooStruct;
   public function bar() : BarStruct;
}

Any class implementing MyStruct will be a MyStruct.

The way it's build up is not up to the struct, it just ensures that the data returned is correct.


What about setting data?

Setting struct data is problematic as we end up with getters and setters and it's something that is close to an anemic object or a DTO and is considered an anti-pattern by some people

Wrong example:

interface FooStruct 
{
    public function getName() : string;
    public function setName(string $value) : FooStruct;
}
interface BarStruct 
{
    public function getId() : int;
    public function setId(int $value) : BarStruct;
}
interface MyStruct 
{
   public function getFoo() : FooStruct;
   public function setFoo(FooStruct $value) : MyStruct;
   public function getBar() : BarStruct;
   public function setBar(BarStruct $value) : MyStruct;
}

Then we end up with class implementations that might be mutable, and a struct must not mutate, this is to make it a "data type", just like int, string. Yet there's no way to restrict that with interfaces in PHP, meaning people will be able to implement your struct interface in a class that is not a struct. Make sure to keep the instance immutable

Also a struct may then be instantiated without the correct data and trigger errors when trying to access the data.

An easy and reliable way to set data in a PHP struct class is through its constructor

interface FooStruct 
{
    public function name() : string;
}
interface BarStruct 
{
    public function id() : int;
}
interface MyStruct 
{
   public function foo() : FooStruct;
   public function bar() : BarStruct;
}

class Foo implements FooStruct 
{
   protected $name;
   public function __construct(string $name)
   {
       $this->name = $name;
   }
   public function name() : string
   {
       return $this->name;
   }
}

class Bar implements BarStruct 
{
   protected $id;
   public function __construct(string $id)
   {
       $this->id = $id;
   }
   public function id() : int
   {
       return $this->id;
   }
}

class My implements MyStruct 
{
   protected $foo, $bar;
   public function __construct(FooStruct $foo, BarStruct $bar)
   {
       $this->foo = $foo;
       $this->bar = $bar;
   }
   public function foo() : FooStruct
   {
       return $this->foo;
   }
   public function bar() : BarStruct
   {
       return $this->bar;
   }
}

Type hinting using interfaces: (if your IDE supports it)

If you don't mind not having the strict type checking, then another way would be using interfaces or classes with comments for the IDE.

/**
 * Interface My
 * @property Foo $foo
 * @property Bar $bar
 */
interface My 
{

}

/**
 * Interface Foo
 * @property string|integer $id
 * @property string $name
 */
interface Foo 
{

}

/**
 * Interface Bar
 * @property integer $id
 */
interface Bar
{

}

The reason to use interfaces instead of classes is for the same reason why interfaces exist in the first place, because then many classes with many implementations can have this same structure and each method/function that uses it will support every class with this interface.

This depends on your IDE, so you might need to use classes instead or just live without it.

Note: Remember that you have to validate/sanitize the data in the instance elsewhere in the code to match the comment.

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

How long to brute force a salted SHA-512 hash? (salt provided)

There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.

The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.

To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.

As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.

One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.

Nested jQuery.each() - continue/break

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

PhpMyAdmin not working on localhost

Try starting MySQL and Apache in Xampp. Verify Port Number assigned to Apache (By default it should be 80). Now load localhost/phpmyadmin. It solved my problem.

Is it possible to use Java 8 for Android development?

Android uses a Java that branches off of Java 6.

As of Android SDK version 19, you can use Java 7 features by doing this. No full support for Java 8 (yet).

Swift 3 - Comparing Date objects

If you want to ignore seconds for example you can use

func isDate(Date, equalTo: Date, toUnitGranularity: NSCalendar.Unit) -> Bool

Example compare if it's the same day:

Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)

How to auto-size an iFrame?

My solution, (using jquery):

<iframe id="Iframe1" class="tabFrame" width="100%" height="100%" scrolling="no" src="http://samedomain" frameborder="0" >
</iframe>  
<script type="text/javascript">
    $(function () {

        $('.tabFrame').load(function () {
            var iframeContentWindow = this.contentWindow;
            var height = iframeContentWindow.$(document).height();
            this.style.height = height + 'px';
        });
    });
</script>

A project with an Output Type of Class Library cannot be started directly

Suppose you have multiple project in the solution. Select the project that you want to view in browser and select 'Set as StartUp Project'. In your multiple project soln which was the main, the visual studio was unable to identify. this was the main problem.

Add resources, config files to your jar using gradle

Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.

Confirm Password with jQuery Validate

jQuery('.validatedForm').validate({
        rules : {
            password : {
                minlength : 5
            },
            password_confirm : {
                minlength : 5,
                equalTo : '[name="password"]'
            }
        }

In general, you will not use id="password" like this. So, you can use [name="password"] instead of "#password"

socket.error: [Errno 48] Address already in use

Use

 sudo lsof -i:5000

This will give you a list of processes using the port if any. Once the list of processes is given, use the id on the PID column to terminate the process use

 kill 379 #use the provided PID

Div width 100% minus fixed amount of pixels

Maybe I'm being dumb, but isn't table the obvious solution here?

<div class="parent">
    <div class="fixed">
    <div class="stretchToFit">
</div>

.parent{ display: table; width 100%; }
.fixed { display: table-cell; width: 150px; }
.stretchToFit{ display: table-cell; vertical-align: top}

Another way that I've figured out in chrome is even simpler, but man is it a hack!

.fixed{ 
   float: left
}
.stretchToFit{
   display: table-cell;
   width: 1%;
}

This alone should fill the rest of the line horizontally, as table-cells do. However, you get some strange issues with it going over 100% of its parent, setting the width to a percent value fixes it though.

How to do IF NOT EXISTS in SQLite

You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"

When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.

SQLite Documentation

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

I have used the steps in this question and it worked for me.

My issue was that G suite didn't consider my password as strong and after changing it it worked perfectly.

How to upgrade rubygems

To update just one gem (and it's dependencies), do:

    bundle update gem-name

But to update just the gem alone (without updating it's dependencies), do

    bundle update --source gem-name

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Slide up/down effect with ng-show and ng-animate

I've written an Angular directive that does slideToggle() without jQuery.

https://github.com/EricWVGG/AngularSlideables

Firebase Permission Denied

Go to database, next to title there are 2 options:

Cloud Firestore, Realtime database

Select Realtime database and go to rules

Change rules to true.

Clear form fields with jQuery

$('form').submit(function() {

var el = $(this);

$('<button type="reset" style="display:none; "></button>')
    .appendTo(el)
    .click()
    .remove()
;

return false;

});

install / uninstall APKs programmatically (PackageManager vs Intents)

On a rooted device, you might use:

String pkg = context.getPackageName();
String shellCmd = "rm -r /data/app/" + pkg + "*.apk\n"
                + "rm -r /data/data/" + pkg + "\n"
                // TODO remove data on the sd card
                + "sync\n"
                + "reboot\n";
Util.sudo(shellCmd);

Util.sudo() is defined here.

Return first N key:value pairs from dict

For Python 3.8 the correct answer should be:

import more_itertools

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

first_n = more_itertools.take(3, d.items())
print(len(first_n))
print(first_n)

Whose output is:

3
[('a', 3), ('b', 2), ('c', 3)]

After pip install more-itertools of course.

How to read file using NPOI

private DataTable GetDataTableFromExcel(String Path)
    {
        XSSFWorkbook wb;
        XSSFSheet sh;
        String Sheet_name;

        using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
        {
            wb = new XSSFWorkbook(fs);

               Sheet_name= wb.GetSheetAt(0).SheetName;  //get first sheet name
        }
        DataTable DT = new DataTable();
        DT.Rows.Clear();
        DT.Columns.Clear();

        // get sheet
        sh = (XSSFSheet)wb.GetSheet(Sheet_name);

        int i = 0;
        while (sh.GetRow(i) != null)
        {
            // add neccessary columns
            if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
            {
                for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                {
                    DT.Columns.Add("", typeof(string));
                }
            }

            // add row
            DT.Rows.Add();

            // write row value
            for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
            {
                var cell = sh.GetRow(i).GetCell(j);

                if (cell != null)
                {
                    // TODO: you can add more cell types capatibility, e. g. formula
                    switch (cell.CellType)
                    {
                        case NPOI.SS.UserModel.CellType.Numeric:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).NumericCellValue;
                            //dataGridView1[j, i].Value = sh.GetRow(i).GetCell(j).NumericCellValue;

                            break;
                        case NPOI.SS.UserModel.CellType.String:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).StringCellValue;

                            break;
                    }
                }
            }

            i++;
        }

        return DT;
    }

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.

CSS3 Rotate Animation

if you want to flip image you can use it.

.image{
    width: 100%;
    -webkit-animation:spin 3s linear infinite;
    -moz-animation:spin 3s linear infinite;
    animation:spin 3s linear infinite;
}
@-moz-keyframes spin { 50% { -moz-transform: rotateY(90deg); } }
@-webkit-keyframes spin { 50% { -webkit-transform: rotateY(90deg); } }
@keyframes spin { 50% { -webkit-transform: rotateY(90deg); transform:rotateY(90deg); } }

Debugging iframes with Chrome developer tools

When the iFrame points to your site like this:

<html>
  <head>
    <script type="text/javascript" src="/jquery.js"></script>
  </head>
  <body>
    <iframe id="my_frame" src="/wherev"></iframe>
  </body>
</html>

You can access iFrame DOM through this kind of thing.

var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));

SQL ROWNUM how to return rows between a specific range

 SELECT * from
 (
 select m.*, rownum r
 from maps006 m
 )
 where r > 49 and r < 101

Laravel Eloquent: Ordering results of all()

You instruction require call to get, because is it bring the records and orderBy the catalog

$results = Project::orderBy('name')
           ->get();

Example:

$results = Result::where ('id', '>=', '20')
->orderBy('id', 'desc')
->get();

In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.

Get checkbox value in jQuery

Here is how to get the value of all checked checkboxes as an array:

var values = (function() {
                var a = [];
                $(".checkboxes:checked").each(function() {
                    a.push(this.value);
                });
                return a;
            })()

Python, compute list difference

Use set if you don't care about items order or repetition. Use list comprehensions if you do:

>>> def diff(first, second):
        second = set(second)
        return [item for item in first if item not in second]

>>> diff(A, B)
[1, 3, 4]
>>> diff(B, A)
[5]
>>> 

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

Uncaught SyntaxError: Unexpected token u in JSON at position 0

localStorage.clear()

That'll clear the stored data. Then refresh and things should start to work.

How to access to a child method from the parent in vue.js

Parent-Child communication in VueJS

Given a root Vue instance is accessible by all descendants via this.$root, a parent component can access child components via the this.$children array, and a child component can access it's parent via this.$parent, your first instinct might be to access these components directly.

The VueJS documentation warns against this specifically for two very good reasons:

  • It tightly couples the parent to the child (and vice versa)
  • You can't rely on the parent's state, given that it can be modified by a child component.

The solution is to use Vue's custom event interface

The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:

  1. $on() - allows you to declare a listener on your Vue instance with which to listen to events
  2. $emit() - allows you to trigger events on the same instance (self)

Example using $on() and $emit():

_x000D_
_x000D_
const events = new Vue({}),_x000D_
    parentComponent = new Vue({_x000D_
      el: '#parent',_x000D_
      ready() {_x000D_
        events.$on('eventGreet', () => {_x000D_
          this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
        });_x000D_
      },_x000D_
      data: {_x000D_
        parentMsg: 'I am listening for an event..',_x000D_
        counter: 0_x000D_
      }_x000D_
    }),_x000D_
    childComponent = new Vue({_x000D_
      el: '#child',_x000D_
      methods: {_x000D_
      greet: function () {_x000D_
        events.$emit('eventGreet');_x000D_
        this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
      }_x000D_
    },_x000D_
    data: {_x000D_
      childMsg: 'I am getting ready to fire an event.',_x000D_
      counter: 0_x000D_
    }_x000D_
  });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
  <h2>Parent Component</h2>_x000D_
  <p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
  <h2>Child Component</h2>_x000D_
  <p>{{childMsg}}</p>_x000D_
  <button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Answer taken from the original post: Communicating between components in VueJS

Use of def, val, and var in scala

As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:

val person = new Person("Kumar",12)

Another possibility would be:

def person = new Person("Kumar",12)
val p = person
p.age=20
println(p.age)

However, person.age=20 in your code is allowed, as you get back a Person instance from the person method, and on this instance you are allowed to change the value of a var. The problem is, that after that line you have no more reference to that instance (as every call to person will produce a new instance).

This is nothing special, you would have exactly the same behavior in Java:

class Person{ 
   public int age; 
   private String name;
   public Person(String name; int age) {
      this.name = name;  
      this.age = age;
   }
   public String name(){ return name; }
}

public Person person() { 
  return new Person("Kumar", 12); 
}

person().age = 20;
System.out.println(person().age); //--> 12

How do I create a SQL table under a different schema?

Hit F4 and you'll get what you are looking for.

Where can I get a list of Countries, States and Cities?

geonames.org has an api and a data dump of worldwide geographical places.

How to use cURL in Java?

Curl is a non-java program and must be provided outside your Java program.

You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)

Spring cron expression for every day 1:01:am

Spring cron expression for every day 1:01:am

@Scheduled(cron = "0 1 1 ? * *")

for more information check this information:

https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm

size of NumPy array

Yes numpy has a size function, and shape and size are not quite the same.

Input

import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)

print(data)
print(arrData.size)
print(arrData.shape)

Output

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

8 # size

(2, 4) # shape

How to get city name from latitude and longitude coordinates in Google Maps?

 com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
        if("OK".equals(jsonObject.getString("status"))){
            String formatted_address;
            JSONArray results = jsonObject.getJSONArray("results");
            if(results != null && results.size() > 0){
                com.alibaba.fastjson.JSONObject object = results.getJSONObject(0);
                String addressComponents = object.getString("address_components");
                formatted_address = object.getString("formatted_address");
                Log.e("amaya","formatted_address="+formatted_address+"--url="+url);
                if(findCity){
                    boolean finded = false;
                    JSONArray ac = JSONArray.parseArray(addressComponents);
                    if(ac != null && ac.size() > 0){
                        for(int i=0;i<ac.size();i++){
                            com.alibaba.fastjson.JSONObject jo = ac.getJSONObject(i);
                            JSONArray types = jo.getJSONArray("types");
                            if(types != null && types.size() > 0){
                                for(int j=0;j<ac.size();j++){
                                    String string = types.getString(i);
                                    if("administrative_area_level_1".equals(string)){
                                        finded = true;
                                        break;
                                    }
                                }
                            }
                            if(finded) break;
                        }
                    }
                    Log.e("amaya","city="+formatted_address);
                }else{
                    Log.e("amaya","poiName="+hotspotPoi.getPoi_name()+"--"+hotspotPoi);
                }
                if(hotspotPoi != null) hotspotPoi.setPoi_name(formatted_address);
                EventBus.getDefault().post(new AmayaEvent.GeoEvent(hotspotPoi));
            }
        }

this is a method to parse google feedback data.

Rerouting stdin and stdout from C

freopen solves the easy part. Keeping old stdin around is not hard if you haven't read anything and if you're willing to use POSIX system calls like dup or dup2. If you're started to read from it, all bets are off.

Maybe you can tell us the context in which this problem occurs?

I'd encourage you to stick to situations where you're willing to abandon old stdin and stdout and can therefore use freopen.

What happens if you don't commit a transaction to a database (say, SQL Server)?

Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

cannot load such file -- bundler/setup (LoadError)

I ran into the same issue, but I think it was due to spring caching some gems and configurations. I fixed it by running gem pristine --all.

This restores installed gems to pristine condition from files located in the gem cache.

or you can just try for your gem like

gem pristine your_gem_name

Conditionally displaying JSF components

In addition to previous post you can have

<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />

Jsf 2.0

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

How can I generate Unix timestamps?

In python add the following lines to get a time stamp:

>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993

VB.NET - If string contains "value1" or "value2"

 If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then


     End if

Remove spacing between table cells and rows

If the caption box is gray then you can try wrapping the image and the caption in a div with the same background color of gray---so a "div" tag before the "tr" tag...This will mask the gap because instead of being white, it will be gray and look like part of the gray caption.

Execute external program

import java.io.*;

public class Code {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
    Process process = builder.start();

    StringBuilder out = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line = null;
      while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append("\n");
      }
      System.out.println(out);
    }
  }
}

Try online

push_back vs emplace_back

A nice code for the push_back and emplace_back is shown here.

http://en.cppreference.com/w/cpp/container/vector/emplace_back

You can see the move operation on push_back and not on emplace_back.

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

Windows Forms - Enter keypress activates submit button?

private void textBox_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter)
        button.PerformClick();
}

Can not find module “@angular-devkit/build-angular”

I tried all the possible commands listed above and none of them worked for me, Check if Package.json contain "@angular-devkit/build-angular" if not just install it using(in my case version 0.803.19 worked)

npm i @angular-devkit/[email protected]

Or checkout at npm website repositories for version selection

Highlight text similar to grep, but don't filter out text

You can do it using only grep by:

  1. reading the file line by line
  2. matching a pattern in each line and highlighting pattern by grep
  3. if there is no match, echo the line as is

which gives you the following:

while read line ; do (echo $line | grep PATTERN) || echo $line  ; done < inputfile

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

How do I drop a foreign key in SQL Server?

I don't know MSSQL but would it not be:

alter table company drop **constraint** Company_CountryID_FK;

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

Django request.GET

from django.http import QueryDict

def search(request):
if request.GET.\__contains__("q"):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'
return HttpResponse(message)

Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/

MySQL DROP all tables, ignoring foreign keys

This solution is based on @SkyLeach answer but with the support of dropping tables with foreign keys.

echo "SET FOREIGN_KEY_CHECKS = 0;" > ./drop_all_tables.sql
mysqldump --add-drop-table --no-data -u user -p dbname | grep 'DROP TABLE' >> ./drop_all_tables.sql
echo "SET FOREIGN_KEY_CHECKS = 1;" >> ./drop_all_tables.sql
mysql -u user -p dbname < ./drop_all_tables.sql

How to check if a variable is a dictionary in Python?

The OP did not exclude the starting variable, so for completeness here is how to handle the generic case of processing a supposed dictionary that may include items as dictionaries.

Also following the pure Python(3.8) recommended way to test for dictionary in the above comments.

from collections.abc import Mapping

dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k_outer, v_outer in in_dict.items():
            if isinstance(v_outer, Mapping):
                for k_inner, v_inner in v_outer.items():
                    print(k_inner, v_inner)
            else:
                print(k_outer, v_outer)

parse_dict(dict)

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

How to set the LDFLAGS in CMakeLists.txt?

It depends a bit on what you want:

A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

How to read XML response from a URL in java?

do it with the following code:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document doc = builder.parse("/home/codefelix/IdeaProjects/Gradle/src/main/resources/static/Employees.xml");
        NodeList namelist = (NodeList) doc.getElementById("1");

        for (int i = 0; i < namelist.getLength(); i++) {
            Node p = namelist.item(i);

            if (p.getNodeType() == Node.ELEMENT_NODE) {
                Element person = (Element) p;
                NodeList id = (NodeList) person.getElementsByTagName("Employee");
                NodeList nodeList = person.getChildNodes();
                List<EmployeeDto> employeeDtoList=new ArrayList();

                for (int j = 0; j < nodeList.getLength(); j++) {
                    Node n = nodeList.item(j);

                    if (n.getNodeType() == Node.ELEMENT_NODE) {
                        Element naame = (Element) n;
                        System.out.println("Employee" + id + ":" + naame.getTagName() + "=" +naame.getTextContent());
                    }
                }
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

How can you get the Manifest Version number from the App's (Layout) XML variables?

There is not a way to directly get the version out, but there are two work-arounds that could be done.

  1. The version could be stored in a resource string, and placed into the manifest by:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.somepackage"
         android:versionName="@string/version" android:versionCode="20">
    
  2. One could create a custom view, and place it into the XML. The view would use this to assign the name:

    context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    

Either of these solutions would allow for placing the version name in XML. Unfortunately there isn't a nice simple solution, like android.R.string.version or something like that.

Timestamp Difference In Hours for PostgreSQL

extract(hour from age(now(),links.created)) gives you a floor-rounded count of the hour difference.

How to save Excel Workbook to Desktop regardless of user?

Not sure if this is still relevant, but I use this way

Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean   'put this at the top of the module

 Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
    GetUserID = Left$(strUserName, lngLen - 1)
Else
    GetUserID = ""
End If
Exit Function
End Function

This next bit I save file as PDF, but can change to suit

Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)

ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
    True
End Sub

ASP.NET MVC Conditional validation

You can disable validators conditionally by removing errors from ModelState:

ModelState["DependentProperty"].Errors.Clear();

How to fix homebrew permissions?

If you're on OSX High Sierra, /usr/local can no longer be chown'd. You can use:

sudo chown -R $(whoami) $(brew --prefix)/*

Find an object in SQL Server (cross-database)

----Option 2

SELECT DISTINCT
    o.name,
    o.xtype
FROM
    syscomments c
    INNER JOIN
        sysobjects o
        ON
            c.id=o.id
WHERE
    c.TEXT LIKE '%TableName%'
order by
    o.name desc,
    o.xtype desc

Highest Salary in each department

select * from (
    select a.* from EmpDetails a 
    right join (select DeptID,max(salary) as Salary from EmpDetails group by DeptID) b
    on b.DeptID=a.DeptID and b.salary=a.salary ) as c  group by c.DeptID;

Precision String Format Specifier In Swift

//It will more help, by specify how much decimal Point you want.
let decimalPoint = 2
let floatAmount = 1.10001
let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)

android start activity from service

UPDATE ANDROID 10 AND HIGHER

Start an activity from service (foreground or background) is no longer allowed.

There are still some restrictions that can be seen in the documentation

https://developer.android.com/guide/components/activities/background-starts

Debugging Stored Procedure in SQL Server 2008

Yes you can (provided you have at least the professional version of visual studio), although it requires a little setting up once you've done this it's not much different from debugging code. MSDN has a basic walkthrough.

Most efficient way to concatenate strings in JavaScript?

I wonder why String.prototype.concat is not getting any love. In my tests (assuming you already have an array of strings), it outperforms all other methods.

perf.link test

Test code:

const numStrings = 100;
const strings = [...new Array(numStrings)].map(() => Math.random().toString(36).substring(6));

const concatReduce = (strs) => strs.reduce((a, b) => a + b);

const concatLoop = (strs) => {
  let result = ''
  for (let i = 0; i < strings.length; i++) {
    result += strings[i];
  }
  return result;
}

// Case 1: 52,570 ops/s
concatLoop(strings);

// Case 2: 96,450 ops/s
concatReduce(strings)

// Case 3: 138,020 ops/s
strings.join('')

// Case 4: 169,520 ops/s
''.concat(...strings)

Submit a form using jQuery

you could use it like this :

  $('#formId').submit();

OR

document.formName.submit();

Spring JSON request getting 406 (not Acceptable)

Check as @joyfun did for the correct version of jackson but also check our headers ... Accept / may not be transmitted by the client ... use firebug or equivalent to check what your get request is actually sending. I think the headers attribute of the annotation /may/ be checking literals although I'm not 100% sure.

Angularjs - ng-cloak/ng-show elements blink

For what it's worth, I had a similar issue ng-cloak not working. It may be worth checking your app/site with cache enabled to reuse source files to see if that helps.

With my run-in with flickering, I was testing with DevTools open and cache disabled. Leaving the panel closed with caching enabled fixed my issue.

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

Because git has the cool ability to push/pull different branches to different "upstream" repositories. You could even use separate repositories for pushing and pulling - on the same branch. This can create a distributed, multi-level flow, I can see this being useful on project such as the Linux kernel. Git was originally built to be used on that project.

As a consequence, it does not make assumption about which repo your branch should be tracking.

On the other hand, most people do not use git in this way, so it might make a good case for a default option.

Git is generally pretty low-level and it can be frustrating. Yet there are GUIs and it should be easy to write helper scripts if you still want to use it from the shell.

is there a css hack for safari only NOT chrome?

This works:

@media not all and (min-resolution:.001dpcm) { 
  @media {
    /* your code for Safari Desktop & Mobile */
    body {
      background-color: red;
      color: blue;
    }
    /* end */
  }
}

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

How do I install and use curl on Windows?

The simplest tutorial for setting up cURL on Windows is the Making cURL work on Windows 7. It only have 3 easy steps.

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:

sum(~np.isnan(data)).

Performance:

In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

when do you need .ascx files and how would you use them?

ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.

What are the differences between .gitignore and .gitkeep?

.gitkeep isn’t documented, because it’s not a feature of Git.

Git cannot add a completely empty directory. People who want to track empty directories in Git have created the convention of putting files called .gitkeep in these directories. The file could be called anything; Git assigns no special significance to this name.

There is a competing convention of adding a .gitignore file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; .gitignore is also used to list files that should be ignored by Git when looking for untracked files.

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

how to use json file in html code

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

My JSON file:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case I tried to run npm i [email protected] and got the error because the dev server was running in another terminal on vsc. Hit ctrl+c, y to stop it in that terminal, and then installation works.

How to move an element into another element?

I noticed huge memory leak & performance difference between insertAfter & after or insertBefore & before .. If you have tons of DOM elements, or you need to use after() or before() inside a MouseMove event, the browser memory will probably increase and next operations will run really slow.

The solution I've just experienced is to use inserBefore instead before() and insertAfter instead after().

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I am late for this but i want put some more solution relevant to this.

 @GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
    return ResponseEntity.ok(service.getRole());
}

How can I combine multiple nested Substitute functions in Excel?

Thanks for the idea of breaking down a formula Werner!

Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.

Just make sure you have enough end statements to match the number of substitute( lines either side of the cell reference.

As in this example:

=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")

becomes:

=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

which works fine as is, but one can always delete the extra paragraphs manually:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

Name > substitute()

[American Samoa] > American Samoa

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Use this third party you don't need to write even one line

https://github.com/hackiftekhar/IQKeyboardManager

download project and drag and drop IQKeyboardManager in your project. If you find any issue please read README document.

Guys really its remove headache to manage keyboard.

regex string replace

Just change + to -:

str = str.replace(/[^a-z0-9-]/g, "");

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

Best way to encode Degree Celsius symbol into web page?

Try to replace it with &deg;, and also to set the charset to utf-8, as Martin suggests.

&deg;C will get you something like this:

Degrees Celsius

How to merge lists into a list of tuples?

Youre looking for the builtin function zip.

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Try this, as it solved in my case on a Samsung mobile phone:

1. Open the "Google Play" app and press the home button to return

2. Go to Settings ? Applications ? Manage Applications

3. Select the "ALL" tab, Search for "Google Play Store" and press it to open.

4. Press "Force stop"

5. Press "Clear cache"

6. Press "Clear Data"

7. Now Open Play Store and it will work normally.

If the above steps does not help then try the following as well:

1. Go to Settings ? Applications ? Manage Applications

2. Select the "ALL" tab, Search for "Google Services Framework" and press it to open.

3. Press "Force stop"

4. Press "Clear cache"

5. Press "Clear Data"

Convert datatable to JSON in C#

try this (ExtensionMethods):

public static string ToJson(this DataTable dt)
{
    List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();
    Dictionary<string, object> item;
    foreach (DataRow row in dt.Rows)
    {
            item = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    item.Add(col.ColumnName, (Convert.IsDBNull(row[col]) ? null : row[col]));       
        }
        lst.Add(item);
    }
        return Newtonsoft.Json.JsonConvert.SerializeObject(lst);
}

and use:

DataTable dt = new DataTable();
.
.
.
var json = dt.ToJson();

Public class is inaccessible due to its protection level

You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

We had a similar issue. Uploaded builds were queueing up and it simply said "Processing" with the popup help, “After builds are uploaded they will go through a processing state before they can be used.” Days passed.

Selecting "Internal Testers," making a change, and saving seemed to immediately clear the queue: The latest build was now active and available for testing. I've done this twice with two different apps now.

Update: At this point, all bets are off. It seems "processing" happens when Apple quietly upgrades iTunes Connect and there's nothing you can do about it.

On September 23, 2015 iTunes Connect didn't accept any uploads for nearly 24 hours. The "Internal Testers" trick didn't work. Eventually bumping the version number (to avoid "duplicate binary" error) and re-submitting worked.

The next day, Surprise! iTunes Connect was completely changed. I guess we were all looking at a dead site while they brought up the new version in the background :(

In our case we can still see dozens of "failed" uploads still sitting in the "processing" state. Oh well.

Some people report using Application Loader works better than Xcode for submitting builds to iTunes Connect. You can find it inside Xcode now, under the Xcode menu "Open Developer Tool" item.

Sometimes this works. Sometimes it doesn't. Your milage may vary ¯\_(?)_/¯

How do I get ruby to print a full backtrace instead of a truncated one?

Exception#backtrace has the entire stack in it:

def do_division_by_zero; 5 / 0; end
begin
  do_division_by_zero
rescue => exception
  puts exception.backtrace
  raise # always reraise
end

(Inspired by Peter Cooper's Ruby Inside blog)

Adb Devices can't find my phone

I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:

  • enter **USBUI (**87284)

to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.

BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.

Windows batch: echo without new line

You can suppress the new line by using the set /p command. The set /p command does not recognize a space, for that you can use a dot and a backspace character to make it recognize it. You can also use a variable as a memory and store what you want to print in it, so that you can print the variable instead of the sentence. For example:

@echo off
setlocal enabledelayedexpansion
for /f %%a in ('"prompt $H & for %%b in (1) do rem"') do (set "bs=%%a")
cls
set "var=Hello World! :)"
set "x=0"

:loop
set "display=!var:~%x%,1!"
<nul set /p "print=.%bs%%display%"
ping -n 1 localhost >nul
set /a "x=%x% + 1"
if "!var:~%x%,1!" == "" goto end
goto loop

:end
echo.
pause
exit

In this way you can print anything without a new line. I have made the program to print the characters one by one, but you can use words too instead of characters by changing the loop.

In the above example I used "enabledelayedexpansion" so the set /p command does not recognize "!" character and prints a dot instead of that. I hope that you don't have the use of the exclamation mark "!" ;)

@Directive vs @Component in Angular

Change detection

Only @Component can be a node in the change detection tree. This means that you cannot set ChangeDetectionStrategy.OnPush in a @Directive. Despite this fact, a Directive can have @Input and @Output properties and you can inject and manipulate host component's ChangeDetectorRef from it. So use Components when you need a granular control over your change detection tree.

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Data structure for maintaining tabular data in memory?

Having a "table" in memory that needs lookups, sorting, and arbitrary aggregation really does call out for SQL. You said you tried SQLite, but did you realize that SQLite can use an in-memory-only database?

connection = sqlite3.connect(':memory:')

Then you can create/drop/query/update tables in memory with all the functionality of SQLite and no files left over when you're done. And as of Python 2.5, sqlite3 is in the standard library, so it's not really "overkill" IMO.

Here is a sample of how one might create and populate the database:

import csv
import sqlite3

db = sqlite3.connect(':memory:')

def init_db(cur):
    cur.execute('''CREATE TABLE foo (
        Row INTEGER,
        Name TEXT,
        Year INTEGER,
        Priority INTEGER)''')

def populate_db(cur, csv_fp):
    rdr = csv.reader(csv_fp)
    cur.executemany('''
        INSERT INTO foo (Row, Name, Year, Priority)
        VALUES (?,?,?,?)''', rdr)

cur = db.cursor()
init_db(cur)
populate_db(cur, open('my_csv_input_file.csv'))
db.commit()

If you'd really prefer not to use SQL, you should probably use a list of dictionaries:

lod = [ ] # "list of dicts"

def populate_lod(lod, csv_fp):
    rdr = csv.DictReader(csv_fp, ['Row', 'Name', 'Year', 'Priority'])
    lod.extend(rdr)

def query_lod(lod, filter=None, sort_keys=None):
    if filter is not None:
        lod = (r for r in lod if filter(r))
    if sort_keys is not None:
        lod = sorted(lod, key=lambda r:[r[k] for k in sort_keys])
    else:
        lod = list(lod)
    return lod

def lookup_lod(lod, **kw):
    for row in lod:
        for k,v in kw.iteritems():
            if row[k] != str(v): break
        else:
            return row
    return None

Testing then yields:

>>> lod = []
>>> populate_lod(lod, csv_fp)
>>> 
>>> pprint(lookup_lod(lod, Row=1))
{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'}
>>> pprint(lookup_lod(lod, Name='Aardvark'))
{'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'}
>>> pprint(query_lod(lod, sort_keys=('Priority', 'Year')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
 {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
 {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
 {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
 {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
 {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> pprint(query_lod(lod, sort_keys=('Year', 'Priority')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
 {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
 {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
 {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
 {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
 {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> print len(query_lod(lod, lambda r:1997 <= int(r['Year']) <= 2002))
6
>>> print len(query_lod(lod, lambda r:int(r['Year'])==1998 and int(r['Priority']) > 2))
0

Personally I like the SQLite version better since it preserves your types better (without extra conversion code in Python) and easily grows to accommodate future requirements. But then again, I'm quite comfortable with SQL, so YMMV.

How do I unbind "hover" in jQuery?

Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):

$("#myElement").unbind('mouseenter mouseleave');

As of jQuery 1.7, you are also able use $.on() and $.off() for event binding, so to unbind the hover event, you would use the simpler and tidier:

$('#myElement').off('hover');

The pseudo-event-name "hover" is used as a shorthand for "mouseenter mouseleave" but was handled differently in earlier jQuery versions; requiring you to expressly remove each of the literal event names. Using $.off() now allows you to drop both mouse events using the same shorthand.

Edit 2016:

Still a popular question so it's worth drawing attention to @Dennis98's point in the comments below that in jQuery 1.9+, the "hover" event was deprecated in favour of the standard "mouseenter mouseleave" calls. So your event binding declaration should now look like this:

$('#myElement').off('mouseenter mouseleave');

Angularjs ng-model doesn't work inside ng-if

You can use ngHide (or ngShow) directive. It doesn't create child scope as ngIf does.

<div ng-hide="testa">

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Here's how I fixed it:

  1. Opened the Install Cerificates.Command.The shell script got executed.
  2. Opened the Python 3.6.5 and typed in nltk.download().The download graphic window opened and all the packages got installed.

How to select option in drop down using Capybara

Here's the most concise way I've found (using capybara 3.3.0 and chromium driver):

all('#id-of-select option')[1].select_option

will select the 2nd option. Increment the index as needed.

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

Is there a way to make a DIV unselectable?

You can use pointer-events: none; in your CSS

div {
  pointer-events: none;
}

javascript cell number validation

This function check the special chars on key press and eliminates the value if it is not a number

function mobilevalid(id) {

    var feild = document.getElementById(id);

    if (isNaN(feild.value) == false) {
        if (feild.value.length == 1) {
            if (feild.value < 7) {
                feild.value = "";
            }
        } else if (feild.value.length > 10) {
            feild.value = feild.value.substr(0, feild.value.length - 1);
        }
        if (feild.value.charAt(0) < 7) {
            feild.value = "";
        }
    } else {
        feild.value = "";
    }

}

No connection could be made because the target machine actively refused it?

One more possibility --

Make sure you're trying to open the same IP address as where you're listening. My server app was listening to the host machine's IP address using IPv6, but the client was attempting to connect on the host machine's IPv4 address.

Notepad++: Multiple words search in a file (may be in different lines)?

<shameless-plug>

Search+ is a notepad++ plugin that does exactly this. You can download it from here and install it following the steps mentioned here

Feel free to post any issues/suggestions here.

</shameless-plug>

Why is "cursor:pointer" effect in CSS not working

Position the element as relative and then use z-index, it worked for me :)

Using sed, Insert a line above or below the pattern?

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

Which versions of SSL/TLS does System.Net.WebRequest support?

I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.

If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.

How to call multiple JavaScript functions in onclick event?

A link with 1 function defined

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

How to validate date with format "mm/dd/yyyy" in JavaScript?

It appears to be working fine for mm/dd/yyyy format dates, example:

http://jsfiddle.net/niklasvh/xfrLm/

The only problem I had with your code was the fact that:

var ExpiryDate = document.getElementById(' ExpiryDate').value;

Had a space inside the brackets, before the element ID. Changed it to:

var ExpiryDate = document.getElementById('ExpiryDate').value;

Without any further details regarding the type of data that isn't working, there isn't much else to give input on.

Importing Excel files into R, xlsx or xls

Update

As the Answer below is now somewhat outdated, I'd just draw attention to the readxl package. If the Excel sheet is well formatted/lain out then I would now use readxl to read from the workbook. If sheets are poorly formatted/lain out then I would still export to CSV and then handle the problems in R either via read.csv() or plain old readLines().

Original

My preferred way is to save individual Excel sheets in comma separated value (CSV) files. On Windows, these files are associated with Excel so you don't loose the double-click-open-in-Excel "feature".

CSV files can be read into R using read.csv(), or, if you are in a location or using a computer set up with some European settings (where , is used as the decimal place), using read.csv2().

These functions have sensible defaults that makes reading appropriately formatted files simple. Just keep any labels for samples or variables in the first row or column.

Added benefits of storing files in CSV are that as the files are plain text they can be passed around very easily and you can be confident they will open anywhere; one doesn't need Excel to look at or edit the data.

Excel CSV. file with more than 1,048,576 rows of data

You should try delimit it can open up to 2 billion rows and 2 million columns very quickly has a free 15 day trial too. Does the job for me!

Get custom product attributes in Woocommerce

Use below code to get all attributes with details

    global $wpdb;

    $attribute_taxonomies = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "woocommerce_attribute_taxonomies WHERE attribute_name != '' ORDER BY attribute_name ASC;" );
    set_transient( 'wc_attribute_taxonomies', $attribute_taxonomies );

    $attribute_taxonomies = array_filter( $attribute_taxonomies  ) ;

    prin_r($attribute_taxonomies);

How to check if user input is not an int value

you have following errors which in turn is causing you that exception, let me explain it

this is your existing code:

if(!scan.hasNextInt()) {
        System.out.println("Invalid input!");
        System.out.print("Enter an integer: ");
        usrInput= sc.nextInt();
    }

in the above code if(!scan.hasNextInt()) will become true only when user input contains both characters as well as integers like your input adfd 123.

but you are trying to read only integers inside the if condition using usrInput= sc.nextInt();. Which is incorrect,that's what is throwing Exception in thread "main" java.util.InputMismatchException.

so correct code should be

 if(!scan.hasNextInt()) {
            System.out.println("Invalid input!");
            System.out.print("Enter an integer: ");
            sc.next(); 
            continue;
        }

in the above code sc.next() will help to read new input from user and continue will help in executing same if condition(i.e if(!scan.hasNextInt())) again.

Please use code in my first answer to build your complete logic.let me know if you need any explanation on it.

How do I pass a value from a child back to the parent form?

If you're just using formOptions to pick a single value and then close, Mitch's suggestion is a good way to go. My example here would be used if you needed the child to communicate back to the parent while remaining open.

In your parent form, add a public method that the child form will call, such as

public void NotifyMe(string s)
{
    // Do whatever you need to do with the string
}

Next, when you need to launch the child window from the parent, use this code:

using (FormOptions formOptions = new FormOptions())
{
    // passing this in ShowDialog will set the .Owner 
    // property of the child form
    formOptions.ShowDialog(this);
}

In the child form, use this code to pass a value back to the parent:

ParentForm parent = (ParentForm)this.Owner;
parent.NotifyMe("whatever");

The code in this example would be better used for something like a toolbox window which is intended to float above the main form. In this case, you would open the child form (with .TopMost = true) using .Show() instead of .ShowDialog().

A design like this means that the child form is tightly coupled to the parent form (since the child has to cast its owner as a ParentForm in order to call its NotifyMe method). However, this is not automatically a bad thing.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Its just that you need multiple When for a single case to behave it like if.. Elseif else..

   Case when 1=1       //if
   Then
    When 1=1              //else if
     Then.... 
    When .....              //else if
    Then 
    Else                      //else
   ....... 
     End

How to conclude your merge of a file?

Note and update:

Since Git1.7.4 (January 2011), you have git merge --abort, synonymous to "git reset --merge" when a merge is in progress.

But if you want to complete the merge, while somehow nothing remains to be added, then a crude rm -rf .git/MERGE* can be enough for Git to forget about the current merge.

APR based Apache Tomcat Native library was not found on the java.library.path?

For Ubntu Users

 1. Install compilers
    #sudo apt-get install make
    #sudo apt-get install gcc

    2. Install openssl and development libraries
    #sudo apt-get install openssl
    #sudo apt-get install libssl-dev
    3. Install the APR package (Downloaded from http://apr.apache.org/)

    #tar -xzf apr-1.4.6.tar.gz
    #cd apr-1.4.6/
    #sudo ./configure
    #sudo make
    #sudo make install

    You should see the compiled file as
    /usr/local/apr/lib/libapr-1.a

    4. Download, compile and install Tomcat Native sourse package
    tomcat-native-1.1.27-src.tar.gz

    Extract the archive into some folder

    #tar -xzf tomcat-native-1.1.27-src.tar.gz
    #cd tomcat-native-1.1.27-src/jni/native
    #JAVA_HOME=/usr/lib/jvm/jdk1.7.0_21/
    #sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
    #sudo make
    #sudo make install

    Now I have compiled Tomcat Native library in /usr/local/apr/libtcnative-1.so.0.1.27 and symbolic link file /usr/local/apr/@libtcnative-1.so pointed to the library

    5. Create or edit the $CATALINA_HOME/bin/setenv.sh file with following lines :
    export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

    6. Restart tomcat and see the desired result:

JavaScript string and number conversion

parseInt is misfeatured like scanf:

parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys"              is a number with value 'NaN'
Number("12 monkeys")       is a number with value 'NaN'

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

I was facing this issue while deploying my ear to my local weblogic instance. Clearing the local repository and building the ear again resolved the issue for me.

How to export a table dataframe in PySpark to csv?

If you cannot use spark-csv, you can do the following:

df.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("file.csv")

If you need to handle strings with linebreaks or comma that will not work. Use this:

import csv
import cStringIO

def row2csv(row):
    buffer = cStringIO.StringIO()
    writer = csv.writer(buffer)
    writer.writerow([str(s).encode("utf-8") for s in row])
    buffer.seek(0)
    return buffer.read().strip()

df.rdd.map(row2csv).coalesce(1).saveAsTextFile("file.csv")

oracle sql: update if exists else insert

MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:

MERGE INTO mytable d
USING (SELECT 1 id, 'x' name from dual) s
ON (d.id = s.id)
WHEN MATCHED THEN UPDATE SET d.name = s.name
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);

Alternatively you can do this in PL/SQL:

BEGIN
  INSERT INTO mytable (id, name) VALUES (1, 'x');
EXCEPTION
  WHEN DUP_VAL_ON_INDEX THEN
    UPDATE mytable
    SET    name = 'x'
    WHERE id = 1;
END;

What are the rules about using an underscore in a C++ identifier?

Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.

Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.

How to get main window handle from process id?

Though it may be unrelated to your question, take a look at GetGUIThreadInfo Function.

Setting user agent of a java URLConnection

Off hand, setting the http.agent system property to "" might do the trick (I don't have the code in front of me).

You might get away with:

 System.setProperty("http.agent", "");

but that might require a race between you and initialisation of the URL protocol handler, if it caches the value at startup (actually, I don't think it does).

The property can also be set through JNLP files (available to applets from 6u10) and on the command line:

-Dhttp.agent=

Or for wrapper commands:

-J-Dhttp.agent=

Disable elastic scrolling in Safari

None of the 'overflow' solutions worked for me. I'm coding a parallax effect with JavaScript using jQuery. In Chrome and Safari on OSX the elastic/rubber-band effect was messing up my scroll numbers, since it actually scrolls past the document's height and updates the window variables with out-of-boundary numbers. What I had to do was check if the scrolled amount was larger than the actual document's height, like so:

$(window).scroll(
    function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height()) return;
        updateScroll(); // my own function to do my parallaxing stuff
    }
);

MassAssignmentException in Laravel

Read this section of Laravel doc : http://laravel.com/docs/eloquent#mass-assignment

Laravel provides by default a protection against mass assignment security issues. That's why you have to manually define which fields could be "mass assigned" :

class User extends Model
{
    protected $fillable = ['username', 'email', 'password'];
}

Warning : be careful when you allow the mass assignment of critical fields like password or role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

Responsive table handling in Twitter Bootstrap

There are many different things you can do when dealing with responsive tables.

I personally like this approach by Chris Coyier:

You can find many other alternatives here:

If you can leverage Bootstrap and get something quickly, you can simply use the class names ".hidden-phone" and ".hidden-tablet" to hide some rows but this approach might to be the best in many cases. More info (see "Responsive utility classes"):

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

Are HTTPS URLs encrypted?

Additionally, if you're building a ReSTful API, browser leakage and http referer issues are mostly mitigated as the client may not be a browser and you may not have people clicking links.

If this is the case I'd recommend oAuth2 login to obtain a bearer token. In which case the only sensitive data would be the initial credentials...which should probably be in a post request anyway

How to terminate a thread when main program ends?

Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt. Such termination functions may (though inevitably in the main thread!) call any stop function you require; together with the possibility of setting a thread as daemon, that gives you the tools to properly design the system functionality you need.

git recover deleted file where no commit was made after the delete

If you have not committed any changes all you have to do is stash those changes and you will be back to the last working commit.

git stash
git stash clear
git clean 

can't multiply sequence by non-int of type 'float'

Because growthRates is a sequence (you're even iterating it!) and you multiply it by (1 + 0.01), which is obviously a float (1.01). I guess you mean for growthRate in growthRates: ... * growthrate?

How to customize message box

Here is the code needed to create your own message box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}   

Open another page in php

Use the following code:

if(processing == success) {
  header("Location:filename");
  exit();
}

And you are good to go.

How to use onClick event on react Link component?

You should use this:

<Link to={this.props.myroute} onClick={hello}>Here</Link>

Or (if method hello lays at this class):

<Link to={this.props.myroute} onClick={this.hello}>Here</Link>

Update: For ES6 and latest if you want to bind some param with click method, you can use this:

    const someValue = 'some';  
....  
    <Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>

Task continuation on UI thread

I just wanted to add this version because this is such a useful thread and I think this is a very simple implementation. I have used this multiple times in various types if multithreaded application:

 Task.Factory.StartNew(() =>
      {
        DoLongRunningWork();
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
              { txt.Text = "Complete"; }));
      });

Java SSLException: hostname in certificate didn't match

The certificate verification process will always verify the DNS name of the certificate presented by the server, with the hostname of the server in the URL used by the client.

The following code

HttpPost post = new HttpPost("https://74.125.236.52/accounts/ClientLogin");

will result in the certificate verification process verifying whether the common name of the certificate issued by the server, i.e. www.google.com matches the hostname i.e. 74.125.236.52. Obviously, this is bound to result in failure (you could have verified this by browsing to the URL https://74.125.236.52/accounts/ClientLogin with a browser, and seen the resulting error yourself).

Supposedly, for the sake of security, you are hesitant to write your own TrustManager (and you musn't unless you understand how to write a secure one), you ought to look at establishing DNS records in your datacenter to ensure that all lookups to www.google.com will resolve to 74.125.236.52; this ought to be done either in your local DNS servers or in the hosts file of your OS; you might need to add entries to other domains as well. Needless to say, you will need to ensure that this is consistent with the records returned by your ISP.

Float a div right, without impacting on design

If you don't want the image to affect the layout at all (and float on top of other content) you can apply the following CSS to the image:

position:absolute;
right:0;
top:0;

If you want it to float at the right of a particular parent section, you can add position: relative to that section.

How to get the focused element with jQuery?

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

Count all values in a matrix greater than a value

There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):

>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[  123, 24123, 32432],
       [  234,    24,    23]])
>>> b = y > 200
>>> b
array([[False,  True,  True],
       [ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432,   234])
>>> len(y[b])
3
>>>> y[b].sum()
56789

Update:

As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:

>>>> (y>200).sum()
3

which is a simpler solution.


Speed comparison with filter:

### use boolean/mask array ###

b = y > 200

%timeit y[b]
100000 loops, best of 3: 3.31 us per loop

%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop

### use filter ###

x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop

%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop

%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop

%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop

*** use numpy.where ***

nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop

%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop

Android Use Done button on Keyboard to click button

Your Last Edittext .setOnEditorActionListener call this method automatic hit api

I was Call in LoginActivity in et_password

 et_Pass.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {

                    Log.i(TAG,"Enter pressed");
                    Log.i(Check Internet," and Connect To Server");

                }
                return false;
            }
        });

Working Fine