Programs & Examples On #Magnet uri

How to validate an OAuth 2.0 access token for a resource server?

OAuth v2 specs indicates:

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

How can I specify a [DllImport] path at runtime?

If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.

EDIT

Here is a code snippet that works, and shows what I meant.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        var result = a.ShowMessage();
    }
}

class FunctionLoader
{
    [DllImport("Kernel32.dll")]
    private static extern IntPtr LoadLibrary(string path);

    [DllImport("Kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
    {
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));
    }
}

public class MyClass
{
    static MyClass()
    {
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
            FunctionLoader.LoadFunction<MessageBoxDelegate>(
                @"c:\windows\system32\user32.dll", "MessageBoxA");
    }

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
    {
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);
    }
}

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.

How to find the mysql data directory from command line in windows

public function variables($variable="")
{
  return empty($variable) ? mysql_query("SHOW VARIABLES") : mysql_query("SELECT @@$variable");
}

/*get datadir*/
$res = variables("datadir");

/*or get all variables*/
$res = variables();

Send HTML in email via PHP

Simplest way is probably to just use Zend Framework or any of the other frameworks like CakePHP or Symphony.

You can do it with the standard mail function too, but you'll need a bit more knowledge on how to attach pictures.

Alternatively, just host the images on a server instead of attaching them. Sending HTML mail is documented in the mail function documentation.

How to disable "prevent this page from creating additional dialogs"?

function alertWithoutNotice(message){
    setTimeout(function(){
        alert(message);
    }, 1000);
}

Given URL is not permitted by the application configuration

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

Need a query that returns every field that contains a specified letter

I'll assume you meant more or less what you said, and you want to find keywords in your table that "contain the letter 'a' and the letter 'b'." Some of the solutions here give the answer to a different question.

To get keywords that contain both the letters 'a' and 'b' in them (as opposed to those that contain either letter), you can use 'ab' as the in the query below:

select
  keyword
from myTable
where not exists (
  select Nums26.i from Nums26
  where Nums26.i <= len(<matchsetstring>) -- or your dialect's equivalent for LEN()
  and keyword not like '%'+substring(<matchsetstring>,Nums26.i,1)+'%' -- adapt SUBSTRING to your dialect
);

The table named "Nums26" should contain a column "i" (indexed for efficiency) that contains each of the values 1 through 26 (or more if you might try to match more than letters). See below. Advice given by others applies with regard to upper/lower case. If your collation is case-sensitive, however, you can't simply specify 'aAbB' here as your , because that would request keywords that contain each of the four characters a, A, b, and B. You might use UPPER and match 'AB', perhaps.

create table nums26 (
  i int primary key
);
insert into nums26 values (1);
insert into nums26 select 1+i from nums26;
insert into nums26 select 2+i from nums26;
insert into nums26 select 4+i from nums26;
insert into nums26 select 8+i from nums26;
insert into nums26 select 16+i from nums26;

How to base64 encode image in linux bash / shell

If you need input from termial, try this

lc=`echo -n "xxx_${yyy}_iOS" |  base64`

-n option will not input "\n" character to base64 command.

Is there a decorator to simply cache function return values?

I implemented something like this, using pickle for persistance and using sha1 for short almost-certainly-unique IDs. Basically the cache hashed the code of the function and the hist of arguments to get a sha1 then looked for a file with that sha1 in the name. If it existed, it opened it and returned the result; if not, it calls the function and saves the result (optionally only saving if it took a certain amount of time to process).

That said, I'd swear I found an existing module that did this and find myself here trying to find that module... The closest I can find is this, which looks about right: http://chase-seibert.github.io/blog/2011/11/23/pythondjango-disk-based-caching-decorator.html

The only problem I see with that is it wouldn't work well for large inputs since it hashes str(arg), which isn't unique for giant arrays.

It would be nice if there were a unique_hash() protocol that had a class return a secure hash of its contents. I basically manually implemented that for the types I cared about.

How to pass parameters to maven build using pom.xml?

If we have parameter like below in our POM XML

<version>${project.version}.${svn.version}</version>
  <packaging>war</packaging>

I run maven command line as follows :

mvn clean install package -Dproject.version=10 -Dsvn.version=1

How to read a list of files from a folder using PHP?

There is also a really simple way to do this with the help of the RecursiveTreeIterator class, answered here: https://stackoverflow.com/a/37548504/2032235

AttributeError: 'datetime' module has no attribute 'strptime'

Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you're facing (in the future), look at your import statements

  • import datetime: that's the module (that's what you have right now).
  • from datetime import datetime: that's the class.

Xcode "Build and Archive" from command line

You mean the validate/share/submit options? I think those are specific to Xcode, and not suited for a command-line build tool.

With some cleverness, I bet you could make a script to do it for you. It looks like they're just stored in ~/Library/MobileDevice/Archived Applications/ with a UUDI and a plist. I can't imagine it would be that hard to reverse engineer the validator either.

The process I'm interested automating is sending builds to beta testers. (Since App Store submission happens infrequently, I don't mind doing it manually, especially since I often need to add new description text.) By doing a pseudo Build+Archive using Xcode's CLI, I can trigger automatic builds from every code commit, create IPA files with embedded provisioning profiles, and email it to testers.

$("#form1").validate is not a function

Maybe silly, but check that you inline script is AFTER you include the script tags.

What's a simple way to get a text input popup dialog box on an iPhone

I would use a UIAlertView with a UITextField subview. You can either add the text field manually or, in iOS 5, use one of the new methods.

TypeError: no implicit conversion of Symbol into Integer

This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item| you are assigning item to a two-element array [key, value], so item[:symbol] throws an error.

Combining (concatenating) date and time into a datetime

Cast it to datetime instead:

select CAST(CollectionDate as DATETIME) + CAST(CollectionTime as TIME)
from field

This works on SQL Server 2008 R2.

If for some reason you wanted to make sure the first part doesn't have a time component, first cast the field to date, then back to datetime.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

How to change or add theme to Android Studio?

Just a note for people in the future. To add more themes on a Mac, put the theme .icls files in

~/Library/Preferences/AndroidStudio/colors/

Then restart Android Studio. And select your new themes in

Android Studio > Preferences > Editor > Colors&Fonts

Android Studio can use any theme that are made for jetbrains IDE. Here is a good Github repo that has many themes for different IDEs.

Also, the Color Ide plugin is a good tool that changes the background colour of all menus in Android Studio to match your theme. Try it, the IDE will look much better.

Windows should have similar setups, just the theme directory will be a bit different, search for JetBrains Ide theme location should give you the result.

How to replace a string in multiple files in linux command line

The first line occurrences of "foo" will be replaced with "bar". And you can using the second line to check.

grep -rl 'foo' . | xargs sed -i 's/foo/bar/g'
grep 'foo' -r * | awk -F: {'print $1'} | sort -n | uniq -c

How do I customize Facebook's sharer.php

Sharer.php no longer allows you to customize. The page you share will be scraped for OG Tags and that data will be shared.

To properly customize, use FB.UI which comes with the JS-SDK.

How to disable/enable select field using jQuery?

Use the following:

$("select").attr("disabled", "disabled");

Or simply add id="pizza_kind" to <select> tag, like <select name="pizza_kind" id="pizza_kind">: jsfiddle link

The reason your code didn't work is simply because $("#pizza_kind") isn't selecting the <select> element because it does not have id="pizza_kind".

Edit: actually, a better selector is $("select[name='pizza_kind']"): jsfiddle link

How do I make Java register a string input with spaces?

Instead of

Scanner in = new Scanner(System.in);
String question;
question = in.next();

Type in

Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();

This should be able to take spaces as input.

How to append a date in batch files

I've used the environment variables technique covered here: http://cwashington.netreach.net/depo/view.asp?Index=19

http://cwashington.netreach.net/depo/default.asp?topic=repository&move=last&ScriptType=command&SubType=Misc

Here's the code from that site:

::~~Author~~.          Brett Middleton
::~~Email_Address~~. [email protected]
::~~Script_Type~~.   nt command line batch
::~~Sub_Type~~. Misc
::~~Keywords~~. environment variables

::~~Comment~~.
::Sets or clears a group of environment variables containing components of the current date extracted from the string returned by the DATE /T command.  These variables can be used to name files, control the flow of execution, etc.

::~~Script~~.

@echo off

::-----------------------------------------------------------------------------
::  SetEnvDate1.CMD                                                     6/30/98
::-----------------------------------------------------------------------------
::  Description  :  Sets or clears a group of environment variables containing
::               :  components of the current date extracted from the string
::               :  returned by the DATE /T command.  These variables can be
::               :  used to name files, control the flow of execution, etc.
::               :
::  Requires     :  Windows NT with command extensions enabled
::               :
::  Tested       :  Yes, as demonstration
::               :
::  Contact      :  Brett Middleton <[email protected]>
::               :  Animal and Dairy Science Department
::               :  University of Georgia, Athens
::-----------------------------------------------------------------------------
::  USAGE
::
::  SetEnvDate1 can be used as a model for coding date/time routines in
::  other scripts, or can be used by itself as a utility that is called
::  from other scripts.
::  
::  Run or call SetEnvDate1 without arguments to set the date variables.
::  Variables are set for the day abbreviation (DT_DAY), month number (DT_MM),
::  day number (DT_DD) and four-digit year (DT_YYYY).
::
::  When the variables are no longer needed, clean up the environment by
::  calling the script again with the CLEAR argument.  E.g.,
::
::       call SetEnvDate1 clear
::-----------------------------------------------------------------------------
::  NOTES
::
::  A time variable could be added by parsing the string returned by the
::  built-in TIME /T command.  This is left as an exercise for the reader. B-)
::
::  This script illustrates the following NT command extensions:
::
::  1.  Use of the extended IF command to do case-insensitive comparisons.
::
::  2.  Use of the extended DATE command.
::
::  3.  Use of the extended FOR command to parse a string returned by a
::      command or program.
::
::  4.  Use of the "()" conditional processing symbols to group commands
::      for conditional execution.  All commands between the parens will
::      be executed if the preceeding IF or FOR statement is TRUE.
::-----------------------------------------------------------------------------

if not "%1" == "?" goto chkarg
echo.
echo Sets or clears date/time variables in the command environment.
echo.
echo    SetEnvDate1 [clear]
echo.
echo When called without arguments, the variables are created or updated.
echo When called with the CLEAR argument, the variables are deleted.
echo.
goto endit

::-----------------------------------------------------------------------------
::  Check arguments and select SET or CLEAR routine.  Unrecognized arguments
::  are ignored and SET is assumed.
::-----------------------------------------------------------------------------

:chkarg

if /I "%1" == "CLEAR" goto clrvar
goto setvar

::-----------------------------------------------------------------------------
::  Set variables for the day abbreviation (DAY), month number (MM), 
::  day number (DD) and 4-digit year (YYYY). 
::-----------------------------------------------------------------------------

:setvar

for /F "tokens=1-4 delims=/ " %%i IN ('date /t') DO (
set DT_DAY=%%i
set DT_MM=%%j
set DT_DD=%%k
set DT_YYYY=%%l)

goto endit

::-----------------------------------------------------------------------------
::  Clear all variables from the environment.
::-----------------------------------------------------------------------------

:clrvar
for %%v in (DT_DAY DT_MM DT_DD DT_YYYY) do set %%v=
goto endit

:endit

What is the purpose of a question mark after a type (for example: int? myVariable)?

It means that the value type in question is a nullable type

Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

class NullableExample
{
  static void Main()
  {
      int? num = null;

      // Is the HasValue property true?
      if (num.HasValue)
      {
          System.Console.WriteLine("num = " + num.Value);
      }
      else
      {
          System.Console.WriteLine("num = Null");
      }

      // y is set to zero
      int y = num.GetValueOrDefault();

      // num.Value throws an InvalidOperationException if num.HasValue is false
      try
      {
          y = num.Value;
      }
      catch (System.InvalidOperationException e)
      {
          System.Console.WriteLine(e.Message);
      }
  }
}

Pythonic way to find maximum value and its index in a list?

This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.

import random
from datetime import datetime
import operator
import numpy as np

def explicit(l):
    max_val = max(l)
    max_idx = l.index(max_val)
    return max_idx, max_val

def implicit(l):
    max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
    return max_idx, max_val

def npmax(l):
    max_idx = np.argmax(l)
    max_val = l[max_idx]
    return (max_idx, max_val)

if __name__ == "__main__":
    from timeit import Timer

t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
      "import random; import operator; import numpy as np;"
      "l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

Results on my computer:

Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass

Does java.util.List.isEmpty() check if the list itself is null?

You can use your own isEmpty (for multiple collection) method too. Add this your Util class.

public static boolean isEmpty(Collection... collections) {
    for (Collection collection : collections) {
        if (null == collection || collection.isEmpty())
            return true;
    }
    return false;
}

What is the difference between == and equals() in Java?

