Programs & Examples On #Compareto

The CompareTo method is found in the .NET Framework and Java and imposes the natural ordering of a class. This is done by returning a negative integer, zero, or a positive integer as the instance of the implementing class is less than, equal to, or greater than the object it is compared to.

How do I write a compareTo method which compares objects?

if (s.compareTo(t) > 0) will compare string s to string t and return the int value you want.

    public int Compare(Object obj) // creating a method to compare {   
        Student s = (Student) obj; //creating a student object

        // compare last names
        return  this.lastName.compareTo(s.getLastName());    
    }

Now just test for a positive negative return from the method as you would have normally.

Cheers

compareTo with primitives -> Integer / int

If you are using java 8, you can create Comparator by this method:

Comparator.comparingInt(i -> i);

if you would like to compare with reversed order:

Comparator.comparingInt(i -> -i);

BigDecimal equals() versus compareTo()

The answer is in the JavaDoc of the equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

As to why equals() behaves this way, this has been answered in this SO question.

How to simplify a null-safe compareTo() implementation?

If you want a simple Hack:

arrlist.sort((o1, o2) -> {
    if (o1.getName() == null) o1.setName("");
    if (o2.getName() == null) o2.setName("");

    return o1.getName().compareTo(o2.getName());
})

if you want put nulls to end of the list just change this in above metod

return o2.getName().compareTo(o1.getName());

compareTo() vs. equals()

compareTo has do do more work if the strings have different lengths. equals can just return false, while compareTo must always examine enough characters to find the sorting order.

Splitting string into multiple rows in Oracle

In Oracle 11g and later, you can use a recursive sub-query and simple string functions (which may be faster than regular expressions and correlated hierarchical sub-queries):

Oracle Setup:

CREATE TABLE table_name ( name, project, error ) as
 select 108, 'test',  'Err1, Err2, Err3' from dual union all
 select 109, 'test2', 'Err1'             from dual;

Query:

WITH table_name_error_bounds ( name, project, error, start_pos, end_pos ) AS (
  SELECT name,
         project,
         error,
         1,
         INSTR( error, ', ', 1 )
  FROM   table_name
UNION ALL
  SELECT name,
         project,
         error,
         end_pos + 2,
         INSTR( error, ', ', end_pos + 2 )
  FROM   table_name_error_bounds
  WHERE  end_pos > 0
)
SELECT name,
       project,
       CASE end_pos
       WHEN 0
       THEN SUBSTR( error, start_pos )
       ELSE SUBSTR( error, start_pos, end_pos - start_pos )
       END AS error
FROM   table_name_error_bounds

Output:

NAME | PROJECT | ERROR
---: | :------ | :----
 108 | test    | Err1 
 109 | test2   | Err1 
 108 | test    | Err2 
 108 | test    | Err3 

db<>fiddle here

How to update values in a specific row in a Python Pandas DataFrame?

If you have one large dataframe and only a few update values I would use apply like this:

import pandas as pd

df = pd.DataFrame({'filename' :  ['test0.dat', 'test2.dat'], 
                                  'm': [12, 13], 'n' : [None, None]})

data = {'filename' :  'test2.dat', 'n':16}

def update_vals(row, data=data):
    if row.filename == data['filename']:
        row.n = data['n']
    return row

df.apply(update_vals, axis=1)

Find the paths between two given nodes?

given the adjacency matrix:

{0, 1, 3, 4, 0, 0}

{0, 0, 2, 1, 2, 0}

{0, 1, 0, 3, 0, 0}

{0, 1, 1, 0, 0, 1}

{0, 0, 0, 0, 0, 6}

{0, 1, 0, 1, 0, 0}

the following Wolfram Mathematica code solve the problem to find all the simple paths between two nodes of a graph. I used simple recursion, and two global var to keep track of cycles and to store the desired output. the code hasn't been optimized just for the sake of code clarity. the "print" should be helpful to clarify how it works.

cycleQ[l_]:=If[Length[DeleteDuplicates[l]] == Length[l], False, True];
getNode[matrix_, node_]:=Complement[Range[Length[matrix]],Flatten[Position[matrix[[node]], 0]]];