There are some small differences depending whether you are talking about "primitives" or "Object Types"; the same can be said if you are talking about "static" or "non-static" members; you can also mix all the above...

Here is an example (you can run it):

public final class MyEqualityTest
{
    public static void main( String args[] )
    {
        String s1 = new String( "Test" );
        String s2 = new String( "Test" );

        System.out.println( "\n1 - PRIMITIVES ");
        System.out.println( s1 == s2 ); // false
        System.out.println( s1.equals( s2 )); // true

        A a1 = new A();
        A a2 = new A();

        System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
        System.out.println( a1 == a2 ); // false
        System.out.println( a1.s == a2.s ); // true
        System.out.println( a1.s.equals( a2.s ) ); // true

        B b1 = new B();
        B b2 = new B();

        System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
        System.out.println( b1 == b2 ); // false
        System.out.println( b1.getS() == b2.getS() ); // false
        System.out.println( b1.getS().equals( b2.getS() ) ); // true
    }
}

final class A
{
    // static
    public static String s;
    A()
    {
        this.s = new String( "aTest" );
    }
}

final class B
{
    private String s;
    B()
    {
        this.s = new String( "aTest" );
    }

    public String getS()
    {
        return s;
    }

}

You can compare the explanations for "==" (Equality Operator) and ".equals(...)" (method in the java.lang.Object class) through these links:

The 'json' native gem requires installed build tools

I would like to add that you should make sure that the generated config.yml file when doing ruby dk.rb init contains the path to the ruby installation you want to use DevKit with. In my case, I had the Heroku Toolbelt installed on my system, which provided its own ruby installation, located at a different place. The config.yml file used that particular installation, and that's not what I wanted. I had to manually edit the file to point it to the correct one, then continue with ruby dk.rb review, etc.

There are No resources that can be added or removed from the server

I didn't find the Dynamic Web Module option when I clicked on the link, then I have installed Maven(Java EE) Integration for Eclipse WTP from the Eclipse Marketplace.Then, the above steps worked.

Is it possible to get the current spark context settings in PySpark?

Spark 1.6+

sc.getConf.getAll.foreach(println)

AndroidStudio SDK directory does not exists

sdk.dir didn't work for me because I had ANDROID_HOME environment variable with wrong path. So, solution is just to update ANDROID_HOME or remove it to use local.properties.
Android Studio restart is required after the change.

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

Recursively find all files newer than a given time

Given a unix timestamp (seconds since epoch) of 1494500000, do:

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)"

To grep those files for "foo":

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)" -exec grep -H 'foo' '{}' \;

Javascript select onchange='this.form.submit()'

Use :

<select onchange="myFunction()">

    function myFunction() {
        document.querySelectorAll("input[type=submit]")[0].click();
    }

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

As an update to Austyn Mahoney's answer, configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.

It will be removed at the end of 2018. For more information see here.

Extract a substring according to a pattern

Here is another simple answer

gsub("^.*:","", string)

Batch file include external file for variables

While trying to use the method with excutable configuration I noticed that it may work or may NOT work depending on where in the script is located the call:

call config.cmd

I know it doesn't make any sens, but for me it's a fact. When "call config.cmd" is located at the top of the script, it works, but if further in the script it doesn't.

By doesn't work, I mean the variable are not set un the calling script.

Very very strange !!!!

NSString with \n or line break

\n is the preferred way to break a line. \r will work too. \n\r or \r\n are overkill and may cause you issues later. Cocoa, has specific paragraph and line break characters for specific uses NSParagraphSeparatorCharacter, NSLineSeparatorCharacter. Here is my source for all the above.

Duplicating a MySQL table, indices, and data

Try this :

`CREATE TABLE new-table (id INT(11) auto_increment primary key) SELECT old-table.name, old-table.group, old-table.floor, old-table.age from old-table;`

I selected 4 columns from old-table and made a new table.

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

permission denied - php unlink

You (as in the process that runs b.php, either you through CLI or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.

Note that if you use the PHP chmod() function to set the mode of a file or folder to 777 you should use 0777 to make sure the number is correctly interpreted as an octal number.

How to get Spinner value?

Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.

What is the difference between print and puts?

The API docs give some good hints:

print() ? nil

print(obj, ...) ? nil

Writes the given object(s) to ios. Returns nil.

The stream must be opened for writing. Each given object that isn't a string will be converted by calling its to_s method. When called without arguments, prints the contents of $_.

If the output field separator ($,) is not nil, it is inserted between objects. If the output record separator ($\) is not nil, it is appended to the output.

...

puts(obj, ...) ? nil

Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns nil.

The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its to_s method. If called without arguments, outputs a single newline.

Experimenting a little with the points given above, the differences seem to be:

  • Called with multiple arguments, print separates them by the 'output field separator' $, (which defaults to nothing) while puts separates them by newlines. puts also puts a newline after the final argument, while print does not.

    2.1.3 :001 > print 'hello', 'world'
    helloworld => nil 
    2.1.3 :002 > puts 'hello', 'world'
    hello
    world
     => nil
    2.1.3 :003 > $, = 'fanodd'
     => "fanodd" 
    2.1.3 :004 > print 'hello', 'world'
    hellofanoddworld => nil 
    2.1.3 :005 > puts 'hello', 'world'
    hello
    world
     => nil
  • puts automatically unpacks arrays, while print does not:

    2.1.3 :001 > print [1, [2, 3]], [4]
    [1, [2, 3]][4] => nil 
    2.1.3 :002 > puts [1, [2, 3]], [4]
    1
    2
    3
    4
     => nil
  • print with no arguments prints $_ (the last thing read by gets), while puts prints a newline:

    2.1.3 :001 > gets
    hello world
     => "hello world\n" 
    2.1.3 :002 > puts
    
     => nil 
    2.1.3 :003 > print
    hello world
     => nil
  • print writes the output record separator $\ after whatever it prints, while puts ignores this variable:

    mark@lunchbox:~$ irb
    2.1.3 :001 > $\ = 'MOOOOOOO!'
     => "MOOOOOOO!" 
    2.1.3 :002 > puts "Oink! Baa! Cluck! "
    Oink! Baa! Cluck! 
     => nil 
    2.1.3 :003 > print "Oink! Baa! Cluck! "
    Oink! Baa! Cluck! MOOOOOOO! => nil

Creating custom function in React component

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

export default class Archive extends React.Component { 

    saySomething(something) {
        console.log(something);
    }

    handleClick(e) {
        this.saySomething("element clicked");
    }

    componentDidMount() {
        this.saySomething("component did mount");
    }

    render() {
        return <button onClick={this.handleClick.bind(this)} value="Click me" />;
    }
}

An error has occured. Please see log file - eclipse juno

None of the current answers worked for me. On CentOS, I had to delete the .eclipse folder from home directory. Then eclipse launched just fine!

What does this thread join code mean?

let's say our main thread starts the threads t1 and t2. Now, when t1.join() is called, the main thread suspends itself till thread t1 dies and then resumes itself. Similarly, when t2.join() executes, the main thread suspends itself again till the thread t2 dies and then resumes.

So, this is how it works.

Also, the while loop was not really needed here.

Removing spaces from string

String res =" Application " res=res.trim();

o/p: Application

Note: White space ,blank space are trim or removed

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I used Mosh's solution, but it was not obvious to me how to implement the composition key correctly in code first.

So here is the solution:

public class Holiday
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int HolidayId { get; set; }
    [Key, Column(Order = 1), ForeignKey("Location")]
    public LocationEnum LocationId { get; set; }

    public virtual Location Location { get; set; }

    public DateTime Date { get; set; }
    public string Name { get; set; }
}

Fast and simple String encrypt/decrypt in JAVA

Update

the library already have Java/Kotlin support, see github.


Original

To simplify I did a class to be used simply, I added it on Encryption library to use it you just do as follow:

Add the gradle library:

compile 'se.simbio.encryption:library:2.0.0'

and use it:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
String encrypted = encryption.encryptOrNull("top secret string");
String decrypted = encryption.decryptOrNull(encrypted);

if you not want add the Encryption library you can just copy the following class to your project. If you are in an android project you need to import android Base64 in this class, if you are in a pure java project you need to add this class manually you can get it here

Encryption.java

package se.simbio.encryption;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * A class to make more easy and simple the encrypt routines, this is the core of Encryption library
 */
public class Encryption {

    /**
     * The Builder used to create the Encryption instance and that contains the information about
     * encryption specifications, this instance need to be private and careful managed
     */
    private final Builder mBuilder;

    /**
     * The private and unique constructor, you should use the Encryption.Builder to build your own
     * instance or get the default proving just the sensible information about encryption
     */
    private Encryption(Builder builder) {
        mBuilder = builder;
    }

    /**
     * @return an default encryption instance or {@code null} if occur some Exception, you can
     * create yur own Encryption instance using the Encryption.Builder
     */
    public static Encryption getDefault(String key, String salt, byte[] iv) {
        try {
            return Builder.getDefaultBuilder(key, salt, iv).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Encrypt a String
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
    }

    /**
     * This is a sugar method that calls encrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be encrypted
     *
     * @return the encrypted String or {@code null} if you send the data as {@code null}
     */
    public String encryptOrNull(String data) {
        try {
            return encrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls encrypt method in background, it is a good idea to use this
     * one instead the default method because encryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be encrypted
     * @param callback the Callback to handle the results
     */
    public void encryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String encrypt = encrypt(data);
                    if (encrypt == null) {
                        callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(encrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * Decrypt a String
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     *
     * @throws UnsupportedEncodingException       if the Builder charset name is not supported or if
     *                                            the Builder charset name is not supported
     * @throws NoSuchAlgorithmException           if the Builder digest algorithm is not available
     *                                            or if this has no installed provider that can
     *                                            provide the requested by the Builder secret key
     *                                            type or it is {@code null}, empty or in an invalid
     *                                            format
     * @throws NoSuchPaddingException             if no installed provider can provide the padding
     *                                            scheme in the Builder digest algorithm
     * @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
     *                                            the cipher
     * @throws InvalidKeyException                if the specified key can not be used to initialize
     *                                            the cipher instance
     * @throws InvalidKeySpecException            if the specified key specification cannot be used
     *                                            to generate a secret key
     * @throws BadPaddingException                if the padding of the data does not match the
     *                                            padding scheme
     * @throws IllegalBlockSizeException          if the size of the resulting bytes is not a
     *                                            multiple of the cipher block size
     * @throws NullPointerException               if the Builder digest algorithm is {@code null} or
     *                                            if the specified Builder secret key type is
     *                                            {@code null}
     * @throws IllegalStateException              if the cipher instance is not initialized for
     *                                            encryption or decryption
     */
    public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        if (data == null) return null;
        byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
        SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
        Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
        byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
        return new String(dataBytesDecrypted);
    }

    /**
     * This is a sugar method that calls decrypt method and catch the exceptions returning
     * {@code null} when it occurs and logging the error
     *
     * @param data the String to be decrypted
     *
     * @return the decrypted String or {@code null} if you send the data as {@code null}
     */
    public String decryptOrNull(String data) {
        try {
            return decrypt(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This is a sugar method that calls decrypt method in background, it is a good idea to use this
     * one instead the default method because decryption can take several time and with this method
     * the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
     * one for success and other for the exception
     *
     * @param data     the String to be decrypted
     * @param callback the Callback to handle the results
     */
    public void decryptAsync(final String data, final Callback callback) {
        if (callback == null) return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String decrypt = decrypt(data);
                    if (decrypt == null) {
                        callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
                    }
                    callback.onSuccess(decrypt);
                } catch (Exception e) {
                    callback.onError(e);
                }
            }
        }).start();
    }

    /**
     * creates a 128bit salted aes key
     *
     * @param key encoded input key
     *
     * @return aes 128 bit salted key
     *
     * @throws NoSuchAlgorithmException     if no installed provider that can provide the requested
     *                                      by the Builder secret key type
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws InvalidKeySpecException      if the specified key specification cannot be used to
     *                                      generate a secret key
     * @throws NullPointerException         if the specified Builder secret key type is {@code null}
     */
    private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
        KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
        SecretKey tmp = factory.generateSecret(spec);
        return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
    }

    /**
     * takes in a simple string and performs an sha1 hash
     * that is 128 bits long...we then base64 encode it
     * and return the char array
     *
     * @param key simple inputted string
     *
     * @return sha1 base64 encoded representation
     *
     * @throws UnsupportedEncodingException if the Builder charset name is not supported
     * @throws NoSuchAlgorithmException     if the Builder digest algorithm is not available
     * @throws NullPointerException         if the Builder digest algorithm is {@code null}
     */
    private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
        messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
        return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
    }

    /**
     * When you encrypt or decrypt in callback mode you get noticed of result using this interface
     */
    public interface Callback {

        /**
         * Called when encrypt or decrypt job ends and the process was a success
         *
         * @param result the encrypted or decrypted String
         */
        void onSuccess(String result);

        /**
         * Called when encrypt or decrypt job ends and has occurred an error in the process
         *
         * @param exception the Exception related to the error
         */
        void onError(Exception exception);

    }

    /**
     * This class is used to create an Encryption instance, you should provide ALL data or start
     * with the Default Builder provided by the getDefaultBuilder method
     */
    public static class Builder {

        private byte[] mIv;
        private int mKeyLength;
        private int mBase64Mode;
        private int mIterationCount;
        private String mSalt;
        private String mKey;
        private String mAlgorithm;
        private String mKeyAlgorithm;
        private String mCharsetName;
        private String mSecretKeyType;
        private String mDigestAlgorithm;
        private String mSecureRandomAlgorithm;
        private SecureRandom mSecureRandom;
        private IvParameterSpec mIvParameterSpec;

        /**
         * @return an default builder with the follow defaults:
         * the default char set is UTF-8
         * the default base mode is Base64
         * the Secret Key Type is the PBKDF2WithHmacSHA1
         * the default salt is "some_salt" but can be anything
         * the default length of key is 128
         * the default iteration count is 65536
         * the default algorithm is AES in CBC mode and PKCS 5 Padding
         * the default secure random algorithm is SHA1PRNG
         * the default message digest algorithm SHA1
         */
        public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
            return new Builder()
                    .setIv(iv)
                    .setKey(key)
                    .setSalt(salt)
                    .setKeyLength(128)
                    .setKeyAlgorithm("AES")
                    .setCharsetName("UTF8")
                    .setIterationCount(1)
                    .setDigestAlgorithm("SHA1")
                    .setBase64Mode(Base64.DEFAULT)
                    .setAlgorithm("AES/CBC/PKCS5Padding")
                    .setSecureRandomAlgorithm("SHA1PRNG")
                    .setSecretKeyType("PBKDF2WithHmacSHA1");
        }

        /**
         * Build the Encryption with the provided information
         *
         * @return a new Encryption instance with provided information
         *
         * @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
         * @throws NullPointerException     if the SecureRandomAlgorithm is {@code null} or if the
         *                                  IV byte array is null
         */
        public Encryption build() throws NoSuchAlgorithmException {
            setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
            setIvParameterSpec(new IvParameterSpec(getIv()));
            return new Encryption(this);
        }

        /**
         * @return the charset name
         */
        private String getCharsetName() {
            return mCharsetName;
        }

        /**
         * @param charsetName the new charset name
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setCharsetName(String charsetName) {
            mCharsetName = charsetName;
            return this;
        }

        /**
         * @return the algorithm
         */
        private String getAlgorithm() {
            return mAlgorithm;
        }

        /**
         * @param algorithm the algorithm to be used
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setAlgorithm(String algorithm) {
            mAlgorithm = algorithm;
            return this;
        }

        /**
         * @return the key algorithm
         */
        private String getKeyAlgorithm() {
            return mKeyAlgorithm;
        }

        /**
         * @param keyAlgorithm the keyAlgorithm to be used in keys
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyAlgorithm(String keyAlgorithm) {
            mKeyAlgorithm = keyAlgorithm;
            return this;
        }

        /**
         * @return the Base 64 mode
         */
        private int getBase64Mode() {
            return mBase64Mode;
        }

        /**
         * @param base64Mode set the base 64 mode
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setBase64Mode(int base64Mode) {
            mBase64Mode = base64Mode;
            return this;
        }

        /**
         * @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
         * are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         */
        private String getSecretKeyType() {
            return mSecretKeyType;
        }

        /**
         * @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
         *                      changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecretKeyType(String secretKeyType) {
            mSecretKeyType = secretKeyType;
            return this;
        }

        /**
         * @return the value used for salting
         */
        private String getSalt() {
            return mSalt;
        }

        /**
         * @param salt the value used for salting
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSalt(String salt) {
            mSalt = salt;
            return this;
        }

        /**
         * @return the key
         */
        private String getKey() {
            return mKey;
        }

        /**
         * @param key the key.
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKey(String key) {
            mKey = key;
            return this;
        }

        /**
         * @return the length of key
         */
        private int getKeyLength() {
            return mKeyLength;
        }

        /**
         * @param keyLength the length of key
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setKeyLength(int keyLength) {
            mKeyLength = keyLength;
            return this;
        }

        /**
         * @return the number of times the password is hashed
         */
        private int getIterationCount() {
            return mIterationCount;
        }

        /**
         * @param iterationCount the number of times the password is hashed
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIterationCount(int iterationCount) {
            mIterationCount = iterationCount;
            return this;
        }

        /**
         * @return the algorithm used to generate the secure random
         */
        private String getSecureRandomAlgorithm() {
            return mSecureRandomAlgorithm;
        }

        /**
         * @param secureRandomAlgorithm the algorithm to generate the secure random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
            mSecureRandomAlgorithm = secureRandomAlgorithm;
            return this;
        }

        /**
         * @return the IvParameterSpec bytes array
         */
        private byte[] getIv() {
            return mIv;
        }

        /**
         * @param iv the byte array to create a new IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIv(byte[] iv) {
            mIv = iv;
            return this;
        }

        /**
         * @return the SecureRandom
         */
        private SecureRandom getSecureRandom() {
            return mSecureRandom;
        }

        /**
         * @param secureRandom the Secure Random
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setSecureRandom(SecureRandom secureRandom) {
            mSecureRandom = secureRandom;
            return this;
        }

        /**
         * @return the IvParameterSpec
         */
        private IvParameterSpec getIvParameterSpec() {
            return mIvParameterSpec;
        }

        /**
         * @param ivParameterSpec the IvParameterSpec
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
            mIvParameterSpec = ivParameterSpec;
            return this;
        }

        /**
         * @return the message digest algorithm
         */
        private String getDigestAlgorithm() {
            return mDigestAlgorithm;
        }

        /**
         * @param digestAlgorithm the algorithm to be used to get message digest instance
         *
         * @return this instance to follow the Builder patter
         */
        public Builder setDigestAlgorithm(String digestAlgorithm) {
            mDigestAlgorithm = digestAlgorithm;
            return this;
        }

    }

}    

Convert Pandas column containing NaNs to dtype `int`

It is now possible to create a pandas column containing NaNs as dtype int, since it is now officially added on pandas 0.24.0

pandas 0.24.x release notes Quote: "Pandas has gained the ability to hold integer dtypes with missing values

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

Is there a way to check for both `null` and `undefined`?

if(data){}

it's mean !data

  • null
  • undefined
  • false
  • ....

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Add shadow to custom shape on Android

If you don't mind doing some custom drawing with the Canvas API, check out this answer about drop shadows. Here's a follow-up question to that one which fixes a problem in the original.

How to detect browser using angularjs?

Browser sniffing should generally be avoided, feature detection is much better, but sometimes you have to do it. For instance in my case Windows 8 Tablets overlaps the browser window with a soft keyboard; Ridiculous I know, but sometimes you have to deal with reality.

So you would measure 'navigator.userAgent' as with regular JavaScript (Please don't sink into the habit of treating Angular as something distinct from JavaScript, use plain JavaScript if possible it will lead to less future refactoring).

However for testing you want to use injected objects rather than global ones. Since '$location' doesn't contain the userAgent the simple trick is to use '$window.location.userAgent'. You can now write tests that inject a $window stub with whatever userAgent you wan't to simulate.

I haven't used it for years, but Modernizr's a good source of code for checking features. https://github.com/Modernizr/Modernizr/issues/878#issuecomment-41448059

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

Why aren't python nested functions called closures?

People are confusing about what closure is. Closure is not the inner function. the meaning of closure is act of closing. So inner function is closing over a nonlocal variable which is called free variable.

def counter_in(initial_value=0):
    # initial_value is the free variable
    def inc(increment=1):
        nonlocal initial_value
        initial_value += increment
        return print(initial_value)
    return inc

when you call counter_in() this will return inc function which has a free variable initial_value. So we created a CLOSURE. people call inc as closure function and I think this is confusing people, people think "ok inner functions are closures". in reality inc is not a closure, since it is part of the closure, to make life easy, they call it closure function.

  myClosingOverFunc=counter_in(2)

this returns inc function which is closing over the free variable initial_value. when you invoke myClosingOverFunc

 myClosingOverFunc() 

it will print 2.

when python sees that a closure sytem exists, it creates a new obj called CELL. this will store only the name of the free variable which is initial_value in this case. This Cell obj will point to another object which stores the value of the initial_value.

in our example, initial_value in outer function and inner function will point to this cell object, and this cell object will be point to the value of the initial_value.

  variable initial_value =====>> CELL ==========>> value of initial_value

So when you call counter_in its scope is gone, but it does not matter. because variable initial_value is directly referencing the CELL Obj. and it indirectly references the value of initial_value. That is why even though scope of outer function is gone, inner function will still have access to the free variable

let's say I want to write a function, which takes in a function as an arg and returns how many times this function is called.

def counter(fn):
    # since cnt is a free var, python will create a cell and this cell will point to the value of cnt
    # every time cnt changes, cell will be pointing to the new value
    cnt = 0

    def inner(*args, **kwargs):
        # we cannot modidy cnt with out nonlocal
        nonlocal cnt
        cnt += 1
        print(f'{fn.__name__} has been called {cnt} times')
        # we are calling fn indirectly via the closue inner
        return fn(*args, **kwargs)
    return inner
      

in this example cnt is our free variable and inner + cnt create CLOSURE. when python sees this it will create a CELL Obj and cnt will always directly reference this cell obj and CELL will reference the another obj in the memory which stores the value of cnt. initially cnt=0.

 cnt   ======>>>>  CELL  =============>  0

when you invoke the inner function wih passing a parameter counter(myFunc)() this will increase the cnt by 1. so our referencing schema will change as follow:

 cnt   ======>>>>  CELL  =============>  1  #first counter(myFunc)()
 cnt   ======>>>>  CELL  =============>  2  #second counter(myFunc)()
 cnt   ======>>>>  CELL  =============>  3  #third counter(myFunc)()

this is only one instance of closure. You can create multiple instances of closure with passing another function

counter(differentFunc)()

this will create a different CELL obj from the above. We just have created another closure instance.

 cnt  ======>>  difCELL  ========>  1  #first counter(differentFunc)()
 cnt  ======>>  difCELL  ========>  2  #secon counter(differentFunc)()
 cnt  ======>>  difCELL  ========>  3  #third counter(differentFunc)()


  

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

Setting maxlength of textbox with JavaScript or jQuery

$('#yourTextBoxId').live('change keyup paste', function(){
    if ($('#yourTextBoxId').val().length > 11) {
        $('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10));
    }
});

I Used this along with vars and selectors caching for performance and that did the trick ..

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

What is the difference between parseInt() and Number()?

parseInt() -> Parses a number to specified redix.

Number()-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.

Hence for converting some non-numeric value to number we should always use Number() function.

eg.

Number("")//0
parseInt("")//NaN

Number("123")//123
parseInt("123")//123

Number("123ac") //NaN,as it is a non numeric string
parsInt("123ac") //123,it parse decimal number outof string

Number(true)//1
parseInt(true) //NaN

There are various corner case to parseInt() functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.

Now, to check weather the provided value is Numeric or not,we should use nativeisNaN() function

Bootstrap 3 unable to display glyphicon properly

Did you choose the customized version of Bootstrap? There is an issue that the font files included in the customized package are broken (see https://github.com/twbs/bootstrap/issues/9925). If you do not want to use the CDN, you have to download them manually and replace your own fonts with the downloaded ones:

https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot

After that try a strong reload (CTRL + F5), hope it helps.

How to fix "Referenced assembly does not have a strong name" error?

I was running into this with a ServiceStack dll I had installed with nuget. Turns out there was another set of dlls available that were labeled signed. Not going to be the answer for everyone, but you may just need to check for an existing signed version of your assembly. ServiceStack.Signed

Switch: Multiple values in one case?

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }

How can I stop Chrome from going into debug mode?

You have multiple Google Chrome browser tabs open for the same URL and developer toolbar.

In some other tab, you have set breakpoints which are showing up when you are debugging in the current tab.

Solution: Close the developer toolbar in the other tab or the tab itself.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

Replace your draw line with

g.drawOval(X - r, Y - r, r, r)

This should make the top-left of your circle the right place to make the center be (X,Y), at least as long as the point (X - r,Y - r) has both components in range.

Regular cast vs. static_cast vs. dynamic_cast

You should look at the article C++ Programming/Type Casting.

It contains a good description of all of the different cast types. The following taken from the above link:

const_cast

const_cast(expression) The const_cast<>() is used to add/remove const(ness) (or volatile-ness) of a variable.

static_cast

static_cast(expression) The static_cast<>() is used to cast between the integer types. 'e.g.' char->long, int->short etc.

Static cast is also used to cast pointers to related types, for example casting void* to the appropriate type.

dynamic_cast

Dynamic cast is used to convert pointers and references at run-time, generally for the purpose of casting a pointer or reference up or down an inheritance chain (inheritance hierarchy).

dynamic_cast(expression)

The target type must be a pointer or reference type, and the expression must evaluate to a pointer or reference. Dynamic cast works only when the type of object to which the expression refers is compatible with the target type and the base class has at least one virtual member function. If not, and the type of expression being cast is a pointer, NULL is returned, if a dynamic cast on a reference fails, a bad_cast exception is thrown. When it doesn't fail, dynamic cast returns a pointer or reference of the target type to the object to which expression referred.

reinterpret_cast

Reinterpret cast simply casts one type bitwise to another. Any pointer or integral type can be casted to any other with reinterpret cast, easily allowing for misuse. For instance, with reinterpret cast one might, unsafely, cast an integer pointer to a string pointer.

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Generally speaking:

F5 may give you the same page even if the content is changed, because it may load the page from cache. But Ctrl-F5 forces a cache refresh, and will guarantee that if the content is changed, you will get the new content.

How to get data from observable in angular2

this.myService.getConfig().subscribe(
  (res) => console.log(res),
  (err) => console.log(err),
  () => console.log('done!')
);

How to enable GZIP compression in IIS 7.5

This is more an add-on to the best answer above (GZip Compression can be enabled directly through IIS) which is correct if your running IIS on Windows desktop however...

If your running IIS on Windows Server, this content compression feature is found in a different place to desktop Windows (not in programs and features in Control Panel). First open "Server Manager" then click Manage -> "Add Roles & Features" then keep clicking NEXT (make sure you select the correct server when you see the list of servers if your managing multiple servers from this instance) until you get to SERVER ROLES, scroll down to and open "Web Server (IIS)..." then "Web Server" then "Performance" then tick "Dynamic Content Compression" then click INSTALL. I tested this on Server 2016 Standard so there may be slight differences if your on an earlier version of Server.

Then follow the instructions from Testing - Check if GZIP Compression is Enabled

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

PHP cURL HTTP CODE return 0

Another reason for PHP to return http code 0 is timeout. In my case, I had the following configuration:

curl_setopt($http, CURLOPT_TIMEOUT_MS,500);

It turned out that the request to the endpoint I was pointing to always took more than 500 ms, always timing out and always returning http code 0.

If you remove this setting (CURLOPT_TIMEOUT_MS) or put a higher value (in my case 5000), you'll get the actual http code, in my case a 200 (as expected).

See https://www.php.net/manual/en/function.curl-setopt.php

Preventing console window from closing on Visual Studio C/C++ Console application

Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).

If this doesn't work then add the following to the end of your code:

Console.WriteLine("Press any key to exit...");
Console.ReadKey();

This wait for you to press a key to close the terminal window once the code has reached the end.

If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.

Angular Material: mat-select not selecting default

You should be binding it as [value] in the mat-option as below,

<mat-select placeholder="Panel color" [(value)]="selected2">
  <mat-option *ngFor="let option of options2" [value]="option.id">
    {{ option.name }}
  </mat-option>
</mat-select>

LIVE DEMO

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I was having the same problem.The following solved my issue

Run pip install pymysql in your shell

Then, edit the init.py file in your project origin directory(the same as settings.py) and then

add:

import pymysql

pymysql.install_as_MySQLdb()

this should solve the problem.

How to play .wav files with java

A class that will play a WAV file, blocking until the sound has finished playing:

class Sound implements Playable {

    private final Path wavPath;
    private final CyclicBarrier barrier = new CyclicBarrier(2);

    Sound(final Path wavPath) {

        this.wavPath = wavPath;
    }

    @Override
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {

        try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
             final Clip clip = AudioSystem.getClip()) {

            listenForEndOf(clip);
            clip.open(audioIn);
            clip.start();
            waitForSoundEnd();
        }
    }

    private void listenForEndOf(final Clip clip) {

        clip.addLineListener(event -> {
            if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
        });
    }

    private void waitOnBarrier() {

        try {

            barrier.await();
        } catch (final InterruptedException ignored) {
        } catch (final BrokenBarrierException e) {

            throw new RuntimeException(e);
        }
    }

    private void waitForSoundEnd() {

        waitOnBarrier();
    }
}