builtTree[node_, matrix_]:=Block[{nodes, posAndNodes, root, pos},
    If[{node} != {} && node != endNode ,
        root = node;
        nodes = getNode[matrix, node];
        (*Print["root:",root,"---nodes:",nodes];*)

        AppendTo[lcycle, Flatten[{root, nodes}]];
        If[cycleQ[lcycle] == True,
            lcycle = Most[lcycle]; appendToTree[root, nodes];,
            Print["paths: ", tree, "\n", "root:", root, "---nodes:",nodes];
            appendToTree[root, nodes];

        ];
    ];

appendToTree[root_, nodes_] := Block[{pos, toAdd},
    pos = Flatten[Position[tree[[All, -1]], root]];
    For[i = 1, i <= Length[pos], i++,
        toAdd = Flatten[Thread[{tree[[pos[[i]]]], {#}}]] & /@ nodes;
        (* check cycles!*)            
        If[cycleQ[#] != True, AppendTo[tree, #]] & /@ toAdd;
    ];
    tree = Delete[tree, {#} & /@ pos];
    builtTree[#, matrix] & /@ Union[tree[[All, -1]]];
    ];
];

to call the code: initNode = 1; endNode = 6; lcycle = {}; tree = {{initNode}}; builtTree[initNode, matrix];

paths: {{1}} root:1---nodes:{2,3,4}

paths: {{1,2},{1,3},{1,4}} root:2---nodes:{3,4,5}

paths: {{1,3},{1,4},{1,2,3},{1,2,4},{1,2,5}} root:3---nodes:{2,4}

paths: {{1,4},{1,2,4},{1,2,5},{1,3,4},{1,2,3,4},{1,3,2,4},{1,3,2,5}} root:4---nodes:{2,3,6}

paths: {{1,2,5},{1,3,2,5},{1,4,6},{1,2,4,6},{1,3,4,6},{1,2,3,4,6},{1,3,2,4,6},{1,4,2,5},{1,3,4,2,5},{1,4,3,2,5}} root:5---nodes:{6}

RESULTS:{{1, 4, 6}, {1, 2, 4, 6}, {1, 2, 5, 6}, {1, 3, 4, 6}, {1, 2, 3, 4, 6}, {1, 3, 2, 4, 6}, {1, 3, 2, 5, 6}, {1, 4, 2, 5, 6}, {1, 3, 4, 2, 5, 6}, {1, 4, 3, 2, 5, 6}}

...Unfortunately I cannot upload images to show the results in a better way :(

http://textanddatamining.blogspot.com

json_encode(): Invalid UTF-8 sequence in argument

json_encode works only with UTF-8 data. You'll have to ensure that your data is in UTF-8. alternatively, you can use iconv() to convert your results to UTF-8 before feeding them to json_encode()

ScalaTest in sbt: is there a way to run a single test without tags?

I don't see a way to run a single untagged test within a test class but I am providing my workflow since it seems to be useful for anyone who runs into this question.

From within a sbt session:

test:testOnly *YourTestClass

(The asterisk is a wildcard, you could specify the full path com.example.specs.YourTestClass.)

All tests within that test class will be executed. Presumably you're most concerned with failing tests, so correct any failing implementations and then run:

test:testQuick

... which will only execute tests that failed. (Repeating the most recently executed test:testOnly command will be the same as test:testQuick in this case, but if you break up your test methods into appropriate test classes you can use a wildcard to make test:testQuick a more efficient way to re-run failing tests.)

Note that the nomenclature for test in ScalaTest is a test class, not a specific test method, so all untagged methods are executed.

If you have too many test methods in a test class break them up into separate classes or tag them appropriately. (This could be a signal that the class under test is in violation of single responsibility principle and could use a refactoring.)

What is the difference between required and ng-required?

I would like to make a addon for tiago's answer:

Suppose you're hiding element using ng-show and adding a required attribute on the same:

<div ng-show="false">
    <input required name="something" ng-model="name"/>
</div>

will throw an error something like :

An invalid form control with name='' is not focusable

This is because you just cannot impose required validation on hidden elements. Using ng-required makes it easier to conditionally apply required validation which is just awesome!!

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

Convert the first element of an array to a string in PHP

Convert array to a string in PHP:

Use the PHP join function like this:

$my_array = array(4,1,8);

print_r($my_array);
Array
(
    [0] => 4
    [1] => 1
    [2] => 8
)

$result_string = join(',' , $my_array);
echo $result_string;

Which delimits the items in the array by comma into a string:

4,1,8

wget ssl alert handshake failure

It works from here with same OpenSSL version, but a newer version of wget (1.15). Looking at the Changelog there is the following significant change regarding your problem:

1.14: Add support for TLS Server Name Indication.

Note that this site does not require SNI. But www.coursera.org requires it. And if you would call wget with -v --debug (as I've explicitly recommended in my comment!) you will see:

$ wget https://class.coursera.org
...
HTTP request sent, awaiting response...
  HTTP/1.1 302 Found
...
Location: https://www.coursera.org/ [following]
...
Connecting to www.coursera.org (www.coursera.org)|54.230.46.78|:443... connected.
OpenSSL: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Unable to establish SSL connection.

So the error actually happens with www.coursera.org and the reason is missing support for SNI. You need to upgrade your version of wget.

Loading/Downloading image from URL on Swift

Use this code in Swift

imageView.image=UIImage(data: NSData(contentsOfURL: NSURL(string: "http://myURL/ios8.png")!)!

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

.foo {
   position : relative;
}
.foo .wrapper {
    background-image : url('semi-trans.png');
    z-index : 10;
    position : absolute;
    top : 0;
    left : 0;
}

<div class="foo">
   <img src="example.png" />
   <div class="wrapper">&nbsp;</div>
</div>

Entity Framework rollback and remove bad migration

You can also use

Remove-Migration -Force

This will revert and remove the last applied migration

How to handle authentication popup with Selenium WebDriver using Java

I faced this issue a number of times in my application.

We can generally handle this with the below 2 approaches.

  1. Pass the username and password in url itself

  2. You can create an AutoIT Script and call script before opening the url.

Please check the below article in which I have mentioned both ways:
Handle Authentication/Login window in Selenium Webdriver

minimum double value in C/C++

Is there a standard and/or portable way to represent the smallest negative value (e.g. to use negative infinity) in a C(++) program?

C approach.

Many implementations support +/- infinities, so the most negative double value is -INFINITY.

#include <math.h>
double most_negative = -INFINITY;

Is there a standard and/or portable way ....?

Now we need to also consider other cases:

  • No infinities

Simply -DBL_MAX.

  • Only an unsigned infinity.

I'd expect in this case, OP would prefer -DBL_MAX.

  • De-normal values greater in magnitude than DBL_MAX.

This is an unusual case, likely outside OP's concern. When double is encoded as a pair of a floating points to achieve desired range/precession, (see double-double) there exist a maximum normal double and perhaps a greater de-normal one. I have seen debate if DBL_MAX should refer to the greatest normal, of the greatest of both.

Fortunately this paired approach usually includes an -infinity, so the most negative value remains -INFINITY.


For more portability, code can go down the route

// HUGE_VAL is designed to be infinity or DBL_MAX (when infinites are not implemented)
// .. yet is problematic with unsigned infinity.
double most_negative1 = -HUGE_VAL;  

// Fairly portable, unless system does not understand "INF"
double most_negative2 = strtod("-INF", (char **) NULL);

// Pragmatic
double most_negative3 = strtod("-1.0e999999999", (char **) NULL);

// Somewhat time-consuming
double most_negative4 = pow(-DBL_MAX, 0xFFFF /* odd value */);

// My suggestion
double most_negative5 = (-DBL_MAX)*DBL_MAX;

How to ssh from within a bash script?

  1. If you want the password prompt to go away then use key based authentication (described here).

  2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'

Return background color of selected cell

You can use Cell.Interior.Color, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).

How to check if a double is null?

How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull().

how to append a css class to an element by javascript?

When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.

Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.

document.addClass= function(el, css){
    var tem, C= el.className.split(/\s+/), A=[];    
    while(C.length){
        tem= C.shift();
        if(tem && tem!= css) A[A.length]= tem;
    }
    A[A.length]= css;
    return el.className= A.join(' ');   
}

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

I know this is an older question, but I thought I would also post my solution:

  • Update your Chrome on your phone and on your PC.
  • Even if it says you have the latest driver for your device inside Device Manager, you may need an alternative. Google latest Samsung drivers and try updating your drivers.

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

How do you get git to always pull from a specific branch?

There is also a way of configuring Git so, it always pulls and pushes the equivalent remote branch to the branch currently checked out to the working copy. It's called a tracking branch which git ready recommends setting by default.

For the next repository above the present working directory:

git config branch.autosetupmerge true

For all Git repositories, that are not configured otherwise:

git config --global branch.autosetupmerge true

Kind of magic, IMHO but this might help in cases where the specific branch is always the current branch.

When you have branch.autosetupmerge set to true and checkout a branch for the first time, Git will tell you about tracking the corresponding remote branch:

(master)$ git checkout gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'

Git will then push to that corresponding branch automatically:

(gh-pages)$ git push
Counting objects: 8, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 1003 bytes, done.
Total 6 (delta 2), reused 0 (delta 0)
To [email protected]:bigben87/webbit.git
   1bf578c..268fb60  gh-pages -> gh-pages

Check if a number is int or float

absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
  print 'Integer number'
else:
  print 'notInteger number'

Java: Replace all ' in a string with \'

Use replace()

 s = s.replace("'", "\\'"); 

output:

You\'ll be totally awesome, I\'m really terrible

Getting visitors country from their IP

As of 2019, MaxMind country DB can be used as follows:

<?php
require_once 'vendor/autoload.php';
use MaxMind\Db\Reader;
$databaseFile = 'GeoIP2-Country.mmdb';
$reader = new Reader($databaseFile);
$cc = $reader->get($_SERVER['REMOTE_ADDR'])['country']['iso_code'] # US/GB...
$reader->close();

Source: https://github.com/maxmind/MaxMind-DB-Reader-php

Zoom to fit all markers in Mapbox or Leaflet

Leaflet also has LatLngBounds that even has an extend function, just like google maps.

http://leafletjs.com/reference.html#latlngbounds

So you could simply use:

var latlngbounds = new L.latLngBounds();

The rest is exactly the same.

Parse strings to double with comma and point

You DO NOT NEED to replace the comma and dot..

I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.

Here I made a complete example to make the difference clear.

string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
    double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
    Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}

double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
    double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
    Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}

The results is the following: enter image description here

Play around with the culture and you will get the result you need.

Backbone.js fetch with parameters

Another example if you are using Titanium Alloy:

 collection.fetch({ 
     data: {
             where : JSON.stringify({
                page: 1
             })
           } 
      });

Python pip install module is not found. How to link python to pip location?

For the sake of anyone also using visual studio from a windows environment:

I realized that I could see my module installed when i ran pip install

py pip install [moduleName] 
py pip list

However debugging in visual studio was getting "module not found". Oddly, i was successfully running import [moduleName] when i ran the interpreter in powershell.

Reason:

visual studio was using the wrong interpreter at: C:\Users\[username]\AppData\Local\Programs\Python\Python37\

What I REALLY wanted was visual studio to use the virtualenv that i setup for my project. To do this, right click Python Environments in "solution explorer", select Add Virtual Environment..., and then select the folder where you created your virtual environment. enter image description here Then, under project settings, under the General tab, select your virtual environment in the dropdown.

enter image description here

Now visual studio should be using the same interpreter and everything should play nice!

usr/bin/ld: cannot find -l<nameOfTheLibrary>

To figure out what the linker is looking for, run it in verbose mode.

For example, I encountered this issue while trying to compile MySQL with ZLIB support. I was receiving an error like this during compilation:

/usr/bin/ld: cannot find -lzlib

I did some Googl'ing and kept coming across different issues of the same kind where people would say to make sure the .so file actually exists and if it doesn't, then create a symlink to the versioned file, for example, zlib.so.1.2.8. But, when I checked, zlib.so DID exist. So, I thought, surely that couldn't be the problem.

I came across another post on the Internets that suggested to run make with LD_DEBUG=all:

LD_DEBUG=all make

Although I got a TON of debugging output, it wasn't actually helpful. It added more confusion than anything else. So, I was about to give up.

Then, I had an epiphany. I thought to actually check the help text for the ld command:

ld --help

From that, I figured out how to run ld in verbose mode (imagine that):

ld -lzlib --verbose

This is the output I got:

==================================================
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a failed
attempt to open /usr/local/lib64/libzlib.so failed
attempt to open /usr/local/lib64/libzlib.a failed
attempt to open /lib64/libzlib.so failed
attempt to open /lib64/libzlib.a failed
attempt to open /usr/lib64/libzlib.so failed
attempt to open /usr/lib64/libzlib.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed
attempt to open /usr/local/lib/libzlib.so failed
attempt to open /usr/local/lib/libzlib.a failed
attempt to open /lib/libzlib.so failed
attempt to open /lib/libzlib.a failed
attempt to open /usr/lib/libzlib.so failed
attempt to open /usr/lib/libzlib.a failed
/usr/bin/ld.bfd.real: cannot find -lzlib

Ding, ding, ding...

So, to finally fix it so I could compile MySQL with my own version of ZLIB (rather than the bundled version):

sudo ln -s /usr/lib/libz.so.1.2.8 /usr/lib/libzlib.so

Voila!

How to access List elements

Recursive solution to print all items in a list:

def printItems(l):
   for i in l:
      if isinstance(i,list):
         printItems(i)
      else:
         print i


l = [['vegas','London'],['US','UK']]
printItems(l)

How to set selected item of Spinner by value, not by position?

you have to pass your custom adapter with position like REPEAT[position]. and it works properly.

Singleton: How should it be used

The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.

1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.

2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.

How does the "this" keyword work?

There is a lot of confusion regarding how "this" keyword is interpreted in JavaScript. Hopefully this article will lay all those to rest once and for all. And a lot more. Please read the entire article carefully. Be forewarned that this article is long.

Irrespective of the context in which it is used, "this" always references the "current object" in Javascript. However, what the "current object" is differs according to context. The context may be exactly 1 of the 6 following:

  1. Global (i.e. Outside all functions)
  2. Inside Direct "Non Bound Function" Call (i.e. a function that has not been bound by calling functionName.bind)
  3. Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply
  4. Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind)
  5. While Object Creation through "new"
  6. Inside Inline DOM event handler

The following describes each of this contexts one by one:

  1. Global Context (i.e. Outside all functions):

    Outside all functions (i.e. in global context) the "current object" (and hence the value of "this") is always the "window" object for browsers.

  2. Inside Direct "Non Bound Function" Call:

    Inside a Direct "Non Bound Function" Call, the object that invoked the function call becomes the "current object" (and hence the value of "this"). If a function is called without a explicit current object, the current object is either the "window" object (For Non Strict Mode) or undefined (For Strict Mode) . Any function (or variable) defined in Global Context automatically becomes a property of the "window" object.For e.g Suppose function is defined in Global Context as

    function UserDefinedFunction(){
        alert(this)
        }
    

    it becomes the property of the window object, as if you have defined it as

    window.UserDefinedFunction=function(){
      alert(this)
    }  
    

    In "Non Strict Mode", Calling/Invoking this function directly through "UserDefinedFunction()" will automatically call/invoke it as "window.UserDefinedFunction()" making "window" as the "current object" (and hence the value of "this") within "UserDefinedFunction".Invoking this function in "Non Strict Mode" will result in the following

    UserDefinedFunction() // displays [object Window]  as it automatically gets invoked as window.UserDefinedFunction()
    

    In "Strict Mode", Calling/Invoking the function directly through "UserDefinedFunction()" will "NOT" automatically call/invoke it as "window.UserDefinedFunction()".Hence the "current object" (and the value of "this") within "UserDefinedFunction" shall be undefined. Invoking this function in "Strict Mode" will result in the following

    UserDefinedFunction() // displays undefined
    

    However, invoking it explicitly using window object shall result in the following

    window.UserDefinedFunction() // "always displays [object Window]   irrespective of mode."
    

    Let us look at another example. Please look at the following code

     function UserDefinedFunction()
        {
            alert(this.a + ","  + this.b + ","  + this.c  + ","  + this.d)
        }
    
    var o1={
                a:1,
                b:2,
                f:UserDefinedFunction
          }
    var o2={
                c:3,
                d:4,
                f:UserDefinedFunction
           }
    
    o1.f() // Shall display 1,2,undefined,undefined
    o2.f() // Shall display undefined,undefined,3,4
    

    In the above example we see that when "UserDefinedFunction" was invoked through o1, "this" takes value of o1 and the value of its properties "a" and "b" get displayed. The value of "c" and "d" were shown as undefined as o1 does not define these properties

    Similarly when "UserDefinedFunction" was invoked through o2, "this" takes value of o2 and the value of its properties "c" and "d" get displayed.The value of "a" and "b" were shown as undefined as o2 does not define these properties.

  3. Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply:

    When a "Non Bound Function" is called through functionName.call or functionName.apply, the "current object" (and hence the value of "this") is set to the value of "this" parameter (first parameter) passed to call/apply. The following code demonstrates the same.

    function UserDefinedFunction()
    {
        alert(this.a + ","  + this.b + ","  + this.c  + ","  + this.d)
    }
    var o1={
                a:1,
                b:2,
                f:UserDefinedFunction
           }
    var o2={
                c:3,
                d:4,
                f:UserDefinedFunction
           }
    
    UserDefinedFunction.call(o1) // Shall display 1,2,undefined,undefined
    UserDefinedFunction.apply(o1) // Shall display 1,2,undefined,undefined
    
    UserDefinedFunction.call(o2) // Shall display undefined,undefined,3,4
    UserDefinedFunction.apply(o2) // Shall display undefined,undefined,3,4
    
    o1.f.call(o2) // Shall display undefined,undefined,3,4
    o1.f.apply(o2) // Shall display undefined,undefined,3,4
    
    o2.f.call(o1) // Shall display 1,2,undefined,undefined
    o2.f.apply(o1) // Shall display 1,2,undefined,undefined
    

    The above code clearly shows that the "this" value for any "NON Bound Function" can be altered through call/apply. Also,if the "this" parameter is not explicitly passed to call/apply, "current object" (and hence the value of "this") is set to "window" in Non strict mode and "undefined" in strict mode.

  4. Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind):

    A bound function is a function whose "this" value has been fixed. The following code demonstrated how "this" works in case of bound function

    function UserDefinedFunction()
    {
        alert(this.a + ","  + this.b + ","  + this.c  + ","  + this.d)
    }
    var o1={
              a:1,
              b:2,
              f:UserDefinedFunction,
              bf:null
           }
    var o2={
               c:3,
               d:4,
               f:UserDefinedFunction,
               bf:null
            }
    
    var bound1=UserDefinedFunction.bind(o1); // permanantly fixes "this" value of function "bound1" to Object o1
    bound1() // Shall display 1,2,undefined,undefined
    
    var bound2=UserDefinedFunction.bind(o2); // permanantly fixes "this" value of function "bound2" to Object o2
    bound2() // Shall display undefined,undefined,3,4
    
    var bound3=o1.f.bind(o2); // permanantly fixes "this" value of function "bound3" to Object o2
    bound3() // Shall display undefined,undefined,3,4
    
    var bound4=o2.f.bind(o1); // permanantly fixes "this" value of function "bound4" to Object o1
    bound4() // Shall display 1,2,undefined,undefined
    
    o1.bf=UserDefinedFunction.bind(o2) // permanantly fixes "this" value of function "o1.bf" to Object o2
    o1.bf() // Shall display undefined,undefined,3,4
    
    o2.bf=UserDefinedFunction.bind(o1) // permanantly fixes "this" value of function "o2.bf" to Object o1
    o2.bf() // Shall display 1,2,undefined,undefined
    
    bound1.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
    
    bound1.apply(o2) // Shall still display 1,2,undefined,undefined. "apply" cannot alter the value of "this" for bound function
    
    o2.bf.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
    o2.bf.apply(o2) // Shall still display 1,2,undefined,undefined."apply" cannot alter the value of "this" for bound function
    

    As given in the code above, "this" value for any "Bound Function" CANNOT be altered through call/apply. Also, if the "this" parameter is not explicitly passed to bind, "current object" (and hence the value of "this" ) is set to "window" in Non strict mode and "undefined" in strict mode. One more thing. Binding an already bound function does not change the value of "this". It remains set as the value set by first bind function.

  5. While Object Creation through "new":

    Inside a constructor function, the "current object" (and hence the value of "this") references the object that is currently being created through "new" irrespective of the bind status of the function. However if the constructor is a bound function it shall get called with predefined set of arguments as set for the bound function.

  6. Inside Inline DOM event handler:

    Please look at the following HTML Snippet

    <button onclick='this.style.color=white'>Hello World</button>
    <div style='width:100px;height:100px;' onclick='OnDivClick(event,this)'>Hello World</div>
    

    The "this" in above examples refer to "button" element and the "div" element respectively.

    In the first example, the font color of the button shall be set to white when it is clicked.

    In the second example when the "div" element is clicked it shall call the OnDivClick function with its second parameter referencing the clicked div element. However the value of "this" within OnDivClick SHALL NOT reference the clicked div element. It shall be set as the "window object" or "undefined" in Non strict and Strict Modes respectively (if OnDivClick is an unbound function) or set to a predefined Bound value (if OnDivClick is a bound function)

The following summarizes the entire article

  1. In Global Context "this" always refers to the "window" object

  2. Whenever a function is invoked, it is invoked in context of an object ("current object"). If the current object is not explicitly provided, the current object is the "window object" in NON Strict Mode and "undefined" in Strict Mode by default.

  3. The value of "this" within a Non Bound function is the reference to object in context of which the function is invoked ("current object")

  4. The value of "this" within a Non Bound function can be overriden by call and apply methods of the function.

  5. The value of "this" is fixed for a Bound function and cannot be overriden by call and apply methods of the function.

  6. Binding and already bound function does not change the value of "this". It remains set as the value set by first bind function.

  7. The value of "this" within a constructor is the object that is being created and initialized

  8. The value of "this" within an inline DOM event handler is reference to the element for which the event handler is given.

How to rename a component in Angular CLI?

I personally have not found any command for the same. Just make a new component (renamed name) and copy paste the previous component's html, css, and ts. In ts obviously the class name would be replaced. Its the safest method but does take a little time.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

It's helped me, I uninstalled EF, restarted VS and I added 'using':

using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

How to use session in JSP pages to get information?

JSP implicit objects likes session, request etc. are not available inside JSP declaration <%! %> tags.

You could use it directly in your expression as

<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>

On other note, using scriptlets in JSP has been long deprecated. Use of EL (expression language) and JSTL tags is highly recommended. For example, here you could use EL as

<td>Username: </td>
<td><input type="text" value="${username}" /></td>

The best part is that scope resolution is done automatically. So, here username could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as

<td><input type="text" value="${requestScope.username}" /></td> or,
<td><input type="text" value="${sessionScope.username}" /></td> or,
<td><input type="text" value="${applicationScope.username}" /></td>

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

JUnit tests pass in Eclipse but fail in Maven Surefire

This doesn't exactly apply to your situation, but I had the same thing -- tests that would pass in Eclipse failed when the test goal from Maven was run.

It turned out to be a test earlier in my suite, in a different package. This took me a week to solve!

An earlier test was testing some Logback classes, and created a Logback context from a config file.

The later test was testing a subclass of Spring's SimpleRestTemplate, and somehow, the earlier Logback context was held, with DEBUG on. This caused extra calls to be made in RestTemplate to log HttpStatus, etc.

It's another thing to check if one ever gets into this situation. I fixed my problem by injecting some Mocks into my Logback test class, so that no real Logback contexts were created.

How do I commit only some files?

This is a simple approach if you don't have much code changes:

1. git stash
2. git stash apply
3. remove the files/code you don't want to commit
4. commit the remaining files/code you do want

Then if you want the code you removed (bits you didn't commit) in a separate commit or another branch, then while still on this branch do:

5. git stash apply
6. git stash

With step 5 as you already applied the stash and committed the code you did want in step 4, the diff and untracked in the newly applied stash is just the code you removed in step 3 before you committed in step 4.

As such step 6 is a stash of the code you didn't [want to] commit, as you probably don't really want to lose those changes right? So the new stash from step 6 can now be committed to this or any other branch by doing git stash apply on the correct branch and committing.

Obviously this presumes you do the steps in one flow, if you stash at any other point in these steps you'll need to note the stash ref for each step above (rather than just basic stash and apply the most recent stash).

data.table vs dplyr: can one do something well the other can't or does poorly?

In direct response to the Question Title...

dplyr definitely does things that data.table can not.

Your point #3

dplyr abstracts (or will) potential DB interactions

is a direct answer to your own question but isn't elevated to a high enough level. dplyr is truly an extendable front-end to multiple data storage mechanisms where as data.table is an extension to a single one.

Look at dplyr as a back-end agnostic interface, with all of the targets using the same grammer, where you can extend the targets and handlers at will. data.table is, from the dplyr perspective, one of those targets.

You will never (I hope) see a day that data.table attempts to translate your queries to create SQL statements that operate with on-disk or networked data stores.

dplyr can possibly do things data.table will not or might not do as well.

Based on the design of working in-memory, data.table could have a much more difficult time extending itself into parallel processing of queries than dplyr.


In response to the in-body questions...

Usage

Are there analytical tasks that are a lot easier to code with one or the other package for people familiar with the packages (i.e. some combination of keystrokes required vs. required level of esotericism, where less of each is a good thing).

This may seem like a punt but the real answer is no. People familiar with tools seem to use the either the one most familiar to them or the one that is actually the right one for the job at hand. With that being said, sometimes you want to present a particular readability, sometimes a level of performance, and when you have need for a high enough level of both you may just need another tool to go along with what you already have to make clearer abstractions.

Performance

Are there analytical tasks that are performed substantially (i.e. more than 2x) more efficiently in one package vs. another.

Again, no. data.table excels at being efficient in everything it does where dplyr gets the burden of being limited in some respects to the underlying data store and registered handlers.

This means when you run into a performance issue with data.table you can be pretty sure it is in your query function and if it is actually a bottleneck with data.table then you've won yourself the joy of filing a report. This is also true when dplyr is using data.table as the back-end; you may see some overhead from dplyr but odds are it is your query.

When dplyr has performance issues with back-ends you can get around them by registering a function for hybrid evaluation or (in the case of databases) manipulating the generated query prior to execution.

Also see the accepted answer to when is plyr better than data.table?

How do emulators work and how are they written?

Emulation is a multi-faceted area. Here are the basic ideas and functional components. I'm going to break it into pieces and then fill in the details via edits. Many of the things I'm going to describe will require knowledge of the inner workings of processors -- assembly knowledge is necessary. If I'm a bit too vague on certain things, please ask questions so I can continue to improve this answer.

Basic idea:

Emulation works by handling the behavior of the processor and the individual components. You build each individual piece of the system and then connect the pieces much like wires do in hardware.

Processor emulation:

There are three ways of handling processor emulation:

  • Interpretation
  • Dynamic recompilation
  • Static recompilation

With all of these paths, you have the same overall goal: execute a piece of code to modify processor state and interact with 'hardware'. Processor state is a conglomeration of the processor registers, interrupt handlers, etc for a given processor target. For the 6502, you'd have a number of 8-bit integers representing registers: A, X, Y, P, and S; you'd also have a 16-bit PC register.

With interpretation, you start at the IP (instruction pointer -- also called PC, program counter) and read the instruction from memory. Your code parses this instruction and uses this information to alter processor state as specified by your processor. The core problem with interpretation is that it's very slow; each time you handle a given instruction, you have to decode it and perform the requisite operation.

With dynamic recompilation, you iterate over the code much like interpretation, but instead of just executing opcodes, you build up a list of operations. Once you reach a branch instruction, you compile this list of operations to machine code for your host platform, then you cache this compiled code and execute it. Then when you hit a given instruction group again, you only have to execute the code from the cache. (BTW, most people don't actually make a list of instructions but compile them to machine code on the fly -- this makes it more difficult to optimize, but that's out of the scope of this answer, unless enough people are interested)

With static recompilation, you do the same as in dynamic recompilation, but you follow branches. You end up building a chunk of code that represents all of the code in the program, which can then be executed with no further interference. This would be a great mechanism if it weren't for the following problems:

  • Code that isn't in the program to begin with (e.g. compressed, encrypted, generated/modified at runtime, etc) won't be recompiled, so it won't run
  • It's been proven that finding all the code in a given binary is equivalent to the Halting problem

These combine to make static recompilation completely infeasible in 99% of cases. For more information, Michael Steil has done some great research into static recompilation -- the best I've seen.

The other side to processor emulation is the way in which you interact with hardware. This really has two sides:

  • Processor timing
  • Interrupt handling

Processor timing:

Certain platforms -- especially older consoles like the NES, SNES, etc -- require your emulator to have strict timing to be completely compatible. With the NES, you have the PPU (pixel processing unit) which requires that the CPU put pixels into its memory at precise moments. If you use interpretation, you can easily count cycles and emulate proper timing; with dynamic/static recompilation, things are a /lot/ more complex.

Interrupt handling:

Interrupts are the primary mechanism that the CPU communicates with hardware. Generally, your hardware components will tell the CPU what interrupts it cares about. This is pretty straightforward -- when your code throws a given interrupt, you look at the interrupt handler table and call the proper callback.

Hardware emulation:

There are two sides to emulating a given hardware device:

  • Emulating the functionality of the device
  • Emulating the actual device interfaces

Take the case of a hard-drive. The functionality is emulated by creating the backing storage, read/write/format routines, etc. This part is generally very straightforward.

The actual interface of the device is a bit more complex. This is generally some combination of memory mapped registers (e.g. parts of memory that the device watches for changes to do signaling) and interrupts. For a hard-drive, you may have a memory mapped area where you place read commands, writes, etc, then read this data back.

I'd go into more detail, but there are a million ways you can go with it. If you have any specific questions here, feel free to ask and I'll add the info.

Resources:

I think I've given a pretty good intro here, but there are a ton of additional areas. I'm more than happy to help with any questions; I've been very vague in most of this simply due to the immense complexity.

Obligatory Wikipedia links:

General emulation resources:

  • Zophar -- This is where I got my start with emulation, first downloading emulators and eventually plundering their immense archives of documentation. This is the absolute best resource you can possibly have.
  • NGEmu -- Not many direct resources, but their forums are unbeatable.
  • RomHacking.net -- The documents section contains resources regarding machine architecture for popular consoles

Emulator projects to reference:

  • IronBabel -- This is an emulation platform for .NET, written in Nemerle and recompiles code to C# on the fly. Disclaimer: This is my project, so pardon the shameless plug.
  • BSnes -- An awesome SNES emulator with the goal of cycle-perfect accuracy.
  • MAME -- The arcade emulator. Great reference.
  • 6502asm.com -- This is a JavaScript 6502 emulator with a cool little forum.
  • dynarec'd 6502asm -- This is a little hack I did over a day or two. I took the existing emulator from 6502asm.com and changed it to dynamically recompile the code to JavaScript for massive speed increases.

Processor recompilation references:

  • The research into static recompilation done by Michael Steil (referenced above) culminated in this paper and you can find source and such here.

Addendum:

It's been well over a year since this answer was submitted and with all the attention it's been getting, I figured it's time to update some things.

Perhaps the most exciting thing in emulation right now is libcpu, started by the aforementioned Michael Steil. It's a library intended to support a large number of CPU cores, which use LLVM for recompilation (static and dynamic!). It's got huge potential, and I think it'll do great things for emulation.

emu-docs has also been brought to my attention, which houses a great repository of system documentation, which is very useful for emulation purposes. I haven't spent much time there, but it looks like they have a lot of great resources.

I'm glad this post has been helpful, and I'm hoping I can get off my arse and finish up my book on the subject by the end of the year/early next year.

Why should Java 8's Optional not be used in arguments

Accepting Optional as parameters causes unnecessary wrapping at caller level.

For example in the case of:

public int calculateSomething(Optional<String> p1, Optional<BigDecimal> p2 {}

Suppose you have two not-null strings (ie. returned from some other method):

String p1 = "p1"; 
String p2 = "p2";

You're forced to wrap them in Optional even if you know they are not Empty.

This get even worse when you have to compose with other "mappable" structures, ie. Eithers:

Either<Error, String> value = compute().right().map((s) -> calculateSomething(
< here you have to wrap the parameter in a Optional even if you know it's a 
  string >));

ref:

methods shouldn't expect Option as parameters, this is almost always a code smell that indicated a leakage of control flow from the caller to the callee, it should be responsibility of the caller to check the content of an Option

ref. https://github.com/teamdigitale/digital-citizenship-functions/pull/148#discussion_r170862749

How to change font-color for disabled input?

The following gets you pretty close in IE8 and works in other browsers too.

In your html:

<input type="text" 
       readonly="readonly"    <!-- disallow editting -->
       onfocus="this.blur();" <!-- prevent focus -->
       tabindex="-1"          <!-- disallow tabbing -->
       class="disabledInput"  <!-- change the color with CSS -->
       />

In your CSS:

.disabledInput {
    color: black;
}

In IE8, there is a slight amount of border color change on hover. Some CSS for input.disabledInput:hover could probably take care of this.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

For those, who wonder how it goes in VS.

MSVC 2015 Update 1, cl.exe version 19.00.24215.1:

#include <iostream>

template<typename X, typename Y>
struct A
{
  template<typename Z>
  static void f()
  {
    std::cout << "from A::f():" << std::endl
      << __FUNCTION__ << std::endl
      << __func__ << std::endl
      << __FUNCSIG__ << std::endl;
  }
};

void main()
{
  std::cout << "from main():" << std::endl
    << __FUNCTION__ << std::endl
    << __func__ << std::endl
    << __FUNCSIG__ << std::endl << std::endl;

  A<int, float>::f<bool>();
}

output:

from main():
main
main
int __cdecl main(void)

from A::f():
A<int,float>::f
f
void __cdecl A<int,float>::f<bool>(void)

Using of __PRETTY_FUNCTION__ triggers undeclared identifier error, as expected.

Android studio Gradle build speed up

After change this settings my compile time 10 mins reduced to 10 secs.

Step 1:

Settings(ctrl+Alt+S) ->

Build,Execution,Deployment ->

Compiler ->

type "--offline" in command-line Options box.

Step 2:

check the “Compile independent modules in parallel” checkbox.

& click Apply -> OK

enter image description here

Step 3: In your gradle.properties file -> Add following lines

org.gradle.jvmargs=-Xmx2048M -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.daemon=true

Update:

If you are using Android studio 2.0 or above try the Instant Run

Settings ? Build, Execution, Deployment ? Instant Run ? Enable Instant Run.

More info about Instant Run - https://developer.android.com/studio/run/index.html#instant-run

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

remove objects from array by object property

If you just want to remove it from the existing array and not create a new one, try:

var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

What causes java.lang.IncompatibleClassChangeError?

All of the above - for whatever reason I was doing some big refactor and starting to get this. I renamed the package my interface was in and that cleared it. Hope that helps.

Using setattr() in python

Setattr: We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrive these values

For example

Employee = type("Employee", (object,), dict())

employee = Employee()

# Set salary to 1000
setattr(employee,"salary", 1000 )

# Get the Salary
value = getattr(employee, "salary")

print(value)

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How to read GET data from a URL using JavaScript?

You can easily do this

const shopId =  new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);

pandas unique values multiple columns

Non-pandas solution: using set().

import pandas as pd
import numpy as np

df = pd.DataFrame({'Col1' : ['Bob', 'Joe', 'Bill', 'Mary', 'Joe'],
              'Col2' : ['Joe', 'Steve', 'Bob', 'Bob', 'Steve'],
               'Col3' : np.random.random(5)})

print df

print set(df.Col1.append(df.Col2).values)

Output:

   Col1   Col2      Col3
0   Bob    Joe  0.201079
1   Joe  Steve  0.703279
2  Bill    Bob  0.722724
3  Mary    Bob  0.093912
4   Joe  Steve  0.766027
set(['Steve', 'Bob', 'Bill', 'Joe', 'Mary'])

How to set top-left alignment for UILabel for iOS application?

Swift 2.0: : Using UILabel Extension

Make constant enum values in a empty Swift file.

//  AppRef.swift

import UIKit
import Foundation

enum UILabelTextPositions : String {

 case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
 case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
 case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"

}

Using UILabel Extension:

Make a empty Swift class and name it. Add the following.

//  AppExtensions.swift

import Foundation
import UIKit

    extension UILabel{ 
     func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
     {
      let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)

      switch positionIdentifier
      {
      case "VerticalAlignmentTop":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
       break;

      case "VerticalAlignmentMiddle":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
        rect.size.width, rect.size.height);
       break;

      case "VerticalAlignmentBottom":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
       break;

      default:
       sampleLabel!.frame = bounds;
       break;
      }
      return sampleLabel!

     }
    }

Usage :

myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

My advice is to not (try to) implement __iob_func.

While fixing these errors:

libpngd.v110.lib(pngrutil.obj) : error LNK2001: unresolved external symbol ___iob_func curllib.v110.lib(mprintf.obj) : error LNK2001: unresolved external symbol ___iob_func

I tried the other answers' solutions, but in the end, returning a FILE* C-array doesn't match up with an array of Windows' internal IOB structs. @Volker is right that it'll never work for more than one of stdin, stdout or stderr.

If a library actually USES one of those streams, it will crash. As long as your program doesn't cause the lib to use them, you'll never know. For example, png_default_error writes to stderr when the CRC doesn't match in the PNG's metadata. (Normally not a crash-worthy issue)

Conclusion: It's not possible to mix VS2012 (Platform Toolset v110/v110_xp) and VS2015+ libraries, if they use stdin, stdout and/or stderr.

Solution: Recompile your libraries that have __iob_func unresolved symbols with your current version of VS and a matching Platform Toolset.

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Up to Android 7.1 (SDK 25)

Until Android 7.1 you will get it with:

Build.SERIAL

From Android 8 (SDK 26)

On Android 8 (SDK 26) and above, this field will return UNKNOWN and must be accessed with:

Build.getSerial()

which requires the dangerous permission android.permission.READ_PHONE_STATE.

From Android Q (SDK 29)

Since Android Q using Build.getSerial() gets a bit more complicated by requiring:

android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE (which can only be acquired by system apps), or for the calling package to be the device or profile owner and have the READ_PHONE_STATE permission. This means most apps won't be able to uses this feature. See the Android Q announcement from Google.

See Android SDK reference


Best Practice for Unique Device Identifier

If you just require a unique identifier, it's best to avoid using hardware identifiers as Google continuously tries to make it harder to access them for privacy reasons. You could just generate a UUID.randomUUID().toString(); and save it the first time it needs to be accessed in e.g. shared preferences. Alternatively you could use ANDROID_ID which is a 8 byte long hex string unique to the device, user and (only Android 8+) app installation. For more info on that topic, see Best practices for unique identifiers.

Is there any WinSCP equivalent for linux?

Xfce/Thunar solution is basically the same as Gnome/Nautilus:

Simply type sftp://yourhost/ to address line in Thunar (You can get there by Ctrl + L)

(The authorization is identical to ssh/scp, i.e. with proper use of ~/.ssh/config, keys and ssh-agent, you can achieve decent ease and security: server alias + no passwords asked.)

SQL Server - boolean literal?

According to Microsoft: syntax for searching is

[ WHERE <search_condition> ]*

And search condition is:

<search_condition> ::= 
    { [ NOT ] <predicate> | ( <search_condition> ) } 
    [ { AND | OR } [ NOT ] { <predicate> | ( <search_condition> ) } ] 
[ ,...n ] 

And predicate is:

<predicate> ::= 
    { expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } expression 

As you can see, you always have to write two expressions to compare. Here search condition is boolean expression like 1=1, a!=b

Do not confuse search expressions with boolean constants like 'True' or 'False'. You can assign boolean constants to BIT variables

DECLARE @B BIT
SET @B='True'

but in TSQL you can not use boolean constants instead of boolean expressions like this:

SELECT * FROM Somewhere WHERE 'True'

It will not work.

But you can use boolean constants to build two-sided search expression like this:

SEARCH * FROM Somewhere WHERE 'True'='True' 

Read file content from S3 bucket with boto3

You might also consider the smart_open module, which supports iterators:

from smart_open import smart_open

# stream lines from an S3 object
for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
    print(line.decode('utf8'))

and context managers:

with smart_open('s3://mybucket/mykey.txt', 'rb') as s3_source:
    for line in s3_source:
         print(line.decode('utf8'))

    s3_source.seek(0)  # seek to the beginning
    b1000 = s3_source.read(1000)  # read 1000 bytes

Find smart_open at https://pypi.org/project/smart_open/

enable or disable checkbox in html

<input type="checkbox" value="" ng-model="t.IsPullPoint" onclick="return false;" onkeydown="return false;"><span class="cr"></span></label>

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);

Plain Old CLR Object vs Data Transfer Object

POCO is simply an object that does not take a dependency on an external framework. It is PLAIN.

Whether a POCO has behaviour or not it's immaterial.

A DTO may be POCO as may a domain object (which would typically be rich in behaviour).

Typically DTOs are more likely to take dependencies on external frameworks (eg. attributes) for serialisation purposes as typically they exit at the boundary of a system.

In typical Onion style architectures (often used within a broadly DDD approach) the domain layer is placed at the centre and so its objects should not, at this point, have dependencies outside of that layer.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Sounds like you want a simple imagemap, I'd recommend to not make it more complex than it needs to be. Here's an article on how to improve imagemaps with svg. It's very easy to do clickable regions in svg itself, just add some <a> elements around the shapes you want to have clickable.

A couple of options if you need something more advanced:

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

How to turn NaN from parseInt into 0 for an empty string?

I had a similar problem (firefox v34) with simple strings like:

var myInt = parseInt("b4");

So I came up with a quick hack of:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

And then got all stupid complicated to deal with floats + ints for non-simple stuff:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

It will return 0 for things like:

var intVal = slowParseNumber("b"); // yeilds 0

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

I had the same sort of need and found this to work well for me (postgres 8.4):

CAST((COALESCE(myfield,'0')) AS INTEGER)

Some test cases to demonstrate:

db=> select CAST((COALESCE(NULL,'0')) AS INTEGER);
 int4
------
    0
(1 row)

db=> select CAST((COALESCE('','0')) AS INTEGER);
 int4
------
    0
(1 row)

db=> select CAST((COALESCE('4','0')) AS INTEGER);
 int4
------
    4
(1 row)

db=> select CAST((COALESCE('bad','0')) AS INTEGER);
ERROR:  invalid input syntax for integer: "bad"

If you need to handle the possibility of the field having non-numeric text (such as "100bad") you can use regexp_replace to strip non-numeric characters before the cast.

CAST(REGEXP_REPLACE(COALESCE(myfield,'0'), '[^0-9]+', '', 'g') AS INTEGER)

Then text/varchar values like "b3ad5" will also give numbers

db=> select CAST(REGEXP_REPLACE(COALESCE('b3ad5','0'), '[^0-9]+', '', 'g') AS INTEGER);
 regexp_replace
----------------
             35
(1 row)

To address Chris Cogdon's concern with the solution not giving 0 for all cases, including a case such as "bad" (no digit characters at all), I made this adjusted statement:

CAST((COALESCE(NULLIF(REGEXP_REPLACE(myfield, '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);

It works similar to the simpler solutions, except will give 0 when the value to convert is non-digit characters only, such as "bad":

db=> select CAST((COALESCE(NULLIF(REGEXP_REPLACE('no longer bad!', '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
     coalesce
----------
        0
(1 row)

Creating and Update Laravel Eloquent

$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));

Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.

How to convert a 3D point into 2D perspective projection?

To obtain the perspective-corrected co-ordinates, just divide by the z co-ordinate:

xc = x / z
yc = y / z

The above works assuming that the camera is at (0, 0, 0) and you are projecting onto the plane at z = 1 -- you need to translate the co-ords relative to the camera otherwise.

There are some complications for curves, insofar as projecting the points of a 3D Bezier curve will not in general give you the same points as drawing a 2D Bezier curve through the projected points.

Focus Next Element In Tab Index

A word of advice: Don’t try to control where the focus lands during a tab event. Instead try to control which element are and aren’t tabbable by setting the tabIndex of the elements you don’t want to receive focus to -1. E.g.

// `tabContainer` is a container where we want only
// element at a time to be tabbable, e.g. a radio menu.

tabContainer.addEventListener("focusin", () => {
  const desired = findDesiredFocusElement();

  if (!desired) {
    // Just leave the focus be. We have no preference
    // at the moment.
    return;
  }

  // Move the focus to the correct element.
  desired.focus();

  // Remove all undesired elements from the tab order.
  for (const undesired of findUndesiredFocusElements()) {
    // Make it untabbable.
    undesired.tabIndex = -1;
  }
});

tabContainer.addEventListener("focusout", (event) => {
  for (const element of findRelevantFocusElements()) {
    // Give each element back their focus capability.
    element.tabIndex = 0;
  }
});

Note: This might not be what is best in your situation, e.g. in your case it might be better to control the tab index in some change events or not to reset the tabIndex state on focusout etc.

More info here.

Extract values in Pandas value_counts()

#!/usr/bin/env python

import pandas as pd

# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
                   (2, 'France'),
                   (3, 'Indonesia'),
                   (4, 'France'),
                   (5, 'France'),
                   (6, 'Germany'),
                   (7, 'UK'),
                   ],
                  columns=['groupid', 'country'],
                  index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()

Now, print(df['country'].value_counts()) gives:

France       3
Germany      2
UK           1
Indonesia    1

and print(values) gives:

['France', 'Germany', 'UK', 'Indonesia']

and print(counts) gives:

[3, 2, 1, 1]

File count from a folder

Reading PDF files from a directory:

var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf");
if (list.Length > 0)
{

}

Best approach to remove time part of datetime in SQL Server

If possible, for special things like this, I like to use CLR functions.

In this case:

[Microsoft.SqlServer.Server.SqlFunction]
    public static SqlDateTime DateOnly(SqlDateTime input)
    {
        if (!input.IsNull)
        {
            SqlDateTime dt = new SqlDateTime(input.Value.Year, input.Value.Month, input.Value.Day, 0, 0, 0);

            return dt;
        }
        else
            return SqlDateTime.Null;
    }

Launching a website via windows commandline

Working from VaLo's answer:

cd %directory to browser%
%browser's name to main executable (firefox, chrome, opera, etc.)% https://www.google.com

start https://www.google.com doesn't seem to work (at least in my environment)

Permutations in JavaScript?

I have improved SiGanteng's answer.

Now it is possible to call permute more than once, because permArr and usedChars are cleared each time.

function permute(input) {
    var permArr = [],
        usedChars = [];
    return (function main() {
        for (var i = 0; i < input.length; i++) {
            var ch = input.splice(i, 1)[0];
            usedChars.push(ch);
            if (input.length == 0) {
                permArr.push(usedChars.slice());
            }
            main();
            input.splice(i, 0, ch);
            usedChars.pop();
        }
        return permArr;
    })();
}

_x000D_
_x000D_
function permute(input) {_x000D_
  var permArr = [],_x000D_
      usedChars = [];_x000D_
  return (function main() {_x000D_
    for (var i = 0; i < input.length; i++) {_x000D_
      var ch = input.splice(i, 1)[0];_x000D_
      usedChars.push(ch);_x000D_
      if (input.length == 0) {_x000D_
        permArr.push(usedChars.slice());_x000D_
      }_x000D_
      main();_x000D_
      input.splice(i, 0, ch);_x000D_
      usedChars.pop();_x000D_
    }_x000D_
    return permArr;_x000D_
  })();_x000D_
}_x000D_
document.write(JSON.stringify(permute([5, 3, 7, 1])));
_x000D_
_x000D_
_x000D_

how to use "AND", "OR" for RewriteCond on Apache?

This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.

In the top section you'll quickly spot the defines used to name these flags:

#define CONDFLAG_NONE               1<<0
#define CONDFLAG_NOCASE             1<<1
#define CONDFLAG_NOTMATCH           1<<2
#define CONDFLAG_ORNEXT             1<<3
#define CONDFLAG_NOVARY             1<<4

and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:

else if (   strcasecmp(key, "ornext") == 0
         || strcasecmp(key, "OR") == 0    ) {
    cfg->flags |= CONDFLAG_ORNEXT;
}

The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):

# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
    rewritecond_entry *c = &conds[i];

    # execute the current Condition, see if it matches
    rc = apply_rewrite_cond(c, ctx);

    # does this Condition have an 'OR' flag?
    if (c->flags & CONDFLAG_ORNEXT) {
        if (!rc) {
            /* One condition is false, but another can be still true. */
            continue;
        }
        else {
            /* skip the rest of the chained OR conditions */
            while (   i < rewriteconds->nelts
                   && c->flags & CONDFLAG_ORNEXT) {
                c = &conds[++i];
            }
        }
    }
    else if (!rc) {
        return 0;
    }
}

You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) ). If you would, for example, have these Conditions:

RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D

it would be interpreted as if ( (A OR B OR C) and D ).

JavaScript code to stop form submission

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

Excel - Combine multiple columns into one column

Function Concat(myRange As Range, Optional myDelimiter As String) As String 
  Dim r As Range 
  Application.Volatile 
  For Each r In myRange 
    If Len(r.Text) Then 
      Concat = Concat & IIf(Concat <> "", myDelimiter, "") & r.Text 
    End If 
  Next 
End Function

What is a regex to match ONLY an empty string?

As explained in http://www.regular-expressions.info/anchors.html under the section "Strings Ending with a Line Break", \Z will generally match before the end of the last newline in strings that end in a newline. If you want to only match the end of the string, you need to use \z. The exception to this rule is Python.

In other words, to exclusively match an empty string, you need to use /\A\z/.

Using mysql concat() in WHERE clause?

Note that the search query is now case sensitive.

When using

SELECT * FROM table WHERE `first_name` LIKE '%$search_term%'

It will match both "Larry" and "larry". With this concat_ws, it will suddenly become case sensitive!

This can be fixed by using the following query:

SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', `first_name`, `last_name`) LIKE UPPER('%$search_term%')

Edit: Note that this only works on non-binary elements. See also mynameispaulie's answer.

What is the difference between buffer and cache memory in Linux?

"Buffers" represent how much portion of RAM is dedicated to cache disk blocks. "Cached" is similar like "Buffers", only this time it caches pages from file reading.

quote from:

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Custom fonts and XML layouts (Android)

If you only have one typeface you would like to add, and want less code to write, you can create a dedicated TextView for your specific font. See code below.

package com.yourpackage;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class FontTextView extends TextView {
    public static Typeface FONT_NAME;


    public FontTextView(Context context) {
        super(context);
        if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
        this.setTypeface(FONT_NAME);
    }
    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
        this.setTypeface(FONT_NAME);
    }
    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if(FONT_NAME == null) FONT_NAME = Typeface.createFromAsset(context.getAssets(), "fonts/FontName.otf");
        this.setTypeface(FONT_NAME);
    }
}

In main.xml, you can now add your textView like this:

<com.yourpackage.FontTextView
    android:id="@+id/tvTimer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

Use formula in custom calculated field in Pivot Table

Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.

Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.

For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0) So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.

Thanks again!! :)

How do I select an element with its name attribute in jQuery?

jQuery("[name='test']") 

Although you should avoid it and if possible select by ID (e.g. #myId) as this has better performance because it invokes the native getElementById.

Converting string to double in C#

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely , and .).

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

html5 - canvas element - Multiple layers

Related to this:

If you have something on your canvas and you want to draw something at the back of it - you can do it by changing the context.globalCompositeOperation setting to 'destination-over' - and then return it to 'source-over' when you're done.

_x000D_
_x000D_
   var context = document.getElementById('cvs').getContext('2d');_x000D_
_x000D_
    // Draw a red square_x000D_
    context.fillStyle = 'red';_x000D_
    context.fillRect(50,50,100,100);_x000D_
_x000D_
_x000D_
_x000D_
    // Change the globalCompositeOperation to destination-over so that anything_x000D_
    // that is drawn on to the canvas from this point on is drawn at the back_x000D_
    // of what's already on the canvas_x000D_
    context.globalCompositeOperation = 'destination-over';_x000D_
_x000D_
_x000D_
_x000D_
    // Draw a big yellow rectangle_x000D_
    context.fillStyle = 'yellow';_x000D_
    context.fillRect(0,0,600,250);_x000D_
_x000D_
_x000D_
    // Now return the globalCompositeOperation to source-over and draw a_x000D_
    // blue rectangle_x000D_
    context.globalCompositeOperation = 'source-over';_x000D_
_x000D_
    // Draw a blue rectangle_x000D_
    context.fillStyle = 'blue';_x000D_
    context.fillRect(75,75,100,100);
_x000D_
<canvas id="cvs" />
_x000D_
_x000D_
_x000D_

updating Google play services in Emulator

You need install Google play image, Android SDK -> SDK platforms --> check show Package details --> install Google play. enter image description here

Excel: replace part of cell's string value

You have a character = STQ8QGpaM4CU6149665!7084880820, and you have a another column = 7084880820.

If you want to get only this in excel using the formula: STQ8QGpaM4CU6149665!, use this:

=REPLACE(H11,SEARCH(J11,H11),LEN(J11),"")

H11 is an old character and for starting number use search option then for no of character needs to replace use len option then replace to new character. I am replacing this to blank.

What is the optimal algorithm for the game 2048?

I copy here the content of a post on my blog


The solution I propose is very simple and easy to implement. Although, it has reached the score of 131040. Several benchmarks of the algorithm performances are presented.

Score

Algorithm

Heuristic scoring algorithm

The assumption on which my algorithm is based is rather simple: if you want to achieve higher score, the board must be kept as tidy as possible. In particular, the optimal setup is given by a linear and monotonic decreasing order of the tile values. This intuition will give you also the upper bound for a tile value: s where n is the number of tile on the board.

(There's a possibility to reach the 131072 tile if the 4-tile is randomly generated instead of the 2-tile when needed)

Two possible ways of organizing the board are shown in the following images:

enter image description here

To enforce the ordination of the tiles in a monotonic decreasing order, the score si computed as the sum of the linearized values on the board multiplied by the values of a geometric sequence with common ratio r<1 .

s

s

Several linear path could be evaluated at once, the final score will be the maximum score of any path.

Decision rule

The decision rule implemented is not quite smart, the code in Python is presented here:

@staticmethod
def nextMove(board,recursion_depth=3):
    m,s = AI.nextMoveRecur(board,recursion_depth,recursion_depth)
    return m

@staticmethod
def nextMoveRecur(board,depth,maxDepth,base=0.9):
    bestScore = -1.
    bestMove = 0
    for m in range(1,5):
        if(board.validMove(m)):
            newBoard = copy.deepcopy(board)
            newBoard.move(m,add_tile=True)

            score = AI.evaluate(newBoard)
            if depth != 0:
                my_m,my_s = AI.nextMoveRecur(newBoard,depth-1,maxDepth)
                score += my_s*pow(base,maxDepth-depth+1)

            if(score > bestScore):
                bestMove = m
                bestScore = score
    return (bestMove,bestScore);

An implementation of the minmax or the Expectiminimax will surely improve the algorithm. Obviously a more sophisticated decision rule will slow down the algorithm and it will require some time to be implemented.I will try a minimax implementation in the near future. (stay tuned)

Benchmark

  • T1 - 121 tests - 8 different paths - r=0.125
  • T2 - 122 tests - 8-different paths - r=0.25
  • T3 - 132 tests - 8-different paths - r=0.5
  • T4 - 211 tests - 2-different paths - r=0.125
  • T5 - 274 tests - 2-different paths - r=0.25
  • T6 - 211 tests - 2-different paths - r=0.5

enter image description here enter image description here enter image description here enter image description here

In case of T2, four tests in ten generate the 4096 tile with an average score of s 42000

Code

The code can be found on GiHub at the following link: https://github.com/Nicola17/term2048-AI It is based on term2048 and it's written in Python. I will implement a more efficient version in C++ as soon as possible.

PYODBC--Data source name not found and no default driver specified

You could try:

import pyodbc
# Using a DSN
cnxn = pyodbc.connect('DSN=odbc_datasource_name;UID=db_user_id;PWD=db_password')

Note: You will need to know the "odbc_datasource_name". In Windows you can search for ODBC Data Sources. The name will look something like this:

Data Source Name Example

Java String declaration

First one will create new String object in heap and str will refer it. In addition literal will also be placed in String pool. It means 2 objects will be created and 1 reference variable.

Second option will create String literal in pool only and str will refer it. So only 1 Object will be created and 1 reference. This option will use the instance from String pool always rather than creating new one each time it is executed.

What are the best practices for SQLite on Android?

  • Use a Thread or AsyncTask for long-running operations (50ms+). Test your app to see where that is. Most operations (probably) don't require a thread, because most operations (probably) only involve a few rows. Use a thread for bulk operations.
  • Share one SQLiteDatabase instance for each DB on disk between threads and implement a counting system to keep track of open connections.

Are there any best practices for these scenarios?

Share a static field between all your classes. I used to keep a singleton around for that and other things that need to be shared. A counting scheme (generally using AtomicInteger) also should be used to make sure you never close the database early or leave it open.

My solution:

The old version I wrote is available at https://github.com/Taeluf/dev/tree/main/archived/databasemanager and is not maintained. If you want to understand my solution, look at the code and read my notes. My notes are usually pretty helpful.

  1. copy/paste the code into a new file named DatabaseManager. (or download it from github)
  2. extend DatabaseManager and implement onCreate and onUpgrade like you normally would. You can create multiple subclasses of the one DatabaseManager class in order to have different databases on disk.
  3. Instantiate your subclass and call getDb() to use the SQLiteDatabase class.
  4. Call close() for each subclass you instantiated

The code to copy/paste:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.util.concurrent.ConcurrentHashMap;

/** Extend this class and use it as an SQLiteOpenHelper class
 *
 * DO NOT distribute, sell, or present this code as your own. 
 * for any distributing/selling, or whatever, see the info at the link below
 *
 * Distribution, attribution, legal stuff,
 * See https://github.com/JakarCo/databasemanager
 * 
 * If you ever need help with this code, contact me at [email protected] (or [email protected] )
 * 
 * Do not sell this. but use it as much as you want. There are no implied or express warranties with this code. 
 *
 * This is a simple database manager class which makes threading/synchronization super easy.
 *
 * Extend this class and use it like an SQLiteOpenHelper, but use it as follows:
 *  Instantiate this class once in each thread that uses the database. 
 *  Make sure to call {@link #close()} on every opened instance of this class
 *  If it is closed, then call {@link #open()} before using again.
 * 
 * Call {@link #getDb()} to get an instance of the underlying SQLiteDatabse class (which is synchronized)
 *
 * I also implement this system (well, it's very similar) in my <a href="http://androidslitelibrary.com">Android SQLite Libray</a> at http://androidslitelibrary.com
 * 
 *
 */
abstract public class DatabaseManager {
    
    /**See SQLiteOpenHelper documentation
    */
    abstract public void onCreate(SQLiteDatabase db);
    /**See SQLiteOpenHelper documentation
     */
    abstract public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
    /**Optional.
     * *
     */
    public void onOpen(SQLiteDatabase db){}
    /**Optional.
     * 
     */
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
    /**Optional
     * 
     */
    public void onConfigure(SQLiteDatabase db){}



    /** The SQLiteOpenHelper class is not actually used by your application.
     *
     */
    static private class DBSQLiteOpenHelper extends SQLiteOpenHelper {

        DatabaseManager databaseManager;
        private AtomicInteger counter = new AtomicInteger(0);

        public DBSQLiteOpenHelper(Context context, String name, int version, DatabaseManager databaseManager) {
            super(context, name, null, version);
            this.databaseManager = databaseManager;
        }

        public void addConnection(){
            counter.incrementAndGet();
        }
        public void removeConnection(){
            counter.decrementAndGet();
        }
        public int getCounter() {
            return counter.get();
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            databaseManager.onCreate(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            databaseManager.onUpgrade(db, oldVersion, newVersion);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            databaseManager.onOpen(db);
        }

        @Override
        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            databaseManager.onDowngrade(db, oldVersion, newVersion);
        }

        @Override
        public void onConfigure(SQLiteDatabase db) {
            databaseManager.onConfigure(db);
        }
    }

    private static final ConcurrentHashMap<String,DBSQLiteOpenHelper> dbMap = new ConcurrentHashMap<String, DBSQLiteOpenHelper>();

    private static final Object lockObject = new Object();


    private DBSQLiteOpenHelper sqLiteOpenHelper;
    private SQLiteDatabase db;
    private Context context;

    /** Instantiate a new DB Helper. 
     * <br> SQLiteOpenHelpers are statically cached so they (and their internally cached SQLiteDatabases) will be reused for concurrency
     *
     * @param context Any {@link android.content.Context} belonging to your package.
     * @param name The database name. This may be anything you like. Adding a file extension is not required and any file extension you would like to use is fine.
     * @param version the database version.
     */
    public DatabaseManager(Context context, String name, int version) {
        String dbPath = context.getApplicationContext().getDatabasePath(name).getAbsolutePath();
        synchronized (lockObject) {
            sqLiteOpenHelper = dbMap.get(dbPath);
            if (sqLiteOpenHelper==null) {
                sqLiteOpenHelper = new DBSQLiteOpenHelper(context, name, version, this);
                dbMap.put(dbPath,sqLiteOpenHelper);
            }
            //SQLiteOpenHelper class caches the SQLiteDatabase, so this will be the same SQLiteDatabase object every time
            db = sqLiteOpenHelper.getWritableDatabase();
        }
        this.context = context.getApplicationContext();
    }
    /**Get the writable SQLiteDatabase
     */
    public SQLiteDatabase getDb(){
        return db;
    }

    /** Check if the underlying SQLiteDatabase is open
     *
     * @return whether the DB is open or not
     */
    public boolean isOpen(){
        return (db!=null&&db.isOpen());
    }


    /** Lowers the DB counter by 1 for any {@link DatabaseManager}s referencing the same DB on disk
     *  <br />If the new counter is 0, then the database will be closed.
     *  <br /><br />This needs to be called before application exit.
     * <br />If the counter is 0, then the underlying SQLiteDatabase is <b>null</b> until another DatabaseManager is instantiated or you call {@link #open()}
     *
     * @return true if the underlying {@link android.database.sqlite.SQLiteDatabase} is closed (counter is 0), and false otherwise (counter > 0)
     */
    public boolean close(){
        sqLiteOpenHelper.removeConnection();
        if (sqLiteOpenHelper.getCounter()==0){
            synchronized (lockObject){
                if (db.inTransaction())db.endTransaction();
                if (db.isOpen())db.close();
                db = null;
            }
            return true;
        }
        return false;
    }
    /** Increments the internal db counter by one and opens the db if needed
    *
    */
    public void open(){
        sqLiteOpenHelper.addConnection();
        if (db==null||!db.isOpen()){
                synchronized (lockObject){
                    db = sqLiteOpenHelper.getWritableDatabase();
                }
        } 
    }
}

Convert data.frame column to a vector?

You can try something like this-

as.vector(unlist(aframe$a2))

Lambda expression to convert array/List of String to array/List of Integers

I used maptoInt() with Lambda operation for converting string to Integer

int[] arr = Arrays.stream(stringArray).mapToInt(item -> Integer.parseInt(item)).toArray();

Found a swap file by the name

Accepted answer fails to mention how to delete the .swp file.

Hit "D" when the prompt comes up and it will remove it.

In my case, after I hit D it left the latest saved version intact and deleted the .swp which got created because I exited VIM incorrectly

Gitignore not working

After going down a bit of a bit of a rabbit hole trying to follow the answers to this question (maybe because I had to do this in a visual studio project), I found the easier path was to

  1. Cut and paste the file(s) I no longer want to track into a temporary location

  2. Commit the "deletion" of those files

  3. Commit a modification of the .gitignore to exclude the files I had temporarily moved

  4. Move the files back into the folder.

I found this to be the most straight forward way to go about it (at least in a visual studio, or I would assume other IDE heave based environment like Android Studio), without accidentally shooting myself in the foot with a pretty pervasive git rm -rf --cached . , after which the visual studio project I was working on didn't load.

How can I hide/show a div when a button is clicked?

This can't be done with just HTML/CSS. You need to use javascript here. In jQuery it would be:

$('#button').click(function(e){
    e.preventDefault(); //to prevent standard click event
    $('#wizard').toggle();
});

SDK Manager.exe doesn't work

I solved my problem opening android.bat inside sdk/tools and setting the java_exe property, which was empty.

set java_exe="C:\Program Files\Java\jre6\bin\java"

How to align 3 divs (left/center/right) inside another div?

#warpcontainer  {width:800px; height:auto; border: 1px solid #000; float:left; }
#warpcontainer2 {width:260px; height:auto; border: 1px solid #000; float:left; clear:both; margin-top:10px }

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

Whether a variable is undefined

function my_url (base, opt)
{
    var retval = ["" + base];
    retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
    retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
    retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
    return retval.join("");
}

my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );

/* Returns:
     ?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

Html: Difference between cell spacing and cell padding

cellspacing and cell padding


Cell padding

is used for formatting purpose which is used to specify the space needed between the edges of the cells and also in the cell contents. The general format of specifying cell padding is as follows:

< table width="100" border="2" cellpadding="5">

The above adds 5 pixels of padding inside each cell .

Cell Spacing:

Cell spacing is one also used f formatting but there is a major difference between cell padding and cell spacing. It is as follows: Cell padding is used to set extra space which is used to separate cell walls from their contents. But in contrast cell spacing is used to set space between cells.

How to show first commit by 'git log'?

Short answer

git rev-list --max-parents=0 HEAD

(from tiho's comment. As Chris Johnsen notices, --max-parents was introduced after this answer was posted.)

Explanation

Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a subtree merge.

The git.git repository has six root commits in its history graph (one each for Linus’s initial commit, gitk, some initially separate tools, git-gui, gitweb, and git-p4). In this case, we know that e83c516 is the one we are probably interested in. It is both the earliest commit and a root commit.

It is not so simple in the general case.

Imagine that libfoo has been in development for a while and keeps its history in a Git repository (libfoo.git). Independently, the “bar” project has also been under development (in bar.git), but not for as long libfoo (the commit with the earliest date in libfoo.git has a date that precedes the commit with the earliest date in bar.git). At some point the developers of “bar” decide to incorporate libfoo into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in bar.git (there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of libfoo, not “bar”.

You can find all the root commits of the history DAG like this:

git rev-list --max-parents=0 HEAD

For the record, if --max-parents weren't available, this does also work:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"

If you have useful tags in place, then git name-rev might give you a quick overview of the history:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin

Bonus

Use this often? Hard to remember? Add a git alias for quick access

git config --global alias.first "rev-list --max-parents=0 HEAD"

Now you can simply do

git first

How to add title to seaborn boxplot

Try adding this at the end of your code:

import matplotlib.pyplot as plt

plt.title('add title here')

How to click or tap on a TextView text

OK I have answered my own question (but is it the best way?)

This is how to run a method when you click or tap on some text in a TextView:

package com.textviewy;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class TextyView extends Activity implements OnClickListener {

TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t = (TextView)findViewById(R.id.TextView01);
    t.setOnClickListener(this);
}

public void onClick(View arg0) {
    t.setText("My text on click");  
    }
}

and my main.xml is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content"             android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content"   android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content"   android:layout_height="wrap_content"></LinearLayout>

<TextView android:text="This is my first text"
 android:id="@+id/TextView01" 
 android:layout_width="wrap_content" 
 android:textStyle="bold"
 android:textSize="28dip"
 android:editable = "true"
 android:clickable="true"
 android:layout_height="wrap_content">
 </TextView>
 </LinearLayout>

How to sort an array of objects by multiple fields?

I made a quite generic multi feature sorter today. You can have a look at thenBy.js here: https://github.com/Teun/thenBy.js

It allows you to use the standard Array.sort, but with firstBy().thenBy().thenBy() style. It is way less code and complexity than the solutions posted above.

UITableView example for Swift

Here is the Swift 4 version.

import Foundation
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{ 
    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad()
    {
        super.viewDidLoad()

        tableView.frame = CGRect(x: 0, y: 50, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return animals.count
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    private func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath)
    {
        print("You tapped cell number \(indexPath.row).")
    }

}

How do I cancel form submission in submit button onclick event?

You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:

<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>

function btnClick() {
    if (!validData()) return false;
}

Edit onSubmit belongs in the form tag.

Git vs Team Foundation Server

I think, the statement

everyone hates it except me

makes any further discussion waste: when you keep using Git, they will blame you if anything goes wrong.

Apart from this, for me Git has two advantages over a centralized VCS that I appreciate most (as partly described by Rob Sobers):

  • automatic backup of the whole repo: everytime someone pulls from the central repo, he/she gets a full history of the changes. When one repo gets lost: don't worry, take one of those present on every workstation.
  • offline repo access: when I'm working at home (or in an airplane or train), I can see the full history of the project, every single checkin, without starting up my VPN connection to work and can work like I were at work: checkin, checkout, branch, anything.

But as I said: I think that you're fighting a lost battle: when everyone hates Git, don't use Git. It could help you more to know why they hate Git instead of trying them to convince them.

If they simply don't want it 'cause it's new to them and are not willing to learn something new: are you sure that you will do successful development with that staff?

Does really every single person hate Git or are they influenced by some opinion leaders? Find the leaders and ask them what's the problem. Convince them and you'll convince the rest of the team.

If you cannot convince the leaders: forget about using Git, take the TFS. Will make your life easier.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Attach onchange event to the checkbox:

<input class="coupon_question" type="checkbox" name="coupon_question" value="1" onchange="valueChanged()"/>

<script type="text/javascript">
    function valueChanged()
    {
        if($('.coupon_question').is(":checked"))   
            $(".answer").show();
        else
            $(".answer").hide();
    }
</script>

could not access the package manager. is the system running while installing android application

You can avoid the error by setting default device before launching application. Launch the AVD before starting the app.

Find the most common element in a list

Without the requirement about the lowest index, you can use collections.Counter for this:

from collections import Counter

a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801] 

c = Counter(a)

print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'

javascript: get a function's variable's value within another function

nameContent only exists within the first() function, as you defined it within the first() function.

To make its scope broader, define it outside of the functions:

var nameContent;

function first(){
    nameContent=document.getElementById('full_name').value;
}

function second() {
    first();
    y=nameContent; alert(y);
}
second();

A slightly better approach would be to return the value, as global variables get messy very quickly:

function getFullName() {
  return document.getElementById('full_name').value;
}

function doStuff() {
  var name = getFullName();

  alert(name);
}

doStuff();

Unrecognized SSL message, plaintext connection? Exception

Another reason is maybe "access denided", maybe you can't access to the URI and received blocking response page for internal network access. If you are not sure your application zone need firewall rule, you try to connect from terminal,command line. For GNU/Linux or Unix, you can try run like this command and see result is coming from blocking rule or really remote address: echo | nc -v yazilimcity.net 443

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

Capture the Screen into a Bitmap

If using the .NET 2.0 (or later) framework you can use the CopyFromScreen() method detailed here:

http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html

//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                               Screen.PrimaryScreen.Bounds.Height,
                               PixelFormat.Format32bppArgb);

// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                            Screen.PrimaryScreen.Bounds.Y,
                            0,
                            0,
                            Screen.PrimaryScreen.Bounds.Size,
                            CopyPixelOperation.SourceCopy);

// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);

How to search images from private 1.0 registry in docker?

List all images

docker search <registry_host>:<registry_port>/

List images like 'vcs'

docker search <registry_host>:<registry_port>/vcs

How to print VARCHAR(MAX) using Print Statement?

There is great function called PrintMax written by Bennett Dill.

Here is slightly modified version that uses temp stored procedure to avoid "schema polution"(idea from https://github.com/Toolien/sp_GenMerge/blob/master/sp_GenMerge.sql)

EXEC (N'IF EXISTS (SELECT * FROM tempdb.sys.objects 
                   WHERE object_id = OBJECT_ID(N''tempdb..#PrintMax'') 
                   AND type in (N''P'', N''PC''))
    DROP PROCEDURE #PrintMax;');
EXEC (N'CREATE PROCEDURE #PrintMax(@iInput NVARCHAR(MAX))
AS
BEGIN
    IF @iInput IS NULL
    RETURN;

    DECLARE @ReversedData NVARCHAR(MAX)
          , @LineBreakIndex INT
          , @SearchLength INT;

    SET @SearchLength = 4000;

    WHILE LEN(@iInput) > @SearchLength
    BEGIN
    SET @ReversedData = LEFT(@iInput COLLATE DATABASE_DEFAULT, @SearchLength);
    SET @ReversedData = REVERSE(@ReversedData COLLATE DATABASE_DEFAULT);
    SET @LineBreakIndex = CHARINDEX(CHAR(10) + CHAR(13),
                          @ReversedData COLLATE DATABASE_DEFAULT);
    PRINT LEFT(@iInput, @SearchLength - @LineBreakIndex + 1);
    SET @iInput = RIGHT(@iInput, LEN(@iInput) - @SearchLength 
                        + @LineBreakIndex - 1);
    END;

    IF LEN(@iInput) > 0
    PRINT @iInput;
END;');

DBFiddle Demo

EDIT:

Using CREATE OR ALTER we could avoid two EXEC calls:

EXEC (N'CREATE OR ALTER PROCEDURE #PrintMax(@iInput NVARCHAR(MAX))
AS
BEGIN
    IF @iInput IS NULL
    RETURN;

    DECLARE @ReversedData NVARCHAR(MAX)
          , @LineBreakIndex INT
          , @SearchLength INT;

    SET @SearchLength = 4000;

    WHILE LEN(@iInput) > @SearchLength
    BEGIN
    SET @ReversedData = LEFT(@iInput COLLATE DATABASE_DEFAULT, @SearchLength);
    SET @ReversedData = REVERSE(@ReversedData COLLATE DATABASE_DEFAULT);
    SET @LineBreakIndex = CHARINDEX(CHAR(10) + CHAR(13), @ReversedData COLLATE DATABASE_DEFAULT);
    PRINT LEFT(@iInput, @SearchLength - @LineBreakIndex + 1);
    SET @iInput = RIGHT(@iInput, LEN(@iInput) - @SearchLength + @LineBreakIndex - 1);
    END;

    IF LEN(@iInput) > 0
    PRINT @iInput;
END;');

db<>fiddle Demo

How do I determine whether my calculation of pi is accurate?

You could use multiple approaches and see if they converge to the same answer. Or grab some from the 'net. The Chudnovsky algorithm is usually used as a very fast method of calculating pi. http://www.craig-wood.com/nick/articles/pi-chudnovsky/

Session 'app': Error Installing APK

If you are using android emulator, try changing a device.

How to shift a block of code left/right by one space in VSCode?

Current Version 1.38.1

I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed "Indent 4-to-2" but it changed the entire file and not the selected text.

I changed the tab spacing in settings and it was simple.

Go to Settings -> Text Editor -> Tab Size

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

Get a filtered list of files in a directory

import glob

jpgFilenamesList = glob.glob('145592*.jpg')

See glob in python documenttion

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

Difference between sh and bash

What is sh

sh (or the Shell Command Language) is a programming language described by the POSIX standard. It has many implementations (ksh88, dash, ...). bash can also be considered an implementation of sh (see below).

Because sh is a specification, not an implementation, /bin/sh is a symlink (or a hard link) to an actual implementation on most POSIX systems.

What is bash

bash started as an sh-compatible implementation (although it predates the POSIX standard by a few years), but as time passed it has acquired many extensions. Many of these extensions may change the behavior of valid POSIX shell scripts, so by itself bash is not a valid POSIX shell. Rather, it is a dialect of the POSIX shell language.

bash supports a --posix switch, which makes it more POSIX-compliant. It also tries to mimic POSIX if invoked as sh.

sh = bash?

For a long time, /bin/sh used to point to /bin/bash on most GNU/Linux systems. As a result, it had almost become safe to ignore the difference between the two. But that started to change recently.

Some popular examples of systems where /bin/sh does not point to /bin/bash (and on some of which /bin/bash may not even exist) are:

  1. Modern Debian and Ubuntu systems, which symlink sh to dash by default;
  2. Busybox, which is usually run during the Linux system boot time as part of initramfs. It uses the ash shell implementation.
  3. BSDs, and in general any non-Linux systems. OpenBSD uses pdksh, a descendant of the Korn shell. FreeBSD's sh is a descendant of the original UNIX Bourne shell. Solaris has its own sh which for a long time was not POSIX-compliant; a free implementation is available from the Heirloom project.

How can you find out what /bin/sh points to on your system?

The complication is that /bin/sh could be a symbolic link or a hard link. If it's a symbolic link, a portable way to resolve it is:

% file -h /bin/sh
/bin/sh: symbolic link to bash

If it's a hard link, try

% find -L /bin -samefile /bin/sh
/bin/sh
/bin/bash

In fact, the -L flag covers both symlinks and hardlinks, but the disadvantage of this method is that it is not portable — POSIX does not require find to support the -samefile option, although both GNU find and FreeBSD find support it.

Shebang line

Ultimately, it's up to you to decide which one to use, by writing the «shebang» line as the very first line of the script.

E.g.

#!/bin/sh

will use sh (and whatever that happens to point to),

#!/bin/bash

will use /bin/bash if it's available (and fail with an error message if it's not). Of course, you can also specify another implementation, e.g.

#!/bin/dash

Which one to use

For my own scripts, I prefer sh for the following reasons:

  • it is standardized
  • it is much simpler and easier to learn
  • it is portable across POSIX systems — even if they happen not to have bash, they are required to have sh

There are advantages to using bash as well. Its features make programming more convenient and similar to programming in other modern programming languages. These include things like scoped local variables and arrays. Plain sh is a very minimalistic programming language.

TypeError: $(...).autocomplete is not a function

you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

Select data from "show tables" MySQL query

You can't put SHOW statements inside a subquery like in your example. The only statement that can go in a subquery is SELECT.

As other answers have stated, you can query the INFORMATION_SCHEMA directly with SELECT and get a lot more flexibility that way.

MySQL's SHOW statements are internally just queries against the INFORMATION_SCHEMA tables.

User @physicalattraction has posted this comment on most other answers:

This gives you (meta)information about the tables, not the contents of the table, as the OP intended. – physicalattraction

On the contrary, the OP's question does not say that they want to select the data in all the tables. They say they want to select from the result of SHOW TABLES, which is just a list of table names.

If the OP does want to select all data from all tables, then the answer is no, you can't do it with one query. Each query must name its tables explicitly. You can't make a table name be a variable or the result of another part of the same query. Also, all rows of a given query result must have the same columns.

So the only way to select all data from all tables would be to run SHOW TABLES and then for each table named in that result, run another query.

Wordpress keeps redirecting to install-php after migration

I experienced the same issue as the OP - Wordpress keeps redirecting to install-php after migration.

Problem was my database tables are named as prefix_tablename and I missed the underscore from $table_prefix in wp-config.

$table_prefix = 'myprefix';

should have been

$table_prefix = 'myprefix_';

CURL to pass SSL certifcate and password

I went through this when trying to get a clientcert and private key out of a keystore.

The link above posted by welsh was great, but there was an extra step on my redhat distribution. If curl is built with NSS ( run curl --version to see if you see NSS listed) then you need to import the keys into an NSS keystore. I went through a bunch of convoluted steps, so this may not be the cleanest way, but it got things working

So export the keys into .p12

keytool -importkeystore -srckeystore $jksfile -destkeystore $p12file \
        -srcstoretype JKS -deststoretype PKCS12 \
        -srcstorepass $jkspassword -deststorepass $p12password  
        -srcalias $myalias -destalias $myalias \
        -srckeypass $keypass -destkeypass $keypass -noprompt

And generate the pem file that holds only the key

 echo making ${fileroot}.key.pem
 openssl pkcs12 -in $p12 -out ${fileroot}.key.pem  \
         -passin pass:$p12password  \
         -passout pass:$p12password  -nocerts
  • Make an empty keystore:
mkdir ~/nss
chmod 700 ~/nss
certutil -N -d ~/nss
  • Import the keys into the keystore
pks12util -i <mykeys>.p12 -d ~/nss -W <password for cert >

Now curl should work.

curl --insecure --cert <client cert alias>:<password for cert> \
     --key ${fileroot}.key.pem  <URL>

As I mentioned, there may be other ways to do this, but at least this was repeatable for me. If curl is compiled with NSS support, I was not able to get it to pull the client cert from a file.

Package doesn't exist error in intelliJ

None of the 13 existing answers worked for me. However, I could resolve the issue by first removing all modules:

  1. open File > Project Structure...,
  2. go to Modules tab,
  3. select all modules and press the remove button,

then removing all remaining Maven modules from Maven tool window:

  1. select all modules,
  2. right click on them,
  3. press Remove projects,

and then adding them again in Project tool window:

  1. right click on root pom.xml,
  2. press Add as Maven project,

now unignoring any ignored modules from Maven tool window:

  1. select all ignored (grey) Maven modules,
  2. right click on them,
  3. press Unignore,

and finally rebuilding using Build > Rebuild project. This assumes that a mvn clean install already happened.

How to get a unique device ID in Swift?

The value of identifierForVendor changes when the user deletes all of that vendor’s apps from the device, if you want to keep the unique ID even for the subsequent fresh installations, you can try to use the following function

func vendorIdentifierForDevice()->String {
    //Get common part of Applicatoin Bundle ID, Note : getCommonPartOfApplicationBundleID is to be defined.
    let commonAppBundleID = getCommonPartOfApplicationBundleID()
    //Read from KeyChain using bunndle ID, Note : readFromKeyChain is to be defined.
    if let vendorID = readFromKeyChain(commonAppBundleID) {
        return vendorID
    } else {
        var vendorID = NSUUID().uuidString
        //Save to KeyChain using bunndle ID, Note : saveToKeyChain is to be defined.
        saveToKeyChain(commonAppBundleID, vendorID)
        return vendorID
    }
}

How to Disable landscape mode in Android?

add class inside oncreate() method

 setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

Default locations:

Programs > Microsoft SQL Server 2008 R2 > SQL Server Management Studio for Query Analyzer. Programs > Microsoft SQL Server 2008 R2 > Performance Tools > SQL Server Profiler for profiler.

Replace only text inside a div using jquery

Find the text nodes (nodeType==3) and replace the textContent:

$('#one').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});

Note that as per the docs you can replace the hard-coded 3 in the above with Node.TEXT_NODE which is much clearer what you're doing.

_x000D_
_x000D_
$('#one').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
       <div class="first"></div>
       "Hi I am text"
       <div class="second"></div>
       <div class="third"></div>
</div>
_x000D_
_x000D_
_x000D_

UIWebView open links in Safari

One quick comment to user306253's answer: caution with this, when you try to load something in the UIWebView yourself (i.e. even from the code), this method will prevent it to happened.

What you can do to prevent this (thanks Wade) is:

if (inType == UIWebViewNavigationTypeLinkClicked) {
    [[UIApplication sharedApplication] openURL:[inRequest URL]];
    return NO;
}

return YES;

You might also want to handle the UIWebViewNavigationTypeFormSubmitted and UIWebViewNavigationTypeFormResubmitted types.

"The page has expired due to inactivity" - Laravel 5.5

I have figured out two solution to avoid these error 1)by adding protected $except = ['/yourroute'] possible disable csrf token inspection from defined root. 2)just comment \App\Http\Middleware\VerifyCsrfToken::class line in protected middleware group in kernel

What could cause java.lang.reflect.InvocationTargetException?

The error vanished after I did Clean->Run xDoclet->Run xPackaging.

In my workspace, in ecllipse.

Get an element by index in jQuery

You can use jQuery's .eq() method to get the element with a certain index.

$('ul li').eq(index).css({'background-color':'#343434'});

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

Another option is using command line:

code -d left.txt right.txt

Note: You may need to add code to your path first. See: How to call VS Code Editor from command line

Getting next element while cycling through a list

while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...

How to convert a String into an ArrayList?

I recommend use the StringTokenizer, is very efficient

     List<String> list = new ArrayList<>();

     StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
     while (token.hasMoreTokens()) {
           list.add(token.nextToken());
     }

Declaring abstract method in TypeScript

No, no, no! Please do not try to make your own 'abstract' classes and methods when the language does not support that feature; the same goes for any language feature you wish a given language supported. There is no correct way to implement abstract methods in TypeScript. Just structure your code with naming conventions such that certain classes are never directly instantiated, but without explicitly enforcing this prohibition.

Also, the example above is only going to provide this enforcement at run time, NOT at compile time, as you would expect in Java/C#.

Swift addsubview and remove it

I've a view inside my custom CollectionViewCell, and embedding a graph on that view. In order to refresh it, I've to check if there is already a graph placed on that view, remove it and then apply new. Here's the solution

cell.cellView.addSubview(graph)
graph.tag = 10

now, in code block where you want to remove it (in your case gestureRecognizerFunction)

if let removable = cell.cellView.viewWithTag(10){
   removable.removeFromSuperview()
}

to embed it again

cell.cellView.addSubview(graph)
graph.tag = 10

Get last 5 characters in a string

I opened this thread looking for a quick solution to a simple question, but I found that the answers here were either not helpful or overly complicated. The best way to get the last 5 chars of a string is, in fact, to use the Right() method. Here is a simple example:

Dim sMyString, sLast5 As String

sMyString = "I will be going to school in 2011!"
sLast5 = Right(sMyString, - 5)
MsgBox("sLast5 = " & sLast5)

If you're getting an error then there is probably something wrong with your syntax. Also, with the Right() method you don't need to worry much about going over or under the string length. In my example you could type in 10000 instead of 5 and it would just MsgBox the whole string, or if sMyString was NULL or "", the message box would just pop up with nothing.

program cant start because php5.dll is missing

if your php version is Non-Thread-Safe (nts) you must use php extension with format example: extension=php_cl_dbg_5_2_nts.dll else if your php version is Thread-Safe (ts) you must use php extension with format example: extension=php_cl_dbg_5_2_ts.dll (notice bolded words)

So if get error like above. Firstly, check your PHP version is nts or ts, if is nts.
Then check in php.ini whether has any line like zend_extension_ts="C:\xammp\php\ext\php_dbg.dll-5.2.x" choose right version of php_dbg.dll-5.2.x from it homepage (google for it). Change from zend_extension_ts to zend_extension_nts.

Hope this help.

Array versus List<T>: When to use which?

Lists in .NET are wrappers over arrays, and use an array internally. The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class). Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

No tests found with test runner 'JUnit 4'

I also faced this Issue while implementing @RunWith(Cucumber.class). Since this annotation was inside a Public class and hence Eclipse Shows this "No tests found with test runner not found" error.

Once I called / placed the test runner annotation before the runner class, The tests showed up nicely.

Readers must identify which Junit Test Runner they are using. One can check with @RunWith(JUnit4.class) is Outside or inside the runner.class parenthesis {}. If its inside, Please place it outside.

Cannot kill Python script with Ctrl-C

KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python

Apply CSS rules if browser is IE

A good way to avoid loading multiple CSS files or to have inline CSS is to hand a class to the body tag depending on the version of Internet Explorer. If you only need general IE hacks, you can do something like this, but it can be extended to be version specific:

<!--[if IE ]><body class="ie"><![endif]-->
<!--[if !IE]>--><body><!--<![endif]-->

Now in your css code, you can simply do:

.ie .abc {
  position:absolute;
  left:30;
  top:-10;
}

This also keeps your CSS files valid, as you do not have to use dirty (and invalid) CSS hacks.

OSError: [Errno 8] Exec format error

If you think the space before and after "=" is mandatory, try it as separate item in the list.

Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

Call ASP.NET function from JavaScript?

Static, strongly-typed programming has always felt very natural to me, so at first I resisted learning JavaScript (not to mention HTML and CSS) when I had to build web-based front-ends for my applications. I would do anything to work around this like redirecting to a page just to perform and action on the OnLoad event, as long as I could code pure C#.

You will find however that if you are going to be working with websites, you must have an open mind and start thinking more web-oriented (that is, don't try to do client-side things on the server and vice-versa). I love ASP.NET webforms and still use it (as well as MVC), but I will say that by trying to make things simpler and hiding the separation of client and server it can confuse newcomers and actually end up making things more difficult at times.

My advice is to learn some basic JavaScript (how to register events, retrieve DOM objects, manipulate CSS, etc.) and you will find web programming much more enjoyable (not to mention easier). A lot of people mentioned different Ajax libraries, but I didn't see any actual Ajax examples, so here it goes. (If you are not familiar with Ajax, all it is, is making an asynchronous HTTP request to refresh content (or perhaps perform a server-side action in your scenario) without reloading the entire page or doing a full postback.

Client-Side:

<script type="text/javascript">
var xmlhttp = new XMLHttpRequest(); // Create object that will make the request
xmlhttp.open("GET", "http://example.org/api/service", "true"); // configure object (method, URL, async)
xmlhttp.send(); // Send request

xmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to <p>
    if (xmlhttp.readyState == 4 && xmlhttp.statsCode == 200) {
          document.getElementById("resultText").innerHTML = xmlhttp.responseText;
    }
};
</script>

That's it. Although the name can be misleading the result can be in plain text or JSON as well, you are not limited to XML. jQuery provides an even simpler interface for making Ajax calls (among simplifying other JavaScript tasks).

The request can be an HTTP-POST or HTTP-GET and does not have to be to a webpage, but you can post to any service that listens for HTTP requests such as a RESTful API. The ASP.NET MVC 4 Web API makes setting up the server-side web service to handle the request a breeze as well. But many people do not know that you can also add API controllers to web forms project and use them to handle Ajax calls like this.

Server-Side:

public class DataController : ApiController
{
    public HttpResponseMessage<string[]> Get()
    {
        HttpResponseMessage<string[]> response = new HttpResponseMessage<string[]>(
            Repository.Get(true),
            new MediaTypeHeaderValue("application/json")
        );

        return response;
    }
}

Global.asax

Then just register the HTTP route in your Global.asax file, so ASP.NET will know how to direct the request.

void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHttpRoute("Service", "api/{controller}/{id}");
}

With AJAX and Controllers, you can post back to the server at any time asynchronously to perform any server side operation. This one-two punch provides both the flexibility of JavaScript and the power the C# / ASP.NET, giving the people visiting your site a better overall experience. Without sacrificing anything, you get the best of both worlds.

References

css transition opacity fade background

Please note that the problem is not white color. It is because it is being transparent.

When an element is made transparent, all of its child element's opacity; alpha filter in IE 6 7 etc, is changed to the new value.

So you cannot say that it is white!

You can place an element above it, and change that element's transparency to 1 while changing the image's transparency to .2 or what so ever you want to.

Read data from a text file using Java

user scanner it should work

         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close(); 

How to add button tint programmatically

In properly extending dimsuz's answer by providing a real code situation, see the following code snippet:

    Drawable buttonDrawable = button.getBackground();
    buttonDrawable = DrawableCompat.wrap(buttonDrawable);
    //the color is a direct color int and not a color resource
    DrawableCompat.setTint(buttonDrawable, Color.RED);
    button.setBackground(buttonDrawable);

This solution is for the scenario where a drawable is used as the button's background. It works on pre-Lollipop devices as well.

How to set UITextField height?

You can not change the height of the rounded rect border style. To set the height, just choose any border style other than rounded border in Xcode:

enter image description here

How do I generate sourcemaps when using babel and webpack?

Minimal webpack config for jsx with sourcemaps:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: `./src/index.jsx` ,
  output: {
    path:  path.resolve(__dirname,"build"),
    filename: "bundle.js"
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

Running it:

Jozsefs-MBP:react-webpack-babel joco$ webpack -d
Hash: c75d5fb365018ed3786b
Version: webpack 1.13.2
Time: 3826ms
        Asset     Size  Chunks             Chunk Names
    bundle.js   1.5 MB       0  [emitted]  main
bundle.js.map  1.72 MB       0  [emitted]  main
    + 221 hidden modules
Jozsefs-MBP:react-webpack-babel joco$

HTML table sort

The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.

The basic process is:

  1. add a click handler to each table header
  2. the click handler notes the index of the column to be sorted
  3. the table is converted to an array of arrays (rows and cells)
  4. that array is sorted using javascript sort function
  5. the data from the sorted array is inserted back into the HTML table

The table should, of course, be nice HTML. Something like this...

<table>
 <thead>
  <tr><th>Name</th><th>Age</th></tr>
 </thead>
 <tbody>
  <tr><td>Sioned</td><td>62</td></tr>
  <tr><td>Dylan</td><td>37</td></tr>
  ...etc...
 </tbody>
</table>

So, first adding the click handlers...

const table = document.querySelector('table'); //get the table to be sorted

table.querySelectorAll('th') // get all the table header elements
  .forEach((element, columnNo)=>{ // add a click handler for each 
    element.addEventListener('click', event => {
        sortTable(table, columnNo); //call a function which sorts the table by a given column number
    })
  })

This won't work right now because the sortTable function which is called in the event handler doesn't exist.

Lets write it...

function sortTable(table, sortColumn){
  // get the data from the table cells
  const tableBody = table.querySelector('tbody')
  const tableData = table2data(tableBody);
  // sort the extracted data
  tableData.sort((a, b)=>{
    if(a[sortColumn] > b[sortColumn]){
      return 1;
    }
    return -1;
  })
  // put the sorted data back into the table
  data2table(tableBody, tableData);
}

So now we get to the meat of the problem, we need to make the functions table2data to get data out of the table, and data2table to put it back in once sorted.

Here they are ...

// this function gets data from the rows and cells 
// within an html tbody element
function table2data(tableBody){
  const tableData = []; // create the array that'll hold the data rows
  tableBody.querySelectorAll('tr')
    .forEach(row=>{  // for each table row...
      const rowData = [];  // make an array for that row
      row.querySelectorAll('td')  // for each cell in that row
        .forEach(cell=>{
          rowData.push(cell.innerText);  // add it to the row data
        })
      tableData.push(rowData);  // add the full row to the table data 
    });
  return tableData;
}

// this function puts data into an html tbody element
function data2table(tableBody, tableData){
  tableBody.querySelectorAll('tr') // for each table row...
    .forEach((row, i)=>{  
      const rowData = tableData[i]; // get the array for the row data
      row.querySelectorAll('td')  // for each table cell ...
        .forEach((cell, j)=>{
          cell.innerText = rowData[j]; // put the appropriate array element into the cell
        })
      tableData.push(rowData);
    });
}

And that should do it.

A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2" is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.

How can I make sticky headers in RecyclerView? (Without external lib)

Yo,

This is how you do it if you want just one type of holder stick when it starts getting out of the screen (we are not caring about any sections). There is only one way without breaking the internal RecyclerView logic of recycling items and that is to inflate additional view on top of the recyclerView's header item and pass data into it. I'll let the code speak.

import android.graphics.Canvas
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

class StickyHeaderItemDecoration(@LayoutRes private val headerId: Int, private val HEADER_TYPE: Int) : RecyclerView.ItemDecoration() {

private lateinit var stickyHeaderView: View
private lateinit var headerView: View

private var sticked = false

// executes on each bind and sets the stickyHeaderView
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
    super.getItemOffsets(outRect, view, parent, state)

    val position = parent.getChildAdapterPosition(view)

    val adapter = parent.adapter ?: return
    val viewType = adapter.getItemViewType(position)

    if (viewType == HEADER_TYPE) {
        headerView = view
    }
}

override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)
    if (::headerView.isInitialized) {

        if (headerView.y <= 0 && !sticked) {
            stickyHeaderView = createHeaderView(parent)
            fixLayoutSize(parent, stickyHeaderView)
            sticked = true
        }

        if (headerView.y > 0 && sticked) {
            sticked = false
        }

        if (sticked) {
            drawStickedHeader(c)
        }
    }
}

private fun createHeaderView(parent: RecyclerView) = LayoutInflater.from(parent.context).inflate(headerId, parent, false)

private fun drawStickedHeader(c: Canvas) {
    c.save()
    c.translate(0f, Math.max(0f, stickyHeaderView.top.toFloat() - stickyHeaderView.height.toFloat()))
    headerView.draw(c)
    c.restore()
}

private fun fixLayoutSize(parent: ViewGroup, view: View) {

    // Specs for parent (RecyclerView)
    val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
    val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED)

    // Specs for children (headers)
    val childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, view.getLayoutParams().width)
    val childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, view.getLayoutParams().height)

    view.measure(childWidthSpec, childHeightSpec)

    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
}

}

And then you just do this in your adapter:

override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
    super.onAttachedToRecyclerView(recyclerView)
    recyclerView.addItemDecoration(StickyHeaderItemDecoration(R.layout.item_time_filter, YOUR_STICKY_VIEW_HOLDER_TYPE))
}

Where YOUR_STICKY_VIEW_HOLDER_TYPE is viewType of your what is supposed to be sticky holder.

Connect to network drive with user name and password

You can use the WindowsIdentity class (with a logon token) to impersonate while reading and writing files.

var windowsIdentity = new WindowsIdentity(logonToken);
using (var impersonationContext = windowsIdentity.Impersonate()) {
    // Connect, read, write
}

Angularjs - display current date

Just my 2 cents in case someone stumble upon this :)

What I am suggesting here will have the same result as the current answer however it has been recommended to write your controller the way that I have mentioned here.

Reference scroll to the first "Note" (Sorry it doesn't have anchor)

Here is the recommended way:

Controller:

var app = angular.module('myApp', []);   
app.controller( 'MyCtrl', ['$scope', function($scope) {
    $scope.date = new Date();
}]);

View:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    {{date | date:'yyyy-MM-dd'}}
  </div>
</div>

Dynamic classname inside ngClass in angular 2

more elegant solution is to use && (using NgFor and its first, its free to use ur own matching tho):

    <div 
        *ngFor="let day of days;
                let first = first;"
        class="day"
        [ngClass]="first && ('day--' + day)"
    </div>

will turn out as:

class="day day--monday"

How can I load Partial view inside the view?

If you do it with a @Html.ActionLink() then loading the PartialView is handled as a normal request when clicking a anchor-element, i.e. load new page with the reponse of the PartialViewResult method.
If you want to load it immedialty, then you use @Html.RenderPartial("_LoadView") or @Html.RenderAction("Load").
If you want to do it upon userinteraction (i.e. clicking a link) then you need to use AJAX --> @Ajax.ActionLink()

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Use notepad++, go to edit -> EOL conversion -> change from CRLF to LF.

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

Why does .NET foreach loop throw NullRefException when collection is null?

Well, the short answer is "because that's the way the compiler designers designed it." Realistically, though, your collection object is null, so there's no way for the compiler to get the enumerator to loop through the collection.

If you really need to do something like this, try the null coalescing operator:

int[] array = null;

foreach (int i in array ?? Enumerable.Empty<int>())
{
   System.Console.WriteLine(string.Format("{0}", i));
}

Fastest way to serialize and deserialize .NET objects

Having an interest in this, I decided to test the suggested methods with the closest "apples to apples" test I could. I wrote a Console app, with the following code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SerializationTests
{
    class Program
    {
        static void Main(string[] args)
        {
            var count = 100000;
            var rnd = new Random(DateTime.UtcNow.GetHashCode());
            Console.WriteLine("Generating {0} arrays of data...", count);
            var arrays = new List<int[]>();
            for (int i = 0; i < count; i++)
            {
                var elements = rnd.Next(1, 100);
                var array = new int[elements];
                for (int j = 0; j < elements; j++)
                {
                    array[j] = rnd.Next();
                }   
                arrays.Add(array);
            }
            Console.WriteLine("Test data generated.");
            var stopWatch = new Stopwatch();

            Console.WriteLine("Testing BinarySerializer...");
            var binarySerializer = new BinarySerializer();
            var binarySerialized = new List<byte[]>();
            var binaryDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                binarySerialized.Add(binarySerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in binarySerialized)
            {
                binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);


            Console.WriteLine();
            Console.WriteLine("Testing ProtoBuf serializer...");
            var protobufSerializer = new ProtoBufSerializer();
            var protobufSerialized = new List<byte[]>();
            var protobufDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                protobufSerialized.Add(protobufSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in protobufSerialized)
            {
                protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            Console.WriteLine();
            Console.WriteLine("Testing NetSerializer serializer...");
            var netSerializerSerializer = new ProtoBufSerializer();
            var netSerializerSerialized = new List<byte[]>();
            var netSerializerDeserialized = new List<int[]>();

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var array in arrays)
            {
                netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

            stopWatch.Reset();
            stopWatch.Start();
            foreach (var serialized in netSerializerSerialized)
            {
                netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
            }
            stopWatch.Stop();
            Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);

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

        public class BinarySerializer
        {
            private static readonly BinaryFormatter Formatter = new BinaryFormatter();

            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    Formatter.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = (T)Formatter.Deserialize(stream);
                    return result;
                }
            }
        }

        public class ProtoBufSerializer
        {
            public byte[] Serialize(object toSerialize)
            {
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(stream, toSerialize);
                    return stream.ToArray();
                }
            }

            public T Deserialize<T>(byte[] serialized)
            {
                using (var stream = new MemoryStream(serialized))
                {
                    var result = ProtoBuf.Serializer.Deserialize<T>(stream);
                    return result;
                }
            }
        }

        public class NetSerializer
        {
            private static readonly NetSerializer Serializer = new NetSerializer();
            public byte[] Serialize(object toSerialize)
            {
                return Serializer.Serialize(toSerialize);
            }

            public T Deserialize<T>(byte[] serialized)
            {
                return Serializer.Deserialize<T>(serialized);
            }
        }
    }
}

The results surprised me; they were consistent when run multiple times:

Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 336.8392ms.
BinaryFormatter: Deserializing took 208.7527ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 2284.3827ms.
ProtoBuf: Deserializing took 2201.8072ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 2139.5424ms.
NetSerializer: Deserializing took 2113.7296ms.
Press any key to end.

Collecting these results, I decided to see if ProtoBuf or NetSerializer performed better with larger objects. I changed the collection count to 10,000 objects, but increased the size of the arrays to 1-10,000 instead of 1-100. The results seemed even more definitive:

Generating 10000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 285.8356ms.
BinaryFormatter: Deserializing took 206.0906ms.

Testing ProtoBuf serializer...
ProtoBuf: Serializing took 10693.3848ms.
ProtoBuf: Deserializing took 5988.5993ms.

Testing NetSerializer serializer...
NetSerializer: Serializing took 9017.5785ms.
NetSerializer: Deserializing took 5978.7203ms.
Press any key to end.

My conclusion, therefore, is: there may be cases where ProtoBuf and NetSerializer are well-suited to, but in terms of raw performance for at least relatively simple objects... BinaryFormatter is significantly more performant, by at least an order of magnitude.

YMMV.

Plotting lines connecting points

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

enter image description here

Stop a youtube video with jquery?

Unfortunately, if id attribute of object tag don't exists, the play/stop/pauseVideo() don't work by IE.

<object style="display: block; margin-left: auto; margin-right: auto;" width="425" height="344" data="http://www.youtube.com/v/7scnebkm3r0&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" />
  <param name="allowscriptaccess" value="always" />
  <param name="allowfullscreen" value="true" />
  <param name="src" value="http://www.youtube.com/v/7scnebkm3r0&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" />
</object>
<object id="idexists" style="display: block; margin-left: auto; margin-right: auto;" width="425" height="344" data="http://www.youtube.com/v/pDW47HNaN84&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash">
  <param name="allowscriptaccess" value="always" />
  <param name="allowFullScreen" value="true" />
  <param name="src" value="http://www.youtube.com/v/pDW47HNaN84&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" />
</object>
<script>
  function pauseVideo()
  {
    $("object").each
    (
      function(index)
      {
        obj = $(this).get(0);
        if (obj.pauseVideo) obj.pauseVideo();
      }
    );
  }
</script>
<button onClick="pauseVideo();">Pause</button>

Try it!

How to define a variable in a Dockerfile?

You can use ARG variable defaultValue and during the run command you can even update this value using --build-arg variable=value. To use these variables in the docker file you can refer them as $variable in run command.

Note: These variables would be available for Linux commands like RUN echo $variable and they wouldn't persist in the image.

Writing a dictionary to a text file?

First of all you are opening file in read mode and trying to write into it. Consult - IO modes python

Secondly, you can only write a string to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.

import json

# as requested in comment
exDict = {'exDict': exDict}

with open('file.txt', 'w') as file:
     file.write(json.dumps(exDict)) # use `json.loads` to do the reverse

In case of serialization

import cPickle as pickle

with open('file.txt', 'w') as file:
     file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse

For python 3.x pickle package import would be different

import _pickle as pickle

sass :first-child not working

While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.

As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:

div#top-level
  declarations: ...
  div.inside
    declarations: ...
    &:first-child
      declarations: ...

which compiles as one would expect:

div#top-level{
  declarations... }
div#top-level div.inside {
  declarations... }
div#top-level div.inside:first-child {
  declarations... }

I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.

Error: vector does not name a type

You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

using namespace std;

PHP check if url parameter exists

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

Change your first line to

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}

Difference between if () { } and if () : endif;

It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.

<?php
    if($something){
        doThis();
    }else{
        echo '<h1>Title</h1>
            <p>This is a paragraph</p>
            <p>and another paragraph</p>';
    }
?>

I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:

<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
    <?php $_modes = $this->getModes(); ?>
    <?php if($_modes && count($_modes)>1): ?>
    <label><?php echo $this->__('View as') ?>:</label>
    <?php foreach ($this->getModes() as $_code=>$_label): ?>
        <?php if($this->isModeActive($_code)): ?>
            <strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>&nbsp;
        <?php else: ?>
            <a href="<?php echo $this->getModeUrl($_code) ?>" title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></a>&nbsp;
        <?php endif; ?>
    <?php endforeach; ?>
    <?php endif; ?>
</p>
<?php endif; ?>

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

Connect to Active Directory via LDAP

If your email address is '[email protected]', try changing the createDirectoryEntry() as below.

XYZ is an optional parameter if it exists in mydomain directory

static DirectoryEntry createDirectoryEntry()
{
    // create and return new LDAP connection with desired settings
    DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
    ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
    ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
    return ldapConnection;
}

This will basically check for com -> mydomain -> XYZ -> Users -> abcd

The main function looks as below:

try
{
    username = "Firstname LastName"
    DirectoryEntry myLdapConnection = createDirectoryEntry();
    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
    search.Filter = "(cn=" + username + ")";
    ....    

How to remove a Gitlab project?

This is taken from feb 2018

Follow the following test

  1. Gitlab Home Page
  2. Select your projects button under Projects Menus
  3. Click your desired project
  4. Select Settings (from left sidebar)
  5. Click Advanced settings
  6. Click Remove Project

Or Click the following Link

Note : USER_NAME will replace by your username

PROJECT_NAME will replace by your repository name

https://gitlab.com/USER_NAME/PROJECT_NAME/edit

click Expand under Advanced settings portion

Click remove project bottom of the page

enter image description here

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

How to assign from a function which returns more than one value?

I put together an R package zeallot to tackle this problem. zeallot includes a multiple assignment or unpacking assignment operator, %<-%. The LHS of the operator is any number of variables to assign, built using calls to c(). The RHS of the operator is a vector, list, data frame, date object, or any custom object with an implemented destructure method (see ?zeallot::destructure).

Here are a handful of examples based on the original post,

library(zeallot)

functionReturningTwoValues <- function() { 
  return(c(1, 2)) 
}

c(a, b) %<-% functionReturningTwoValues()
a  # 1
b  # 2

functionReturningListOfValues <- function() {
  return(list(1, 2, 3))
}

c(d, e, f) %<-% functionReturningListOfValues()
d  # 1
e  # 2
f  # 3

functionReturningNestedList <- function() {
  return(list(1, list(2, 3)))
}

c(f, c(g, h)) %<-% functionReturningNestedList()
f  # 1
g  # 2
h  # 3

functionReturningTooManyValues <- function() {
  return(as.list(1:20))
}

c(i, j, ...rest) %<-% functionReturningTooManyValues()
i     # 1
j     # 2
rest  # list(3, 4, 5, ..)

Check out the package vignette for more information and examples.

ASP.NET MVC Razor pass model to layout

Let's assume your model is a collection of objects (or maybe a single object). For each object in the model do the following.

1) Put the object you want to display in the ViewBag. For example:

  ViewBag.YourObject = yourObject;

2) Add a using statement at the top of _Layout.cshtml that contains the class definition for your objects. For example:

@using YourApplication.YourClasses;

3) When you reference yourObject in _Layout cast it. You can apply the cast because of what you did in (2).

How to create an empty file at the command line in Windows?

echo "" > filename

I believe this works on Windows/DOS, but my last hands-on experience with either is quite a while ago. I do know for a fact that it works on basically any POSIX compliant OS.

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

Push to GitHub without a password using ssh-key

Using the command line:

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

In the terminal is shows: No directory exist

Then generate a new SSH key

Step 1.

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

step 2.

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

step 3.

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

Enter same passphrase again: [Type password again]

Vue template or render function not defined yet I am using neither?

In my case, I imported my component (in router) as:

import bsw from 'common-mod/src/components/webcommon/webcommon'

It is simply solved if I changed it to

import bsw from 'common-mod/src/components/webcommon/webcommon.vue'

How to set JVM parameters for Junit Unit Tests?

An eclipse specific alternative limited to the java.library.path JVM parameter allows to set it for a specific source folder rather than for the whole jdk as proposed in another response:

  1. select the source folder in which the program to start resides (usually source/test/java)
  2. type alt enter to open Properties page for that folder
  3. select native in the left panel
  4. Edit the native path. The path can be absolute or relative to the workspace, the second being more change resilient.

For those interested on detail on why maven argline tag should be preferred to the systemProperties one, look, for example:

Pick up native JNI files in Maven test (lwjgl)

System.Collections.Generic.List does not contain a definition for 'Select'

You need to have the System.Linq namespace included in your view since Select is an extension method. You have a couple of options on how to do this:

Add @using System.Linq to the top of your cshtml file.

If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add child that adds System.Linq. Here is an example:

<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="System.Linq" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

SQLException : String or binary data would be truncated

Simply Used this: MessageBox.Show(cmd4.CommandText.ToString()); in c#.net and this will show you main query , Copy it and run in database .

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

Getting a union of two arrays in JavaScript

I'm probably wasting time on a dead thread here. I just had to implement this and went looking to see if I was wasting my time.

I really like KennyTM's answer. That's just how I would attack the problem. Merge the keys into a hash to naturally eliminate duplicates and then extract the keys. If you actually have jQuery you can leverage its goodies to make this a 2 line problem and then roll it into an extension. The each() in jQuery will take care of not iterating over items where hasOwnProperty() is false.

jQuery.fn.extend({
    union: function(array1, array2) {
        var hash = {}, union = [];
        $.each($.merge($.merge([], array1), array2), function (index, value) { hash[value] = value; });
        $.each(hash, function (key, value) { union.push(key); } );
        return union;
    }
});

Note that both of the original arrays are left intact. Then you call it like this:

var union = $.union(array1, array2);

How to deal with floating point number precision in JavaScript?

Threw this together based on @SheetJs's answer, which I liked:

_x000D_
_x000D_
  getCorrectionFactor(numberToCheck: number): number {_x000D_
    var correctionFactor: number = 1;_x000D_
    _x000D_
    if (!Number.isInteger(numberToCheck)) {_x000D_
      while (!Number.isInteger(numberToCheck)) {_x000D_
        correctionFactor *= 10;_x000D_
        numberToCheck *= correctionFactor;_x000D_
      }_x000D_
    }_x000D_
_x000D_
    return correctionFactor;_x000D_
  }
_x000D_
_x000D_
_x000D_