Google Geocoding API - REQUEST_DENIED

It's suck Google don't let you that your service is not enabled by this account. Try to enable it first. Go here https://console.developers.google.com/project and create a new project with place service activated this may solve your problem.

How to display a Windows Form in full screen on top of the taskbar?

I'm not have an explain on how it works, but works, and being cowboy coder is that all I need.

        System.Drawing.Rectangle rect = Screen.GetWorkingArea(this);
        this.MaximizedBounds = Screen.GetWorkingArea(this);
        this.WindowState = FormWindowState.Maximized;

The requested operation cannot be performed on a file with a user-mapped section open

I encountered this error and it turned out the issue was FxCop was running against my project. I closed FxCop and then I could compile again.

Gson: How to exclude specific fields from Serialization without annotations

Or can say whats fields not will expose with:

Gson gson = gsonBuilder.excludeFieldsWithModifiers(Modifier.TRANSIENT).create();

on your class on attribute:

private **transient** boolean nameAttribute;

How can I export data to an Excel file

MS provides the OpenXML SDK V 2.5 - see https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx

This can read+write MS Office files (including Excel)...

Another option see http://www.codeproject.com/KB/office/OpenXML.aspx

IF you need more like rendering, formulas etc. then there are different commercial libraries like Aspose and Flexcel...

Prevent form redirect OR refresh on submit?

In the opening tag of your form, set an action attribute like so:

<form id="contactForm" action="#">

Powershell: Get FQDN Hostname

How about this

$FQDN=[System.Net.Dns]::GetHostByName($VM).Hostname.Split('.')
[int]$i = 1
[int]$x = 0
[string]$Domain = $null
do {
    $x = $i-$FQDN.Count
    $Domain = $Domain+$FQDN[$x]+"."
    $i = $i + 1
} until ( $i -eq $FQDN.Count )
$Domain = $Domain.TrimEnd(".")

How to delete empty folders using windows command prompt?

This can be easily done by using rd command with two parameters:

rd <folder> /Q /S
  • /Q - Quiet mode, do not ask if ok to remove a directory tree with /S

  • /S - Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree.

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Specify the from user when sending email using the mail command

Most people need to change two values when trying to correctly forge the from address on an email. First is the from address and the second is the orig-to address. Many of the solutions offered online only change one of these values.

If as root, I try a simple mail command to send myself an email it might look like this. echo "test" | mail -s "a test" [email protected]

And the associated logs: Feb 6 09:02:51 myserver postfix/qmgr[28875]: B10322269D: from=<[email protected]>, size=437, nrcpt=1 (queue active) Feb 6 09:02:52 myserver postfix/smtp[19848]: B10322269D: to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=0.34, delays=0.1/0/0.11/0.13, dsn=2.0.0, status=sent (250 Ok 0000014b5f678593-a0e399ef-a801-4655-ad6b-19864a220f38-000000)

Trying to change the from address with -- echo "test" | mail -s "a test" [email protected] -- [email protected]

This changes the orig-to value but not the from value: Feb 6 09:09:09 myserver postfix/qmgr[28875]: 6BD362269D: from=<[email protected]>, size=474, nrcpt=2 (queue active) Feb 6 09:09:09 myserver postfix/smtp[20505]: 6BD362269D: to=<me@noone>, orig_to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=0.31, delays=0.06/0/0.09/0.15, dsn=2.0.0, status=sent (250 Ok 0000014b5f6d48e2-a98b70be-fb02-44e0-8eb3-e4f5b1820265-000000)

Next trying it with a -r and a -- to adjust the from and orig-to. echo "test" | mail -s "a test" -r [email protected] [email protected] -- [email protected]

And the logs: Feb 6 09:17:11 myserver postfix/qmgr[28875]: E3B972264C: from=<[email protected]>, size=459, nrcpt=2 (queue active) Feb 6 09:17:11 myserver postfix/smtp[21559]: E3B972264C: to=<[email protected]>, orig_to=<[email protected]>, relay=myMTA[x.x.x.x]:25, delay=1.1, delays=0.56/0.24/0.11/0.17, dsn=2.0.0, status=sent (250 Ok 0000014b5f74a2c0-c06709f0-4e8d-4d7e-9abf-dbcea2bee2ea-000000)

This is how it's working for me. Hope this helps someone.

Call jQuery Ajax Request Each X Minutes

you can use setInterval() in javascript

<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>

JavaScript: undefined !== undefined?

That's a bad practice to use the == equality operator instead of ===.

undefined === undefined // true
null == undefined // true
null === undefined // false

The object.x === undefined should return true if x is unknown property.

In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like

value = myObject[name];
if (value == null) {
    alert(name + ' not found.');
}

It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:

value = myObject[name];
if (value === undefined) {
    alert(name + ' not found.');
}

Error : ORA-01704: string literal too long

INSERT INTO table(clob_column) SELECT TO_CLOB(q'[chunk1]') || TO_CLOB(q'[chunk2]') ||
            TO_CLOB(q'[chunk3]') || TO_CLOB(q'[chunk4]') FROM DUAL;

Add left/right horizontal padding to UILabel

Sometimes it's convenient to use UNICODE partial spaces to achieve alignment while prototyping. This can be handy in prototyping, proof-of-concept, or just to defer implementation of graphics algorithms.

If you use UNICODE spaces for convenience, be aware that at least one of the UNICODE spaces has a size based on the font it is displayed from, specifically the actual space character itself (U+0020, ASCII 32)

If you're using the default iOS system font in a UILabel, the default System font characteristics could change in a subsequent iOS release and suddenly introduce an unwanted misalignment by changing your app's precise spacing. This can and does happen, for example the "San Francisco" font replaced a previous iOS system font in an iOS release.

UNICODE easy to specify in Swift, for example:

let six_per_em_space = "\u{2006}"

Alternatively, cut/paste the space from an HTML page directly into the UILabel's text field in Interface Builder.

Note: Attached pic is a screenshot, not HTML, so visit the linked page if you want to cut/paste the space.

UNICODE spaces

AlertDialog.Builder with custom layout and EditText; cannot access view

Use this one

   AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    // Get the layout inflater
    LayoutInflater inflater = (activity).getLayoutInflater();
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the
    // dialog layout
    builder.setTitle(title);
    builder.setCancelable(false);
    builder.setIcon(R.drawable.galleryalart);
    builder.setView(inflater.inflate(R.layout.dialogue, null))
    // Add action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    }
                }
            });
    builder.create();
    builder.show();

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

How do I check if an element is hidden in jQuery?

You can use a CSS class when it visible or hidden by toggling the class:

.show{ display :block; }

Set your jQuery toggleClass() or addClass() or removeClass();.

As an example,

jQuery('#myID').toggleClass('show')

The above code will add show css class when the element don't have show and will remove when it has show class.

And when you are checking if it visible or not, You can follow this jQuery code,

jQuery('#myID').hasClass('show');

Above code will return a boolean (true) when #myID element has our class (show) and false when it don't have the (show) class.

Working with select using AngularJS's ng-options

I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.

Makes JSON:

[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]

services.js:

angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}
    });
});

HTML file:

<div ng:controller="MakeModelCtrl">
  <div>Make</div>
  <select id="makeListBox"
      ng-model="make.selected"
      ng-options="make.code as make.name for make in makes"
      ng-change="makeChanged(make.selected)">
  </select>

  <div>Model</div>
  <select id="modelListBox"
     ng-disabled="makeNotSelected"
     ng-model="model.selected"
     ng-options="model.code as model.name for model in models">
  </select>
</div>

controllers.js:

function MakeModelCtrl($scope)
{
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};
    });

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
        {
            $scope.model = {selected: "0"};
        }
    };

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    ];
    $scope.model = {selected: "0"};
}

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

Editable text to string

If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString().

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

You can view which modules (compiled in) are available via terminal through php -m

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

iPhone UIView Animation Best Practice

Anyway the "Block" method is preffered now-a-days. I will explain the simple block below.

Consider the snipped below. bug2 and bug 3 are imageViews. The below animation describes an animation with 1 second duration after a delay of 1 second. The bug3 is moved from its center to bug2's center. Once the animation is completed it will be logged "Center Animation Done!".

-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;

[UIView animateWithDuration:1
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                     bug3.center = bug2Center;
                 } 
                 completion:^(BOOL finished){
                     NSLog(@"Center Animation Done!");
                 }];
}

Hope that's clean!!!

string to string array conversion in java

String data = "abc";
String[] arr = explode(data);

public String[] explode(String s) {
    String[] arr = new String[s.length];
    for(int i = 0; i < s.length; i++)
    {
        arr[i] = String.valueOf(s.charAt(i));
    }
    return arr;
}

Execute a batch file on a remote PC using a batch file on local PC

If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server.

UPDATE:

Seems shutdown.bat here is for shutting down apache-tomcat.

So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client

As native solution could be wmic

Example:

wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"

In your example should be:

wmic /node:inidsoasrv01 process call create ^
    "cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"

wmic /? and wmic /node /? for more

How to redirect DNS to different ports

(It's been a while since I did this stuff. Please don't blindly assume that all the details below are correct. But I hope I'm not too embarrassingly wrong. :))


As the previous answer stated, the Minecraft client (as of 1.3.1) supports SRV record lookup using the service name _minecraft and the protocol name _tcp, which means that if your zone file looks like this...

arboristal.com.                 86400 IN A   <your IP address>
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 20 25565 arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25566 arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25567 arboristal.com.

...then Minecraft clients who perform SRV record lookup as hinted in the changelog will use ports 25566 and 25567 with preference (40% of the time each) over port 25565 (20% of the time). We can assume that Minecraft clients who do not find and respect these SRV records will use port 25565 as usual.


However, I would argue that it would actually be more "clean and professional" to do it using a load balancer such as Nginx. (I pick Nginx just because I've used it before. I'm not claiming it's uniquely suited to this task. It might even be a bad choice for some reason.) Then you don't have to mess with your DNS, and you can use the same approach to load-balance any service, not just ones like Minecraft which happen to have done the hard client-side work to look up and respect SRV records. To do it the Nginx way, you'd run Nginx on the arboristal.com machine with something like the following in /etc/nginx/sites-enabled/arboristal.com:

upstream minecraft_servers {
    ip_hash;
    server 127.0.0.1:25566 weight=1;
    server 127.0.0.1:25567 weight=1;
    server 127.0.0.1:25568 weight=1;
}
server {
    listen 25565;
    proxy_pass minecraft_servers;
}

Here we are controlling the load-balancing ourselves on the server side (via Nginx), so we no longer need to worry that badly behaved clients might prefer port 25565 to the other two ports. In fact, now all clients will talk to arboristal.com:25565! But the listener on that port is no longer a Minecraft server; it's Nginx, secretly proxying all the traffic onto three other ports on the same machine.

We load-balance based on a hash of the client's IP address (ip_hash), so that if a client disconnects and then reconnects later, there's a good chance that it'll get reconnected to the same Minecraft server it had before. (I don't know how much this matters to Minecraft, or how SRV-enabled clients are programmed to deal with this aspect.)

Notice that we used to run a Minecraft server on port 25565; I've moved it to port 25568 so that we can use port 25565 for the load-balancer.

A possible disadvantage of the Nginx method is that it makes Nginx a bottleneck in your system. If Nginx goes down, then all three servers become unreachable. If some part of your system can't keep up with the volume of traffic on that single port, 25565, all three servers become flaky. And not to mention, Nginx is a big new dependency in your ecosystem. Maybe you don't want to introduce yet another massive piece of software with a complicated config language and a huge attack surface. I can respect that.

A possible advantage of the Nginx method is... that it makes Nginx a bottleneck in your system! You can apply global policies via Nginx, such as rejecting packets above a certain size, or responding with a static web page to HTTP connections on port 80. You can also firewall off ports 25566, 25567, and 25568 from the Internet, since now they should be talked to only by Nginx over the loopback interface. This reduces your attack surface somewhat.

Nginx also makes it easier to add new Minecraft servers to your backend; now you can just add a server line to your config and service nginx reload. Using the old port-based approach, you'd have to add a new SRV record with your DNS provider (and it could take up to 86400 seconds for clients to notice the change) and then also remember to edit your firewall (e.g. /etc/iptables.rules) to permit external traffic over that new port.

Nginx also frees you from having to think about DNS TTLs when making ops changes. Suppose you decide to split up your three Minecraft servers onto three different physical machines with different IP addresses. Using Nginx, you can do that completely via config changes to your server lines, and you can keep those new machines inside your firewall (connected only to Nginx over a private interface), and the changes will take effect immediately, by definition. Whereas, using SRV records, you'll have to rewrite your zone file to something like this...

arboristal.com.                 86400 IN CNAME mc1.arboristal.com.
mc1.arboristal.com.             86400 IN A   <a new machine's IP address>
mc2.arboristal.com.             86400 IN A   <a new machine's IP address>
mc3.arboristal.com.             86400 IN A   <a new machine's IP address>
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 20 25565 mc1.arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc2.arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc3.arboristal.com.

...and you'll have to leave all three new machines poking outside your firewall so that they can receive connections from the Internet. And you'll have to wait up to 86400 seconds for your clients to notice the change, which could affect the complexity of your rollout plan. And if you were running any other services (such as an HTTP server) on arboristal.com, now you have to move them to the mc1.arboristal.com machine because of how I did that CNAME. I did that only for the benefit of those hypothetical Minecraft clients who don't respect SRV records and will still be trying to connect to arboristal.com:25565.


So, I think both ways (SRV records and Nginx load-balancing) are reasonable, and your choice will depend on your personal preferences. I caricature the options as:

  • SRV records: "I just need it to work. I don't want complexity. And I know and trust my DNS provider."
  • Nginx: "I foresee arboristal.com taking over the world, or at least moving to a bigger machine someday. I'm not scared of learning a new tool. What's a zone file?"

Adding an assets folder in Android Studio

right click on app-->select

New-->Select Folder-->then click on Assets Folder

How can I increase the size of a bootstrap button?

You can add your own css property for button size as follows:

.btn {
    min-width: 250px;
}

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Get source JARs from Maven repository

In Eclipse

  1. Right click on the pom.xml
  2. Select Run As -> Maven generate-sources
    it will generate the source by default in .m2 folder

Pre-Requisite:

Maven should be configured with Eclipse.

For each row in an R dataframe

you can do something for a list object,

data("mtcars")
rownames(mtcars)
data <- list(mtcars ,mtcars, mtcars, mtcars);data

out1 <- NULL 
for(i in seq_along(data)) { 
  out1[[i]] <- data[[i]][rownames(data[[i]]) != "Volvo 142E", ] } 
out1

Or a data frame,

data("mtcars")
df <- mtcars
out1 <- NULL 
for(i in 1:nrow(df)) {
  row <- rownames(df[i,])
  # do stuff with row
  out1 <- df[rownames(df) != "Volvo 142E",]
  
}
out1 

What is a lambda expression in C++11?

Answers

Q: What is a lambda expression in C++11?

A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.

Q: When would I use one?

A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.

Q: What class of problem do they solve that wasn't possible prior to their introduction?

A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)

Example of usage

auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);

Extras about lambdas, not covered by question. Ignore this section if you're not interest

1. Captured values. What you can to capture

1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.

1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).

[captureVar1,captureVar2](int arg1){}

1.3. You can capture be reference. & -- in this context mean reference, not pointers.

   [&captureVar1,&captureVar2](int arg1){}

1.4. It exists notation to capture all non-static vars by value, or by reference

  [=](int arg1){} // capture all not-static vars by value

  [&](int arg1){} // capture all not-static vars by reference

1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2

[=,&Param2](int arg1){} 

Capture all not-static vars by reference, but by value capture Param2

[&,Param2](int arg1){} 

2. Return type deduction

2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.

[=](int arg1)->trailing_return_type{return trailing_return_type();}

If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions

3. Captured values. What you can not capture

3.1. You can capture only local vars, not member variable of the object.

4. ?onversions

4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.

p.s.

  1. More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88

  2. In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:

    auto toFloat = [](int value) { return float(value);};
    auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
    

Rails update_attributes without save?

You can use the 'attributes' method:

@car.attributes = {:model => 'Sierra', :years => '1990', :looks => 'Sexy'}

Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

attributes=(new_attributes, guard_protected_attributes = true) Allows you to set all the attributes at once by passing in a hash with keys matching the attribute names (which again matches the column names).

If guard_protected_attributes is true (the default), then sensitive attributes can be protected from this form of mass-assignment by using the attr_protected macro. Or you can alternatively specify which attributes can be accessed with the attr_accessible macro. Then all the attributes not included in that won’t be allowed to be mass-assigned.

class User < ActiveRecord::Base
  attr_protected :is_admin
end

user = User.new
user.attributes = { :username => 'Phusion', :is_admin => true }
user.username   # => "Phusion"
user.is_admin?  # => false

user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
user.is_admin?  # => true

How to implement "Access-Control-Allow-Origin" header in asp.net

1.Install-Package Microsoft.AspNet.WebApi.Cors

2 . Add this code in WebApiConfig.cs.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes

    config.EnableCors();

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

3. Add this

using System.Web.Http.Cors; 

4. Add this code in Api Controller (HomeController.cs)

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
    [HttpGet]
    [Route("api/Home/test")]
    public string test()
    {
       return "";
    }
}

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

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

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

Simulate a button click in Jest

I needed to do a little bit of testing myself of a button component. These tests work for me ;-)

import { shallow } from "enzyme";
import * as React from "react";
import Button from "../button.component";

describe("Button Component Tests", () => {
    it("Renders correctly in DOM", () => {
        shallow(
            <Button text="Test" />
        );
    });
    it("Expects to find button HTML element in the DOM", () => {
        const wrapper = shallow(<Button text="test"/>)
        expect(wrapper.find('button')).toHaveLength(1);
    });

    it("Expects to find button HTML element with className test in the DOM", () => {
        const wrapper = shallow(<Button className="test" text="test"/>)
        expect(wrapper.find('button.test')).toHaveLength(1);
    });

    it("Expects to run onClick function when button is pressed in the DOM", () => {
        const mockCallBackClick = jest.fn();
        const wrapper = shallow(<Button onClick={mockCallBackClick} className="test" text="test"/>);
        wrapper.find('button').simulate('click');
        expect(mockCallBackClick.mock.calls.length).toEqual(1);
    });
});

Insert HTML with React Variable Statements (JSX)

You can also include this HTML in ReactDOM like this:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

Here are two links link and link2 from React documentation which could be helpful.

Difference between application/x-javascript and text/javascript content types

According to RFC 4329 the correct MIME type for JavaScript should be application/javascript. Howerver, older IE versions choke on this since they expect text/javascript.

How to make a cross-module variable?

Global variables are usually a bad idea, but you can do this by assigning to __builtins__:

__builtins__.foo = 'something'
print foo

Also, modules themselves are variables that you can access from any module. So if you define a module called my_globals.py:

# my_globals.py
foo = 'something'

Then you can use that from anywhere as well:

import my_globals
print my_globals.foo

Using modules rather than modifying __builtins__ is generally a cleaner way to do globals of this sort.

Remove Project from Android Studio

Select your project in the projects window > File > Project Structure > (in the Modules section) select your project and click the minus button.

Comparing two .jar files

Extract each jar to it's own directory using the jar command with parameters xvf. i.e. jar xvf myjar.jar for each jar.

Then, use the UNIX command diff to compare the two directories. This will show the differences in the directories. You can use diff -r dir1 dir2 two recurse and show the differences in text files in each directory(.xml, .properties, etc).

This will also show if binary class files differ. To actually compare the class files you will have to decompile them as noted by others.

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

    public ToggleImageButton(Context context) {
        super(context);
    }

    public ToggleImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        setChecked(attrs);
    }

    public ToggleImageButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setChecked(attrs);
    }

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method, in C#, needs a ; and hence must be enclosed by { }.

  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

What is difference between INNER join and OUTER join

Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. check this

What is a serialVersionUID and why should I use it?

I can't pass up this opportunity to plug Josh Bloch's book Effective Java (2nd Edition). Chapter 11 is an indispensible resource on Java serialization.

Per Josh, the automatically-generated UID is generated based on a class name, implemented interfaces, and all public and protected members. Changing any of these in any way will change the serialVersionUID. So you don't need to mess with them only if you are certain that no more than one version of the class will ever be serialized (either across processes or retrieved from storage at a later time).

If you ignore them for now, and find later that you need to change the class in some way but maintain compatibility w/ old version of the class, you can use the JDK tool serialver to generate the serialVersionUID on the old class, and explicitly set that on the new class. (Depending on your changes you may need to also implement custom serialization by adding writeObject and readObject methods - see Serializable javadoc or aforementioned chapter 11.)

Install Visual Studio 2013 on Windows 7

Visual Studio Express for Windows needs Windows 8.1. Having a look at the requirements page you might want to try the Web or Windows Desktop version which are able to run under Windows 7.

How to terminate a python subprocess launched with shell=True

When shell=True the shell is the child process, and the commands are its children. So any SIGTERM or SIGKILL will kill the shell but not its child processes, and I don't remember a good way to do it. The best way I can think of is to use shell=False, otherwise when you kill the parent shell process, it will leave a defunct shell process.

How to perform string interpolation in TypeScript?

In JavaScript you can use template literals:

let value = 100;
console.log(`The size is ${ value }`);

Handling Enter Key in Vue.js

For enter event handling you can use

  1. @keyup.enter or
  2. @keyup.13

13 is the keycode of enter. For @ key event, the keycode is 50. So you can use @keyup.50.

For example:

<input @keyup.50="atPress()" />

Jquery, Clear / Empty all contents of tbody element?

jQuery:

$("#tbodyid").empty();

HTML:

<table>
    <tbody id="tbodyid">
        <tr>
            <td>something</td>
        </tr>
    </tbody>
</table>

Works for me
http://jsfiddle.net/mbsh3/

Is there an alternative to string.Replace that is case-insensitive?

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
    StringBuilder sb = new StringBuilder();

    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1)
    {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));

    return sb.ToString();
}

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

Remove all items from a FormArray in Angular

Or you can simply clear the controls

this.myForm= {
     name: new FormControl(""),
     desc: new FormControl(""),
     arr: new FormArray([])
}

Add something array

const arr = <FormArray>this.myForm.controls.arr;
arr.push(new FormControl("X"));

Clear the array

const arr = <FormArray>this.myForm.controls.arr;
arr.controls = [];

When you have multiple choices selected and clear, sometimes it doesn't update the view. A workaround is to add

arr.removeAt(0)

UPDATE

A more elegant solution to use form arrays is using a getter at the top of your class and then you can access it.

get inFormArray(): FormArray {
    this.myForm.get('inFormArray') as FormArray;
}

And to use it in a template

<div *ngFor="let c of inFormArray; let i = index;" [formGroup]="i">
other tags...
</div>

Reset:

inFormArray.reset();

Push:

inFormArray.push(new FormGroup({}));

Remove value at index: 1

inFormArray.removeAt(1);

UPDATE 2:

Get partial object, get all errors as JSON and many other features, use the NaoFormsModule

JNI and Gradle in Android Studio

gradle supports ndk compilation by generating another Android.mk file with absolute paths to your sources. NDK supports absolute paths since r9 on OSX, r9c on Windows, so you need to upgrade your NDK to r9+.

You may run into other troubles as NDK support by gradle is preliminary. If so you can deactivate the ndk compilation from gradle by setting:

sourceSets.main {
    jni.srcDirs = []
    jniLibs.srcDir 'src/main/libs'
}

to be able to call ndk-build yourself and integrate libs from libs/.

btw, you have any issue compiling for x86 ? I see you haven't included it in your APP_ABI.

iterating over and removing from a map

Use a real iterator.

Iterator<Object> it = map.keySet().iterator();

while (it.hasNext())
{
  it.next();
  if (something)
    it.remove();
 }

Actually, you might need to iterate over the entrySet() instead of the keySet() to make that work.

Ignore 'Security Warning' running script from command line

Try this, edit the file with:

notepad foo.ps1:Zone.Identifier

And set 'ZoneId=0'

How to split a delimited string in Ruby and convert it to an array?

For String Integer without space as String

arr = "12345"

arr.split('')

output: ["1","2","3","4","5"]

For String Integer with space as String

arr = "1 2 3 4 5"

arr.split(' ')

output: ["1","2","3","4","5"]

For String Integer without space as Integer

arr = "12345"

arr.split('').map(&:to_i)

output: [1,2,3,4,5]

For String

arr = "abc"

arr.split('')

output: ["a","b","c"]

Explanation:

  1. arr -> string which you're going to perform any action.
  2. split() -> is an method, which split the input and store it as array.
  3. '' or ' ' or ',' -> is an value, which is needed to be removed from given string.

Clearing an HTML file upload field via JavaScript

Just another one for the pot but you can actually change the type of an input. If you set the type to text, then back to file, it seems to reset the element.

var myFileInput = document.getElementById('myfileinput');
myFileInput.type = "text";
myFileInput.type = "file";

It resets. Tested in Google Chrome, Opera, Edge, IE 11

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

How do I create a custom Error in JavaScript?

The following worked for me taken from the official Mozilla documentation Error.

function NotImplementedError(message) {
    var instance = new Error(message);
    instance.name = 'NotImplementedError';

    Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
    if (Error.captureStackTrace) {
        Error.captureStackTrace(instance, NotImplementedError);
    }
    return instance;
}

NotImplementedError.prototype = Object.create(Error.prototype, {
    constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
    }
});

What is the right way to write my script 'src' url for a local development environment?

Write the src tag for calling the js file as

<script type='text/javascript' src='../Users/myUserName/Desktop/myPage.js'></script>

This should work.

How can I send large messages with Kafka (over 15MB)?

You need to adjust three (or four) properties:

  • Consumer side:fetch.message.max.bytes - this will determine the largest size of a message that can be fetched by the consumer.
  • Broker side: replica.fetch.max.bytes - this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
  • Broker side: message.max.bytes - this is the largest size of the message that can be received by the broker from a producer.
  • Broker side (per topic): max.message.bytes - this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes.)

I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.

Order of execution of tests in TestNG

There are ways of executing tests in a given order. Normally though, tests have to be repeatable and independent to guarantee it is testing only the desired functionality and is not dependent on side effects of code outside of what is being tested.

So, to answer your question, you'll need to provide more information such as WHY it is important to run tests in a specific order.

How to switch from POST to GET in PHP CURL

Add this before calling curl_exec($curl_handle)

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');

what is .subscribe in angular?

.subscribe is not an Angular2 thing.

It's a method that comes from rxjs library which Angular is using internally.

If you can imagine yourself subscribing to a newsletter, every time there is a new newsletter, they will send it to your home (the method inside subscribe gets called).

That's what happens when you subscribing to a source of magazines ( which is called an Observable in rxjs library)

All the AJAX calls in Angular are using rxjs internally and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.

Also, when writing this code <button (click)="doSomething()">, Angular is using Observables internally and subscribes you to that source of event, which in this case is a click event.

Back to our analogy of Observables and newsletter stores, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe from them for which you have to remember the subscription number or id, which in rxjs case it would be like :

 let subscription = magazineStore.getMagazines().subscribe(
   (newMagazine)=>{

         console.log('newMagazine',newMagazine);

    }); 

And when you don't want to get the magazines anymore:

   subscription.unsubscribe();

Also, the same goes for

 this.route.paramMap

which is returning an Observable and then you're subscribing to it.

My personal view is rxjs was one of the greatest things that were brought to JavaScript world and it's even better in Angular.

There are 150~ rxjs methods ( very similar to lodash methods) and the one that you're using is called switchMap

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

This is old, but someone else may stumble on it as I did. When you connect to the DataCast, you are talking to a daemon that can access the database. It was intended that a customer would write some code to access the database and store the results somewhere. It just happens that telnet works to access data manually. netcat should also work. ssh obviously will not.

How to iterate a table rows with JQuery and access some cell values?

$("tr.item").each(function() {
  $this = $(this);
  var value = $this.find("span.value").html();
  var quantity = $this.find("input.quantity").val();
});

Getting the number of filled cells in a column (VBA)

To find the last filled column use the following :

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

HTML input - name vs. id

If you are using JavaScript/CSS, you must use 'id' of control to apply any CSS/JavaScript stuff on it.

If you use name, CSS won't work for that control. As an example, if you use a JavaScript calendar attached to a textbox, you must use id of text control to assign it the JavaScript calendar.

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

How to export JSON from MongoDB using Robomongo

There are a few MongoDB GUIs out there, some of them have built-in support for data exporting. You'll find a comprehensive list of MongoDB GUIs at http://mongodb-tools.com

You've asked about exporting the results of your query, and not about exporting entire collections. Give 3T MongoChef MongoDB GUI a try, this tool has support for your specific use case.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

There are two main differences.

Accessing the association sides

The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.

So, for a unidirectional @ManyToOne association, it means you can only access the relationship from the child side where the foreign key resides.

If you have a unidirectional @OneToMany association, it means you can only access the relationship from the parent side which manages the foreign key.

For the bidirectional @OneToMany association, you can navigate the association in both ways, either from the parent or from the child side.

You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.

Performance

The second aspect is related to performance.

  1. For @OneToMany, unidirectional associations don't perform as well as bidirectional ones.
  2. For @OneToOne, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.
  3. For @ManyToMany, the collection type makes quite a difference as Sets perform better than Lists.

How to show shadow around the linearlayout in Android?

Well, this is easy to achieve .

Just build a GradientDrawable that comes from black and goes to a transparent color, than use parent relationship to place your shape close to the View that you want to have a shadow, then you just have to give any values to height or width .

Here is an example, this file have to be created inside res/drawable , I name it as shadow.xml :

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

    <gradient
        android:startColor="#9444"
        android:endColor="#0000"
        android:type="linear"
        android:angle="90"> <!-- Change this value to have the correct shadow angle, must be multiple from 45 -->
    </gradient>

</shape>

Place the following code above from a LinearLayout , for example, set the android:layout_width and android:layout_height to fill_parent and 2.3dp, you'll have a nice shadow effect on your LinearLayout .

<View
    android:id="@+id/shadow"
    android:layout_width="fill_parent"
    android:layout_height="2.3dp"  
    android:layout_above="@+id/id_from_your_LinearLayout" 
    android:background="@drawable/shadow">
</View>

Note 1: If you increase android:layout_height more shadow will be shown .

Note 2: Use android:layout_above="@+id/id_from_your_LinearLayout" attribute if you are placing this code inside a RelativeLayout, otherwise ignore it.

Hope it help someone.

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

If you want to run inside a background service and take the data in foreground use the below one, it is tested and verified.

public class MyService extends Service 
        implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, 
        GoogleApiClient.OnConnectionFailedListener, 
        com.google.android.gms.location.LocationListener {


    private static final int ASHIS = 1234;
    Intent intentForPendingIntent;
    HandlerThread handlerThread;
    Looper looper;
    GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRrequest;
    private static final int UPDATE_INTERVAL = 1000;
    private static final int FASTEST_INTERVAL = 100;
    private static final int DSIPLACEMENT_UPDATES = 1;
    ;
    private Handler handler1;
    private Runnable runable1;
    private Location mLastLocation;
    private float waitingTime;
    private int waiting2min;
    private Location locationOld;
    private double distance;
    private float totalWaiting;
    private float speed;
    private long timeGpsUpdate;
    private long timeOld;
    private NotificationManager mNotificationManager;
    Notification notification;
    PendingIntent resultPendingIntent;
    NotificationCompat.Builder mBuilder;


    // Sets an ID for the notification
    int mNotificationId = 001;
    private static final String TAG = "BroadcastService";
    public static final String BROADCAST_ACTION = "speedExceeded";
    private final Handler handler = new Handler();
    Intent intentforBroadcast;
    int counter = 0;
    private Runnable sendUpdatesToUI;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(MyService.this, "binder", Toast.LENGTH_SHORT).show();

        return null;
    }


    @Override
    public void onCreate() {
        showNotification();
        intentforBroadcast  = new Intent(BROADCAST_ACTION);

        Toast.makeText(MyService.this, "created", Toast.LENGTH_SHORT).show();

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        createLocationRequest();
        mGoogleApiClient.connect();


    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void showNotification() {

        mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_media_play)
                        .setContentTitle("Total Waiting Time")
                        .setContentText(totalWaiting+"");


        Intent resultIntent = new Intent(this, trackingFusion.class);

        // Because clicking the notification opens a new ("special") activity, there's
        // no need to create an artificial back stack.
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Builds the notification and issues it.

        mNotifyMgr.notify(mNotificationId, mBuilder.build());


        startForeground(001, mBuilder.getNotification());
    }


    @Override
    public void onLocationChanged(Location location) {

        //handler.removeCallbacks(runable);

        Toast.makeText(MyService.this, "speed" + speed, Toast.LENGTH_SHORT).show();
        timeGpsUpdate = location.getTime();
        float delta = (timeGpsUpdate - timeOld) / 1000;
        if (location.getAccuracy() < 100) {
            speed = location.getSpeed();
            distance += mLastLocation.distanceTo(location);
            Log.e("distance", "onLocationChanged: " + distance);
            //mLastLocation = location;
            //newLocation = mLastLocation;

            Log.e("location:", location + "");


            //speed = (long) (distance / delta);


            locationOld = location;
            mLastLocation = location;

            diaplayViews();
        }

        diaplayViews();
     /*if (map != null) {
         map.addMarker(new MarkerOptions()
                 .position(new LatLng(location.getLatitude(), location.getLongitude()))
                 .title("Hello world"));


     }*/
    }


    private void createLocationRequest() {

        mLocationRrequest = new LocationRequest();

        mLocationRrequest.setInterval(UPDATE_INTERVAL);
        mLocationRrequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRrequest.setSmallestDisplacement(DSIPLACEMENT_UPDATES);

    }


    private void methodToCalculateWaitingTime() {


        if (handler1 != null) {
            handler1.removeCallbacks(runable1);

        }


        Log.e("Here", "here1");
        handler1 = new Handler(Looper.getMainLooper());
        runable1 = new Runnable() {
            public void run() {

                Log.e("Here", "here2:" + mLastLocation.getSpeed());


                if (mLastLocation != null) {
                    diaplayViews();
                    if ((mLastLocation.getSpeed() == 0.0)) {

                        increaseTime();

                    } else {
                        if (waitingTime <= 120) {
                            waiting2min = 0;

                        }
                    }
                    handler1.postDelayed(this, 10000);
                } else {
                    if (ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }

                    locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mLastLocation = locationOld;

                }
            }
        };

        handler1.postDelayed(runable1, 10000);


    }

    private void diaplayViews() {
        float price = (float) (14 + distance * 0.5);

        //textDistance.setText(waitingTime);a
    }


    private void increaseTime() {
        waiting2min = waiting2min + 10;
        if (waiting2min >= 120)

        {
            if (waiting2min == 120) {
                waitingTime = waitingTime + 2 * 60;


            } else {
                waitingTime = waitingTime + 10;
            }


            totalWaiting = waitingTime / 60;
            showNotification();
            Log.e("waiting Time", "increaseTime: " + totalWaiting);
        }


    }

    @Override
    public void onDestroy() {
        Toast.makeText(MyService.this, "distroyed", Toast.LENGTH_SHORT).show();
        if (mGoogleApiClient.isConnected()) {

            mGoogleApiClient.disconnect();
        }
        mGoogleApiClient.disconnect();

    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.e("Connection_fusion", "connected");

        startLocationUpdates();


    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    private void startLocationUpdates() {
        Location location = plotTheInitialMarkerAndGetInitialGps();
        if (location == null) {
            plotTheInitialMarkerAndGetInitialGps();


        } else {

            mLastLocation = location;
            methodToCalculateWaitingTime();
        }
    }

    private Location plotTheInitialMarkerAndGetInitialGps() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRrequest, this);
        locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if ((locationOld != null)) {
            mLastLocation = locationOld;

            timeOld = locationOld.getTime();
        } else {
            startLocationUpdates();
        }

        return mLastLocation;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        Toast.makeText(MyService.this, "start command", Toast.LENGTH_SHORT).show();

        sendUpdatesToUI = new Runnable() {
            public void run() {
                DisplayLoggingInfo();
                handler.postDelayed(this, 10000); // 5 seconds
            }
        };
        handler.postDelayed(sendUpdatesToUI, 10000); // 1 second
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        return START_NOT_STICKY;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        sendUpdatesToUI = new Runnable() {
            public void run() {
                Log.e("sent", "sent");
                DisplayLoggingInfo();
                handler.postDelayed(this, 5000); // 5 seconds
            }
        };
        handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        super.onStart(intent, startId);
    }

    private void DisplayLoggingInfo() {
        Log.d(TAG, "entered DisplayLoggingInfo");
        intentforBroadcast.putExtra("distance", distance);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intentforBroadcast);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

    }
}

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

How to change onClick handler dynamically?

I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:

document.getElementById("foo").onclick = function (event){alert('foo');};

or in jQuery:

$('#foo').click(function(event) { alert('foo'); }

Most efficient way to remove special characters from string

A regular expression will look like:

public string RemoveSpecialChars(string input)
{
    return Regex.Replace(input, @"[^0-9a-zA-Z\._]", string.Empty);
}

But if performance is highly important, I recommend you to do some benchmarks before selecting the "regex path"...

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

$.focus() not working

I also had this problem. The solution that worked in my case was using the tabindex property on the HTML element.

I was using ng-repeat for some li elements inside a list and I was not able to bring focus to the first li using .focus(), so I simply added the tabindex attribute to each li during the loop.

so now <li ng-repeat="user in users track by $index" tabindex="{{$index+1}}"></li>

That +1 was index starts from 0. Also make sure that the element is present in DOM before calling the .focus() function

I hope this helps.

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

Replace contents of factor column in R dataframe

In case you have to replace multiple values and if you don't mind "refactoring" your variable with as.factor(as.character(...)) you could try the following:

replace.values <- function(search, replace, x){
  stopifnot(length(search) == length(replace))
  xnew <- replace[ match(x, search) ]
  takeOld <- is.na(xnew) & !is.na(x)
  xnew[takeOld] <- x[takeOld]
  return(xnew)
}

iris$Species <- as.factor(search=c("oldValue1","oldValue2"),
                          replace=c("newValue1","newValue2"),
                          x=as.character(iris$Species))

jQuery Ajax PUT with parameters

You can use the PUT method and pass data that will be included in the body of the request:

let data = {"key":"value"}

$.ajax({
    type: 'PUT',
    url: 'http://example.com/api',
    contentType: 'application/json',
    data: JSON.stringify(data), // access in body
}).done(function () {
    console.log('SUCCESS');
}).fail(function (msg) {
    console.log('FAIL');
}).always(function (msg) {
    console.log('ALWAYS');
});

stop service in android

This code works for me: check this link
This is my code when i stop and start service in activity

case R.id.buttonStart:
  Log.d(TAG, "onClick: starting srvice");
  startService(new Intent(this, MyService.class));
  break;
case R.id.buttonStop:
  Log.d(TAG, "onClick: stopping srvice");
  stopService(new Intent(this, MyService.class));
  break;
}
}
 }

And in service class:

  @Override
public void onCreate() {
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

    player = MediaPlayer.create(this, R.raw.braincandy);
    player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onDestroy");
    player.stop();
}

HAPPY CODING!

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

No signing certificate "iOS Distribution" found

enter image description here

Solution Steps:

  1. Unchecked "Automatically manage signing".

  2. Select "Provisioning profile" in "Signing (Release)" section.

  3. No signing certificate error will be show.

  4. Then below the error has a "Manage Certificates" button. click the button.

enter image description here

  1. This window will come. Click the + sign and click "iOS Distribution". xcode will create the private key for your distribution certificate and error will be gone.

Jackson JSON custom serialization for certain fields

You can implement a custom serializer as follows:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = IntToStringSerializer.class, as=String.class)
    public int favoriteNumber:
}


public class IntToStringSerializer extends JsonSerializer<Integer> {

    @Override
    public void serialize(Integer tmpInt, 
                          JsonGenerator jsonGenerator, 
                          SerializerProvider serializerProvider) 
                          throws IOException, JsonProcessingException {
        jsonGenerator.writeObject(tmpInt.toString());
    }
}

Java should handle the autoboxing from int to Integer for you.

Clone an image in cv2 python

The first answer is correct but you say that you are using cv2 which inherently uses numpy arrays. So, to make a complete different copy of say "myImage":

newImage = myImage.copy()

The above is enough. No need to import numpy.

How to sort findAll Doctrine's method?

You need to use a criteria, for example:

<?php

namespace Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;

/**
* Thing controller
*/
class ThingController extends Controller
{
    public function thingsAction(Request $request, $id)
    {
        $ids=explode(',',$id);
        $criteria = new Criteria(null, <<DQL ordering expression>>, null, null );

        $rep    = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
        $things = $rep->matching($criteria);
        return $this->render('Bundle:Thing:things.html.twig', [
            'entities' => $things,
        ]);
    }
}

Could not find server 'server name' in sys.servers. SQL Server 2014

I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers still had the old server name.

I had to drop the old server name and add the new server name to sys.servers on the new server

sp_dropserver 'Server_A'
GO
sp_addserver  'Server',local
GO

Batch / Find And Edit Lines in TXT file

@echo off
set "replace=something"
set "replaced=different"

set "source=Source.txt"
set "target=Target.txt"

setlocal enableDelayedExpansion
(
   for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %source%') do (
      set "line=%%b"
      if defined line set "line=!line:%replace%=%replaced%!"
      echo(!line!
   )
) > %target%
endlocal

Source. Hoping it will help some one.

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

Deserializing a JSON into a JavaScript object

You could also use eval() but JSON.parse() is safer and easier way, so why would you?

good and works

var yourJsonObject = JSON.parse(json_as_text);

I don't see any reason why would you prefer to use eval. It only puts your application at risk.

That said - this is also possible.

bad - but also works

var yourJsonObject = eval(json_as_text);

Why is eval a bad idea?

Consider the following example.

Some third party or user provided JSON string data.

var json = `
[{
    "adjacencies": [
        {
          "nodeTo": function(){
            return "delete server files - you have been hacked!";
          }(),
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}]
`;

Your server-side script processes that data.

Using JSON.parse:

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}

will throw:

Uncaught SyntaxError: Unexpected token u in JSON at position X. 

Function will not get executed.

You are safe.

Using eval():

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}

will execute the function and return the text.

If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.

You are NOT safe.

I was able to manipulate a JSON text string so it acts as a function which will execute on the server.

eval(JSON)[0].adjacencies[0].nodeTo expects to process a JSON string but, in reality, we just executed a function on our server.

This could also be prevented if we server-side check all user-provided data before passing it to an eval() function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?

How to do the equivalent of pass by reference for primitives in Java

For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:

import java.util.concurrent.atomic.AtomicInteger;


public class PrimitivePassByReferenceSample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        AtomicInteger myNumber = new AtomicInteger(0);
        System.out.println("MyNumber before method Call:" + myNumber.get());
        PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
        temp.changeMyNumber(myNumber);
        System.out.println("MyNumber After method Call:" + myNumber.get());


    }

     void changeMyNumber(AtomicInteger myNumber) {
        myNumber.getAndSet(100);

    }

}

Output:

MyNumber before method Call:0

MyNumber After method Call:100

Create an ArrayList of unique values

Solution #1: HashSet

A good solution to the immediate problem of reading a file into an ArrayList with a uniqueness constraint is to simply keep a HashSet of seen items. Before processing a line, we check that its key is not already in the set. If it isn't, we add the key to the set to mark it as finished, then add the line data to the result ArrayList.

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) 
        throws FileNotFoundException, IOException {

        String file = "prova.txt";
        ArrayList<String[]> data = new ArrayList<>();
        HashSet<String> seen = new HashSet<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line; (line = br.readLine()) != null;) {
                String[] split = line.split("\\s+");
                String key = split[0] + " " + split[1];

                if (!seen.contains(key)) {
                    data.add(Arrays.copyOfRange(split, 2, split.length));
                    seen.add(key);
                }
            }
        }

        for (String[] row : data) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Solution #2: LinkedHashMap/LinkedHashSet

Since we have key-value pairs in this particular dataset, we could roll everything into a LinkedHashMap<String, ArrayList<String>> (see docs for LinkedHashMap) which preserves ordering but can't be indexed into (use-case driven decision, but amounts to the same strategy as above. ArrayList<String> or String[] is arbitrary here--it could be any data value). Note that this version makes it easy to preserve the most recently seen key rather than the oldest (remove the !data.containsKey(key) test).

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) 
        throws FileNotFoundException, IOException {

        String file = "prova.txt";
        LinkedHashMap<String, ArrayList<String>> data = new LinkedHashMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line; (line = br.readLine()) != null;) {
                String[] split = line.split("\\s+");
                String key = split[0] + " " + split[1];

                if (!data.containsKey(key)) {
                    ArrayList<String> val = new ArrayList<>();
                    String[] sub = Arrays.copyOfRange(split, 2, split.length); 
                    Collections.addAll(val, sub);
                    data.put(key, val);
                }
            }
        }

        for (Map.Entry<String, ArrayList<String>> e : data.entrySet()) {
            System.out.println(e.getKey() + " => " + e.getValue());
        }
    }
}

Solution #3: ArrayListSet

The above examples represent pretty narrow use cases. Here's a sketch for a general ArrayListSet class, which maintains the usual list behavior (add/set/remove etc) while preserving uniqueness.

Basically, the class is an abstraction of solution #1 in this post (HashSet combined with ArrayList), but with a slightly different flavor (the data itself is used to determine uniqueness rather than a key, but it's a truer "ArrayList" structure).

This class solves the problems of efficiency (ArrayList#contains is linear, so we should reject that solution except in trivial cases), lack of ordering (storing everything directly in a HashSet doesn't help us), lack of ArrayList operations (LinkedHashSet is otherwise the best solution but we can't index into it, so it's not a true replacement for an ArrayList).

Using a HashMap<E, index> instead of a HashSet would speed up remove(Object o) and indexOf(Object o) functions (but slow down sort). A linear remove(Object o) is the main drawback over a plain HashSet.

import java.util.*;

public class ArrayListSet<E> implements Iterable<E>, Set<E> {
    private ArrayList<E> list;
    private HashSet<E> set;

    public ArrayListSet() {
        list = new ArrayList<>();
        set = new HashSet<>();
    }

    public boolean add(E e) {
        return set.add(e) && list.add(e);
    }

    public boolean add(int i, E e) {
        if (!set.add(e)) return false;
        list.add(i, e);
        return true;
    }

    public void clear() {
        list.clear();
        set.clear();
    }

    public boolean contains(Object o) {
        return set.contains(o);
    }

    public E get(int i) {
        return list.get(i);
    }

    public boolean isEmpty() {
        return list.isEmpty();
    }

    public E remove(int i) {        
        E e = list.remove(i);
        set.remove(e);
        return e;
    }

    public boolean remove(Object o) {        
        if (set.remove(o)) {
            list.remove(o);
            return true;
        }

        return false;
    }

    public boolean set(int i, E e) {
        if (set.contains(e)) return false;

        set.add(e);
        set.remove(list.set(i, e));
        return true;
    }

    public int size() {
        return list.size();
    }

    public void sort(Comparator<? super E> c) {
        Collections.sort(list, c);
    }

    public Iterator<E> iterator() {
        return list.iterator();
    }

    public boolean addAll(Collection<? extends E> c) {
        int before = size();
        for (E e : c) add(e);
        return size() == before;
    }

    public boolean containsAll(Collection<?> c) {
        return set.containsAll(c);
    }

    public boolean removeAll(Collection<?> c) {
        return set.removeAll(c) && list.removeAll(c);
    }

    public boolean retainAll(Collection<?> c) {
         return set.retainAll(c) && list.retainAll(c);
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

Example usage:

public class ArrayListSetDriver {
    public static void main(String[] args) {
        ArrayListSet<String> fruit = new ArrayListSet<>();
        fruit.add("apple");
        fruit.add("banana");
        fruit.add("kiwi");
        fruit.add("strawberry");
        fruit.add("apple");
        fruit.add("strawberry");

        for (String item : fruit) {
            System.out.print(item + " "); // => apple banana kiwi strawberry
        }

        fruit.remove("kiwi");
        fruit.remove(1);
        fruit.add(0, "banana");
        fruit.set(2, "cranberry");
        fruit.set(0, "cranberry");
        System.out.println();

        for (int i = 0; i < fruit.size(); i++) {
            System.out.print(fruit.get(i) + " "); // => banana apple cranberry
        }

        System.out.println();
    }
}

Solution #4: ArrayListMap

This class solves a drawback of ArrayListSet which is that the data we want to store and its associated key may not be the same. This class provides a put method that enforces uniqueness on a different object than the data stored in the underlying ArrayList. This is just what we need to solve the original problem posed in this thread. This gives us the ordering and iteration of an ArrayList but fast lookups and uniqueness properties of a HashMap. The HashMap contains the unique values mapped to their index locations in the ArrayList, which enforces ordering and provides iteration.

This approach solves the scalability problems of using a HashSet in solution #1. That approach works fine for a quick file read, but without an abstraction, we'd have to handle all consistency operations by hand and pass around multiple raw data structures if we needed to enforce that contract across multiple functions and over time.

As with ArrayListSet, this can be considered a proof of concept rather than a full implementation.

import java.util.*;

public class ArrayListMap<K, V> implements Iterable<V>, Map<K, V> {
    private ArrayList<V> list;
    private HashMap<K, Integer> map;

    public ArrayListMap() {
        list = new ArrayList<>();
        map = new HashMap<>();
    }

    public void clear() {
        list.clear();
        map.clear();
    }

    public boolean containsKey(Object key) {
        return map.containsKey(key);
    }

    public boolean containsValue(Object value) {
        return list.contains(value);
    }

    public V get(int i) {
        return list.get(i);
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public V get(Object key) {
        return list.get(map.get(key));
    }

    public V put(K key, V value) {
        if (map.containsKey(key)) {
            int i = map.get(key);
            V v = list.get(i);
            list.set(i, value);
            return v;
        }

        list.add(value);
        map.put(key, list.size() - 1);
        return null;
    }

    public V putIfAbsent(K key, V value) {
        if (map.containsKey(key)) {
            if (list.get(map.get(key)) == null) {
                list.set(map.get(key), value);
                return null;
            }

            return list.get(map.get(key));
        }

        return put(key, value);
    }

    public V remove(int i) {
        V v = list.remove(i);

        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            if (entry.getValue() == i) {
                map.remove(entry.getKey());
                break;
            }
        }

        decrementMapIndices(i);
        return v;
    }

    public V remove(Object key) {
        if (map.containsKey(key)) {
            int i = map.remove(key);
            V v = list.get(i);
            list.remove(i);
            decrementMapIndices(i);
            return v;
        }

        return null;
    }

    private void decrementMapIndices(int start) {
        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            int i = entry.getValue();

            if (i > start) {
                map.put(entry.getKey(), i - 1);
            }
        }
    }

    public int size() {
        return list.size();
    }

    public void putAll(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    public Set<Map.Entry<K, V>> entrySet() {
        Set<Map.Entry<K, V>> es = new HashSet<>();

        for (Map.Entry<K, Integer> entry : map.entrySet()) {
            es.add(new AbstractMap.SimpleEntry<>(
                entry.getKey(), list.get(entry.getValue())
            ));
        }

        return es;
    }

    public Set<K> keySet() {
        return map.keySet();
    }

    public Collection<V> values() {
        return list;
    }

    public Iterator<V> iterator() {
        return list.iterator();
    }

    public Object[] toArray() {
        return list.toArray();
    }

    public <T> T[] toArray(T[] a) {
        return list.toArray(a);
    }
}

Here's the class in action on the original problem:

import java.io.*;

public class Main {
    public static void main(String[] args) 
        throws FileNotFoundException, IOException {

        String file = "prova.txt";
        ArrayListMap<String, String[]> data = new ArrayListMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (String line; (line = br.readLine()) != null;) {
                String[] split = line.split("\\s+");
                String key = split[0] + " " + split[1];
                String[] sub = Arrays.copyOfRange(split, 2, split.length); 
                data.putIfAbsent(key, sub); 
            }
        }

        for (Map.Entry<String, String[]> e : data.entrySet()) {
            System.out.println(e.getKey() + " => " + 
                java.util.Arrays.toString(e.getValue()));
        }

        for (String[] a : data) {
            System.out.println(java.util.Arrays.toString(a));
        }
    }
}

How do I install an R package from source?

From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection:

library(devtools)
install_github("twitter/AnomalyDetection")

does the trick.

How to convert int to char with leading zeros?

In my case I wanted my field to have leading 0's in 10 character field (NVARCHAR(10)). The source file does not have the leading 0's needed to then join to in another table. Did this simply due to being on SQL Server 2008R2:

Set Field = right(('0000000000' + [Field]),10) (Can't use Format() as this is pre SQL2012)

Performed this against the existing data. So this way 1 or 987654321 will still fill all 10 spaces with leading 0's.

As the new data is being imported & then dumped to the table through an Access database, I am able to use Format([Field],"0000000000") when appending from Access to the SQL server table for any new records.

How to convert PDF files to images

I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.

/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
    using var pdfDocument = new PdfDocument(pdfPath);
    var firstPage = pdfDocument.Pages[0];

    using var pageBitmap = new PDFiumBitmap(width, height, true);

    firstPage.Render(pageBitmap);

    var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
        ? Path.ChangeExtension(pdfPath, "jpg")
        : thumbnailPath;
    var image = Image.Load(pageBitmap.AsBmpStream());

    // Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
    image.Mutate(x => x.BackgroundColor(Rgba32.White));

    image.Save(imageJpgPath, new JpegEncoder());
}

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

Try to give the full path to your csv file

open('/users/gcameron/Desktop/map/data.csv')

The python process is looking for file in the directory it is running from.

DIV table colspan: how?

I would imagine that this would be covered by CSS Tables, a specification which, while mentioned on the CSS homepage, appears to currently be at a state of "not yet published in any form"

In practical terms, you can't achieve this at present.

Transform DateTime into simple Date in Ruby on Rails

In Ruby 1.9.2 and above they added a .to_date function to DateTime:

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

This instance method doesn't appear to be present in earlier versions like 1.8.7.

HTML entity for the middle dot

Do you mean bulletpoints? • • •

&bull;

How to calculate growth with a positive and negative number?

Simplest solution is the following:

=(NEW/OLD-1)*SIGN(OLD)

The SIGN() function will result in -1 if the value is negative and 1 if the value is positive. So multiplying by that will conditionally invert the result if the previous value is negative.

How do I set a cookie on HttpClient's HttpRequestMessage

After spending hours on this issue, none of the answers above helped me so I found a really useful tool.

Firstly, I used Telerik's Fiddler 4 to study my Web Requests in details

Secondly, I came across this useful plugin for Fiddler:

https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode

It will just generate the C# code for you. An example was:

        var uriBuilder = new UriBuilder("test.php", "test");
        var httpClient = new HttpClient();


        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());



        httpRequestMessage.Headers.Add("Host", "test.com");
        httpRequestMessage.Headers.Add("Connection", "keep-alive");
     //   httpRequestMessage.Headers.Add("Content-Length", "138");
        httpRequestMessage.Headers.Add("Pragma", "no-cache");
        httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
        httpRequestMessage.Headers.Add("Origin", "test.com");
        httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
    //    httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
        httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
        httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
        httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");


        var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;

        var httpContent = httpResponseMessage.Content;
        string result = httpResponseMessage.Content.ReadAsStringAsync().Result;

Note that I had to comment out two lines as this plugin is not totally perfect yet but it did the job nevertheless.

DISCLAIMER: I am not associated or endorsed by either Telerik or the plugin's author in anyway.

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

How to run Node.js as a background process and never die?

Simple solution (if you are not interested in coming back to the process, just want it to keep running):

nohup node server.js &

There's also the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Powerful solution (allows you to reconnect to the process if it is interactive):

screen

You can then detach by pressing Ctrl+a+d and then attach back by running screen -r

Also consider the newer alternative to screen, tmux.

How to use Oracle's LISTAGG function with a unique filter?

select group_id, 
       listagg(name, ',') within group (order by name) as names
       over (partition by group_id)   
from demotable
group by group_id 

Serializing a list to JSON

.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespace and the DataContractJsonSerializer class since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.

That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.

The following code serializea a list to the console output stream. As you see it is a bit more verbose than Json.NET and not type-safe (ie no generics)

        var list = new List<string> {"a", "b", "c", "d"};

        using(var output = Console.OpenStandardOutput())                
        {                
            var writer = new DataContractJsonSerializer(typeof (List<string>));
            writer.WriteObject(output,list);
        }

On the other hand, Json.NET provides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.

Another option is ServiceStack.Text, part of the ServicStack ... stack, which provides a set of very fast serializers for Json, JSV and CSV.

How to redirect to Login page when Session is expired in Java web application?

When the use logs in, put its username in the session:

`session.setAttribute("USER", username);`

At the beginning of each page you can do this:

<%
String username = (String)session.getAttribute("USER");
if(username==null) 
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<% { } %>

Error: No default engine was specified and no extension was provided

If all that's needed is to send html code inline in the code, we can use below

var app = express();
app.get('/test.html', function (req, res) {
   res.header('Content-Type', 'text/html').send("<html>my html code</html>");
});

subtract time from date - moment js

Michael Richardson's solution is great. If you would like to subtract dates (because Google will point you here if you search for it), you could also say:

var date1 = moment( "2014-06-07 00:03:00" );
var date2 = moment( "2014-06-07 09:22:00" );

differenceInMs = date2.diff(date1); // diff yields milliseconds
duration = moment.duration(differenceInMs); // moment.duration accepts ms
differenceInMinutes = duration.asMinutes(); // if you would like to have the output 559

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

The problem could be:

  • the Application Pool for your site is configured for .NET Framework Version = v2.0.XXXXX
  • .NET 4 isn't installed on your server.

See also

... which helped me fix a similar issue.

use jQuery to get values of selected checkboxes

var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

Write to Windows Application Event Log

You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):

var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");

However, you'll need to configure this source "MySource" using administrative privileges:

Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

What is the reason behind "non-static method cannot be referenced from a static context"?

I just realized, I think people shouldn't be exposed to the concept of "static" very early.

Static methods should probably be the exception rather than the norm. Especially early on anyways if you want to learn OOP. (Why start with an exception to the rule?) That's very counter-pedagogical of Java, that the "first" thing you should learn is the public static void main thing. (Few real Java applications have their own main methods anyways.)

How to do this in Laravel, subquery where in

The following code worked for me:

$result=DB::table('tablename')
->whereIn('columnName',function ($query) {
                $query->select('columnName2')->from('tableName2')
                ->Where('columnCondition','=','valueRequired');

            })
->get();

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

For CGSize

CGSize(width: self.view.frame.width * 3, height: self.view.frame.size.height)

How to listen for changes to a MongoDB collection?

Alternatively, you could use the standard Mongo FindAndUpdate method, and within the callback, fire an EventEmitter event (in Node) when the callback is run.

Any other parts of the application or architecture listening to this event will be notified of the update, and any relevant data sent there also. This is a really simple way to achieve notifications from Mongo.