Programs & Examples On #Boost tuples

A Boost C++ library providing an implementation of tuple, a fixed-sized collection of elements, possibly of different types

Generating random whole numbers in JavaScript in a specific range?

    <!DOCTYPE html>
<html>
    <head>
            <meta charset="utf-8" />
    </head>
    <body>
        <script>
            /*

                assuming that window.crypto.getRandomValues is available
                the real range would be fron 0 to 1,998 instead of 0 to 2,000
                See javascript documentation for explanation
                https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
            */
            var array = new Uint8Array(2);
            window.crypto.getRandomValues(array);
            console.log(array[0] + array[1]);

        </script>
    </body>
</html>

Uint8Array create a array filled with a number up to 3 digits which would be a maximum of 999. This code is very short.

Pandas: convert dtype 'object' to int

Cannot comment so posting this as an answer, which is somewhat in between @piRSquared/@cyril's solution and @cs95's:

As noted by @cs95, if your data contains NaNs or Nones, converting to string type will throw an error when trying to convert to int afterwards.

However, if your data consists of (numerical) strings, using convert_dtypes will convert it to string type unless you use pd.to_numeric as suggested by @cs95 (potentially combined with df.apply()).

In the case that your data consists only of numerical strings (including NaNs or Nones but without any non-numeric "junk"), a possibly simpler alternative would be to convert first to float and then to one of the nullable-integer extension dtypes provided by pandas (already present in version 0.24) (see also this answer):

df['purchase'].astype(float).astype('Int64')

Note that there has been recent discussion on this on github (currently an -unresolved- closed issue though) and that in the case of very long 64-bit integers you may have to convert explicitly to float128 to avoid approximations during the conversions.

How do I rename a Git repository?

To rename any repository of your GitHub account:

  1. Go to that particular repository which you want to rename
  2. Navigate to the settings tab
  3. There, in the repository name section, type the new name you want to put and click Rename

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

Why you can't just use mysqlsh?

PS C:\Users\artur\Desktop> mysqlsh --user root
MySQL Shell 8.0.17

Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type '\help' or '\?' for help; '\quit' to exit.
Creating a session to 'root@localhost'
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 13 (X protocol)
Server version: 8.0.17 MySQL Community Server - GPL
No default schema selected; type \use <schema> to set one.
 MySQL  localhost:33060+ ssl  JS >

mysqlsh on windows terminal (pic)

stdcall and cdecl

Raymond Chen gives a nice overview of what __stdcall and __cdecl does.

(1) The caller "knows" to clean up the stack after calling a function because the compiler knows the calling convention of that function and generates the necessary code.

void __stdcall StdcallFunc() {}

void __cdecl CdeclFunc()
{
    // The compiler knows that StdcallFunc() uses the __stdcall
    // convention at this point, so it generates the proper binary
    // for stack cleanup.
    StdcallFunc();
}

It is possible to mismatch the calling convention, like this:

LRESULT MyWndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam);
// ...
// Compiler usually complains but there's this cast here...
windowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);

So many code samples get this wrong it's not even funny. It's supposed to be like this:

// CALLBACK is #define'd as __stdcall
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg
    WPARAM wParam, LPARAM lParam);
// ...
windowClass.lpfnWndProc = &MyWndProc;

However, assuming the programmer doesn't ignore compiler errors, the compiler will generate the code needed to clean up the stack properly since it'll know the calling conventions of the functions involved.

(2) Both ways should work. In fact, this happens quite frequently at least in code that interacts with the Windows API, because __cdecl is the default for C and C++ programs according to the Visual C++ compiler and the WinAPI functions use the __stdcall convention.

(3) There should be no real performance difference between the two.

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Java multiline string

Pluses are converted to StringBuilder.append, except when both strings are constants so the compiler can combine them at compile time. At least, that's how it is in Sun's compiler, and I would suspect most if not all other compilers would do the same.

So:

String a="Hello";
String b="Goodbye";
String c=a+b;

normally generates exactly the same code as:

String a="Hello";
String b="Goodbye":
StringBuilder temp=new StringBuilder();
temp.append(a).append(b);
String c=temp.toString();

On the other hand:

String c="Hello"+"Goodbye";

is the same as:

String c="HelloGoodbye";

That is, there's no penalty in breaking your string literals across multiple lines with plus signs for readability.

Turning off hibernate logging console output

I managed to stop by adding those 2 lines

log4j.logger.org.hibernate.orm.deprecation=error

log4j.logger.org.hibernate=error

Bellow is what my log4j.properties looks like, i just leave some commented lines explaining the log level

# Root logger option
#Level/rules TRACE < DEBUG < INFO < WARN < ERROR < FATAL.
#FATAL: shows messages at a FATAL level only
#ERROR: Shows messages classified as ERROR and FATAL
#WARNING: Shows messages classified as WARNING, ERROR, and FATAL
#INFO: Shows messages classified as INFO, WARNING, ERROR, and FATAL
#DEBUG: Shows messages classified as DEBUG, INFO, WARNING, ERROR, and FATAL
#TRACE : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL
#ALL : Shows messages classified as TRACE,DEBUG, INFO, WARNING, ERROR, and FATAL
#OFF : No log messages display


log4j.rootLogger=INFO, file, console

log4j.logger.main=DEBUG
log4j.logger.org.hibernate.orm.deprecation=error
log4j.logger.org.hibernate=error

#######################################
# Direct log messages to a log file
log4j.appender.file.Threshold=ALL
log4j.appender.file.file=logs/MyProgram.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %c{1} - %m%n

# set file size limit
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=50


#############################################
# Direct log messages to System Out
log4j.appender.console.Threshold=INFO
log4j.appender.console.Target=System.out
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss} %-5p %c{1} - %m%n

How to check if string input is a number?

I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):

This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)

a=(raw_input("Amount:"))

try:
    int(a)
except ValueError:
    try:
        float(a)
    except ValueError:
        print "This is not a number"
        a=0


if a==0:
    a=0
else:
    print a
    #Do stuff

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

There is no tracking information for the current branch

I was trying the above examples and couldn't get them to sync with a (non-master) branch I had created on a different computer. For background, I created this repository on computer A (git v 1.8) and then cloned the repository onto computer B (git 2.14). I made all my changes on comp B, but when I tried to pull the changes onto computer A I was unable to do so, getting the same above error. Similar to the above solutions, I had to do:

git branch --set-upstream-to=origin/<my_repository_name> 
git pull

slightly different but hopefully helps someone

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

Use NOT IN to find where constraints are constraining:

SELECT column FROM table WHERE column NOT IN 
(SELECT intended_foreign_key FROM another_table)

so, more specifically:

SELECT sourcecode_id FROM sourcecodes_tags WHERE sourcecode_id NOT IN 
(SELECT id FROM sourcecodes)

EDIT: IN and NOT IN operators are known to be much faster than the JOIN operators, as well as much easier to construct, and repeat.

Extracting .jar file with command line

From the docs:

To extract the files from a jar file, use x, as in:

C:\Java> jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

C:\Java> jar xf myFile.jar foo bar

The folder where jar is probably isn't C:\Java for you, on my Windows partition it's:

C:\Program Files (x86)\Java\jdk[some_version_here]\bin

Unless the location of jar is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.

EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html

How do I create an Excel chart that pulls data from multiple sheets?

2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.

Hope that will help.

How to return the current timestamp with Moment.js?

Try to use it this way:

let current_time = moment().format("HH:mm")

Parsing JSON array into java.util.List with Gson

Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:

List<String> servers = Streams.stream(jsonArray.iterator())
                              .map(je -> je.getAsString())
                              .collect(Collectors.toList());

Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.

How to extract text from a PDF?

Since today I know it: the best thing for text extraction from PDFs is TET, the text extraction toolkit. TET is part of the PDFlib.com family of products.

PDFlib.com is Thomas Merz's company. In case you don't recognize his name: Thomas Merz is the author of the "PostScript and PDF Bible".

TET's first incarnation is a library. That one can probably do everything Budda006 wanted, including positional information about every element on the page. Oh, and it can also extract images. It recombines images which are fragmented into pieces.

pdflib.com also offers another incarnation of this technology, the TET plugin for Acrobat. And the third incarnation is the PDFlib TET iFilter. This is a standalone tool for user desktops. Both these are free (as in beer) to use for private, non-commercial purposes.

And it's really powerful. Way better than Adobe's own text extraction. It extracted text for me where other tools (including Adobe's) do spit out garbage only.

I just tested the desktop standalone tool, and what they say on their webpage is true. It has a very good commandline. Some of my "problematic" PDF test files the tool handled to my full satisfaction.

This thing will from now on be my recommendation for every sophisticated and challenging PDF text extraction requirements.

TET is simply awesome. It detects tables. Inside tables, it identifies cells spanning multiple columns. It identifies table rows and contents of each table cell separately. It deals very well with hyphenations: it removes hyphens and restores complete words. It supports non-ASCII languages (including CJK, Arabic and Hebrew). When encountering ligatures, it restores the original characters...

Give it a try.

Explain ExtJS 4 event handling

One more trick for controller event listeners.

You can use wildcards to watch for an event from any component:

this.control({
   '*':{ 
       myCustomEvent: this.doSomething
   }
});

How to repair a serialized string which has been corrupted by an incorrect byte count length?

Another reason of this problem can be column type of "payload" sessions table. If you have huge data on session, a text column wouldn't be enough. You will need MEDIUMTEXT or even LONGTEXT.

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How to use placeholder as default value in select2 framework

$("#e2").select2({
   placeholder: "Select a State",
   allowClear: true
});
$("#e2_2").select2({
   placeholder: "Select a State"
});

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.

When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

https://select2.org/placeholders

How to run mvim (MacVim) from Terminal?

If you already have macVim installed: /Applications/MacVim.app/Contents/MacOS/Vim -g will give you macVim GUI.

just add an alias.

i use gvim because that is what i use on linux for gnome-vim.

alias gvim='/Applications/MacVim.app/Contents/MacOS/Vim -g'

How to add key,value pair to dictionary?

I am not sure what you mean by "dynamic". If you mean adding items to a dictionary at runtime, it is as easy as dictionary[key] = value.

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

dictionary[key] = value

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

Big one I see that causes this is filename. If you have a SPACE then any number such as 'Site 2' the file path with look like something/Site%202/index.html This is because spaces or rendered as %20, and if another number is immediately following that it will try to read it as %202. Fix is you never use spaces in your filenames.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Can I remove the URL from my print css, so the web address doesn't print?

In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).

In your code, replace <html> with <html moznomarginboxes mozdisallowselectionprint>.

In others browsers, I don't know, but you can view http://www.mintprintables.com/print-tips/header-footer-windows/

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Iterate Multi-Dimensional Array with Nested Foreach Statement

Two ways:

  1. Define the array as a jagged array, and use nested foreachs.
  2. Define the array normally, and use foreach on the entire thing.

Example of #2:

int[,] arr = { { 1, 2 }, { 3, 4 } };
foreach(int a in arr)
    Console.Write(a);

Output will be 1234. ie. exactly the same as doing i from 0 to n, and j from 0 to n.

Taskkill /f doesn't kill a process

Run CMD as Admin will fix the problem

Change Orientation of Bluestack : portrait/landscape mode

Here are the step:

  1. Install the Nova theme in bluestack
  2. go into Nova setting -> look and feel -> screen orientation -> Force Portrait -> go to Home screen

You are done! :)

How to format a number as percentage in R?

Base R

I much prefer to use sprintf which is available in base R.

sprintf("%0.1f%%", .7293827 * 100)
[1] "72.9%"

I especially like sprintf because you can also insert strings.

sprintf("People who prefer %s over %s: %0.4f%%", 
        "Coke Classic", 
        "New Coke",
        .999999 * 100)
[1] "People who prefer Coke Classic over New Coke: 99.9999%"

It's especially useful to use sprintf with things like database configurations; you just read in a yaml file, then use sprintf to populate a template without a bunch of nasty paste0's.

Longer motivating example

This pattern is especially useful for rmarkdown reports, when you have a lot of text and a lot of values to aggregate.

Setup / aggregation:

library(data.table) ## for aggregate

approval <- data.table(year = trunc(time(presidents)), 
                       pct = as.numeric(presidents) / 100,
                       president = c(rep("Truman", 32),
                                     rep("Eisenhower", 32),
                                     rep("Kennedy", 12),
                                     rep("Johnson", 20),
                                     rep("Nixon", 24)))
approval_agg <- approval[i = TRUE,
                         j = .(ave_approval = mean(pct, na.rm=T)), 
                         by = president]
approval_agg
#     president ave_approval
# 1:     Truman    0.4700000
# 2: Eisenhower    0.6484375
# 3:    Kennedy    0.7075000
# 4:    Johnson    0.5550000
# 5:      Nixon    0.4859091

Using sprintf with vectors of text and numbers, outputting to cat just for newlines.

approval_agg[, sprintf("%s approval rating: %0.1f%%",
                       president,
                       ave_approval * 100)] %>% 
  cat(., sep = "\n")
# 
# Truman approval rating: 47.0%
# Eisenhower approval rating: 64.8%
# Kennedy approval rating: 70.8%
# Johnson approval rating: 55.5%
# Nixon approval rating: 48.6%

Finally, for my own selfish reference, since we're talking about formatting, this is how I do commas with base R:

30298.78 %>% round %>% prettyNum(big.mark = ",")
[1] "30,299"

Reshape an array in NumPy

There are two possible result rearrangements (following example by @eumiro). Einops package provides a powerful notation to describe such operations non-ambigously

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])

RegEx: Grabbing values between quotation marks

echo 'junk "Foo Bar" not empty one "" this "but this" and this neither' | sed 's/[^\"]*\"\([^\"]*\)\"[^\"]*/>\1</g'

This will result in: >Foo Bar<><>but this<

Here I showed the result string between ><'s for clarity, also using the non-greedy version with this sed command we first throw out the junk before and after that ""'s and then replace this with the part between the ""'s and surround this by ><'s.

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

mysqldump data only

This should work:

# To export to file (data only)
mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql

# To export to file (structure only)
mysqldump -u [user] -p[pass] --no-data mydb > mydb.sql

# To import to database
mysql -u [user] -p[pass] mydb < mydb.sql

NOTE: there's no space between -p & [pass]

How to list the certificates stored in a PKCS12 keystore with keytool?

You can also use openssl to accomplish the same thing:

$ openssl pkcs12 -nokeys -info \
    -in </path/to/file.pfx> \
    -passin pass:<pfx's password>

MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
    localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
    friendlyName: jedis-server
subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1
issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE-----
...
...
...
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048

How can I display a pdf document into a Webview?

This is the actual usage limit that google allows before you get the error mentioned in the comments, if it's a once in a lifetime pdf that the user will open in app then i feel its completely safe. Although it is advised to to follow the the native approach using the built in framework in Android from Android 5.0 / Lollipop, it's called PDFRenderer.

Convert Swift string to array

    let string = "hell0"
    let ar = Array(string.characters)
    print(ar)

Error in Python script "Expected 2D array, got 1D array instead:"?

I was facing the same issue earlier but I have somehow found the solution, You can try reg.predict([[3300]]).

The API used to allow scalar value but now you need to give a 2D array.

How to uninstall/upgrade Angular CLI?

None of the above solutions alone worked for me. On Windows 7 this worked:

Install Rapid Environment Editor and remove any entries for node, npm, angular-cli or @angular/cli

Uninstall node.js and reinstall. Run Rapid Environment Editor again and make sure node.js and npm are in your System or User path. Uninstall any existing ng versions with:

npm uninstall -g angular-cli

npm uninstall -g @angular/cli

npm cache clean

Delete the C:\Users\YOU\AppData\Roaming\npm\node_modules\@angular folder.

Reboot, then, finally, run:

npm install -g @angular/cli

Then hold your breath and run ng -v. If you're lucky, you'll get some love. Hold your breath henceforward every time you run the ng command, because 'command not found' has magically reappeared for me several times after ng was running fine and I thought the problem was solved.

Why does NULL = NULL evaluate to false in SQL server

MSDN has a nice descriptive article on nulls and the three state logic that they engender.

In short, the SQL92 spec defines NULL as unknown, and NULL used in the following operators causes unexpected results for the uninitiated:

= operator NULL   true   false 
NULL       NULL   NULL   NULL
true       NULL   true   false
false      NULL   false  true

and op     NULL   true   false 
NULL       NULL   NULL   false
true       NULL   true   false
false      false  false  false

or op      NULL   true   false 
NULL       NULL   true   NULL
true       true   true   true
false      NULL   true   false

Generating a PNG with matplotlib when DISPLAY is undefined

One other thing to check is whether your current user is authorised to connect to the X display. In my case, root was not allowed to do that and matplotlib was complaining with the same error.

user@debian:~$ xauth list         
debian/unix:10  MIT-MAGIC-COOKIE-1  ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xauth add debian/unix:10  MIT-MAGIC-COOKIE-1 ae921efd0026c6fc9d62a8963acdcca0
root@debian:~# xterm

source: http://www.debian-administration.org/articles/494 https://debian-administration.org/article/494/Getting_X11_forwarding_through_ssh_working_after_running_su

How to import RecyclerView for Android L-preview

implementation 'com.android.support:appcompat-v7:28.0.0'

implementation 'com.android.support:recyclerview-v7:28.0.0'

Above works for me in build.gradle file

Xcode Objective-C | iOS: delay function / NSTimer help?

Try

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

Difference between RUN and CMD in a Dockerfile

Note: Don’t confuse RUN with CMD. RUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.

from docker file reference

https://docs.docker.com/engine/reference/builder/#cmd

Python: maximum recursion depth exceeded while calling a Python object

Instead of doing recursion, the parts of the code with checkNextID(ID + 18) and similar could be replaced with ID+=18, and then if you remove all instances of return 0, then it should do the same thing but as a simple loop. You should then put a return 0 at the end and make your variables non-global.

How can I run a PHP script inside a HTML file?

To execute 'php' code inside 'html' or 'htm', for 'apache version 2.4.23'

Go to '/etc/apache2/mods-enabled' edit '@mime.conf'

Go to end of file and add the following line:

 "AddType application/x-httpd-php .html .htm"

BEFORE tag '< /ifModules >' verified and tested with 'apache 2.4.23' and 'php 5.6.17-1' under 'debian'

twitter bootstrap 3.0 typeahead ajax example

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);
            });
        }
    });
})
</script>

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

Array.push() if does not exist?

It is quite easy to do using the Array.findIndex function, which takes a function as an argument:

var arrayObj = [{name:"bull", text: "sour"},
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob"); 
// here you can check specific property for an object whether it exist in your array or not

index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
 

How to go up a level in the src path of a URL in HTML?

Supposing you have the following file structure:

-css
  --index.css
-images
  --image1.png
  --image2.png
  --image3.png

In CSS you can access image1, for example, using the line ../images/image1.png.

NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.

Why do we need C Unions?

Use a union when you have some function where you return a value that can be different depending on what the function did.

Markdown `native` text alignment

It's hacky but if you're using GFM or some other MD syntax which supports building tables with pipes you can use the column alignment features:

|| <!-- empty table header -->
|:--:| <!-- table header/body separator with center formatting -->
| I'm centered! | <!-- cell gets column's alignment -->

This works in marked.

How can I get a list of Git branches, ordered by most recent commit?

My best result as a script:

git for-each-ref --sort=-committerdate refs/heads/ --format='%(refname:short)|%(committerdate:iso)|%(authorname)' |
    sed 's/refs\/heads\///g' |
    grep -v BACKUP  | 
    while IFS='|' read branch date author
    do 
        printf '%-15s %-30s %s\n' "$branch" "$date" "$author"
    done

How to declare a global variable in C++

Not sure if this is correct in any sense but this seems to work for me.

someHeader.h
inline int someVar;

I don't have linking/multiple definition issues and it "just works"... ;- )

It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )

Java - get pixel array from image

Mota's answer is great unless your BufferedImage came from a Monochrome Bitmap. A Monochrome Bitmap has only 2 possible values for its pixels (for example 0 = black and 1 = white). When a Monochrome Bitmap is used then the

final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

call returns the raw Pixel Array data in such a fashion that each byte contains more than one pixel.

So when you use a Monochrome Bitmap image to create your BufferedImage object then this is the algorithm you want to use:

/**
 * This returns a true bitmap where each element in the grid is either a 0
 * or a 1. A 1 means the pixel is white and a 0 means the pixel is black.
 * 
 * If the incoming image doesn't have any pixels in it then this method
 * returns null;
 * 
 * @param image
 * @return
 */
public static int[][] convertToArray(BufferedImage image)
{

    if (image == null || image.getWidth() == 0 || image.getHeight() == 0)
        return null;

    // This returns bytes of data starting from the top left of the bitmap
    // image and goes down.
    // Top to bottom. Left to right.
    final byte[] pixels = ((DataBufferByte) image.getRaster()
            .getDataBuffer()).getData();

    final int width = image.getWidth();
    final int height = image.getHeight();

    int[][] result = new int[height][width];

    boolean done = false;
    boolean alreadyWentToNextByte = false;
    int byteIndex = 0;
    int row = 0;
    int col = 0;
    int numBits = 0;
    byte currentByte = pixels[byteIndex];
    while (!done)
    {
        alreadyWentToNextByte = false;

        result[row][col] = (currentByte & 0x80) >> 7;
        currentByte = (byte) (((int) currentByte) << 1);
        numBits++;

        if ((row == height - 1) && (col == width - 1))
        {
            done = true;
        }
        else
        {
            col++;

            if (numBits == 8)
            {
                currentByte = pixels[++byteIndex];
                numBits = 0;
                alreadyWentToNextByte = true;
            }

            if (col == width)
            {
                row++;
                col = 0;

                if (!alreadyWentToNextByte)
                {
                    currentByte = pixels[++byteIndex];
                    numBits = 0;
                }
            }
        }
    }

    return result;
}

Access denied for root user in MySQL command-line

By default there is no password is set for root user in XAMPP.

You can set password for root user of MySQL.

Navigate to

localhost:80/security/index.php

and set password for root user.

Note:Please change the port number in above url if your Apache in on different port.

Open XAMPP control panel Click "Shell" button

Command prompt window will open now in that window type

mysql -u root -p;

It will ask for password type the password which you have set for root user.

There you go ur logged in as root user :D Now do what u want to do :P

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

ExecutorService that interrupts tasks after a timeout

You can use a ScheduledExecutorService for this. First you would submit it only once to begin immediately and retain the future that is created. After that you can submit a new task that would cancel the retained future after some period of time.

 ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
 final Future handler = executor.submit(new Callable(){ ... });
 executor.schedule(new Runnable(){
     public void run(){
         handler.cancel();
     }      
 }, 10000, TimeUnit.MILLISECONDS);

This will execute your handler (main functionality to be interrupted) for 10 seconds, then will cancel (i.e. interrupt) that specific task.

Drop multiple tables in one shot in MySQL

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

Select top 2 rows in Hive

Here I think it's worth mentioning SORT BY and ORDER BY both clauses and why they different,

SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2

If you are using SORT BY clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY clause will result in ordered data for the final Reduce task. To understand more please refer to this link.

SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2

Note: Finally, Even though the accepted answer contains SORT BY clause, I mostly prefer to use ORDER BY clause for the general use case to avoid any data loss.

Windows batch script to unhide files hidden by virus

echo "Enter Drive letter" 
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*

How to do jquery code AFTER page loading?

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
    // Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure

open program minimized via command prompt

You could try using the third-party tool called NirCmd. It is a genuine, free command line utility. If or when you have it, use this code in a batch file:

title Open Word
nircmd win hide title "Open Word"
start "C:\Program" "Files" "(x86)\Microsoft" "Office\Office12\WINWORD.exe
nircmd wait 20
nircmd win min foreground
exit

This program, in order, changes its title, hides itself according to its title, starts Word, waits 20 milliseconds as a buffer for Word to settle, minimizes Word by assuming it is now the top window, and then exits itself. This program should work as intended as long as their are no key presses or clicks in that ~50 millisecond time window, which shouldn't be hard.

As for installing nircmd on your computer, use this link, and click "Download NirCmd" at the bottom of the page. Save the .zip folder to a normal directory (like "My Documents"), extract it, and copy "nircmd.exe" to %systemroot%\system32, and there you go. Now you have nircmd included with your command line utilities.

Textarea onchange detection

I know this question was specific to JavaScript, however, there seems to be no good, clean way to ALWAYS detect when a textarea changes in all current browsers. I've learned jquery has taken care of it for us. It even handles contextual menu changes to text areas. The same syntax is used regardless of input type.

    $('div.lawyerList').on('change','textarea',function(){
      // Change occurred so count chars...
    });

or

    $('textarea').on('change',function(){
      // Change occurred so count chars...
    });

Which selector do I need to select an option by its text?

Use following

$('#select option:contains(ABC)').val();

Windows batch script launch program and exit console

Use start notepad.exe.

More info with start /?.

Oracle Differences between NVL and Coalesce

There is also difference is in plan handling.

Oracle is able form an optimized plan with concatenation of branch filters when search contains comparison of nvl result with an indexed column.

create table tt(a, b) as
select level, mod(level,10)
from dual
connect by level<=1e4;

alter table tt add constraint ix_tt_a primary key(a);
create index ix_tt_b on tt(b);

explain plan for
select * from tt
where a=nvl(:1,a)
  and b=:2;

explain plan for
select * from tt
where a=coalesce(:1,a)
  and b=:2;

nvl:

-----------------------------------------------------------------------------------------
| Id  | Operation                     | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |         |     2 |    52 |     2   (0)| 00:00:01 |
|   1 |  CONCATENATION                |         |       |       |            |          |
|*  2 |   FILTER                      |         |       |       |            |          |
|*  3 |    TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | IX_TT_B |     7 |       |     1   (0)| 00:00:01 |
|*  5 |   FILTER                      |         |       |       |            |          |
|*  6 |    TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  7 |     INDEX UNIQUE SCAN         | IX_TT_A |     1 |       |     1   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   2 - filter(:1 IS NULL)
   3 - filter("A" IS NOT NULL)
   4 - access("B"=TO_NUMBER(:2))
   5 - filter(:1 IS NOT NULL)
   6 - filter("B"=TO_NUMBER(:2))
   7 - access("A"=:1)

coalesce:

---------------------------------------------------------------------------------------
| Id  | Operation                   | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |         |     1 |    26 |     1   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS BY INDEX ROWID| TT      |     1 |    26 |     1   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | IX_TT_B |    40 |       |     1   (0)| 00:00:01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("A"=COALESCE(:1,"A"))
   2 - access("B"=TO_NUMBER(:2))

Credits go to http://www.xt-r.com/2012/03/nvl-coalesce-concatenation.html.

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

How to update cursor limit for ORA-01000: maximum open cursors exceed

RUn the following query to find if you are running spfile or not:

SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type" 
       FROM sys.v_$parameter WHERE name = 'spfile';

If the result is "SPFILE", then use the following command:

alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor

if the result is "PFILE", then use the following command:

alter system set open_cursors = 1000 ;

You can read about SPFILE vs PFILE here,

http://www.orafaq.com/node/5

How to move an element into another element?

You can use following code to move source to destination

 jQuery("#source")
       .detach()
       .appendTo('#destination');

try working codepen

_x000D_
_x000D_
function move() {_x000D_
 jQuery("#source")_x000D_
   .detach()_x000D_
   .appendTo('#destination');_x000D_
}
_x000D_
#source{_x000D_
  background-color:red;_x000D_
  color: #ffffff;_x000D_
  display:inline-block;_x000D_
  padding:35px;_x000D_
}_x000D_
#destination{_x000D_
  background-color:blue;_x000D_
  color: #ffffff;_x000D_
  display:inline-block;_x000D_
  padding:50px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="source">_x000D_
I am source_x000D_
</div>_x000D_
_x000D_
<div id="destination">_x000D_
I am destination_x000D_
</div>_x000D_
_x000D_
<button onclick="move();">Move</button>
_x000D_
_x000D_
_x000D_

Allow only numbers and dot in script

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 46 || charCode > 57)) {
        return false;
    }
    return true;
}

you should use this function and write the properties of this element ;

HTML Code:

<input id="deneme" data-mini="true" onKeyPress="return isNumber(event)" type="text"/>`

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

Manually creating a folder named 'npm' in the displayed path fixed the problem.

More information can be found on Troubleshooting page

Difference between PCDATA and CDATA in DTD

The very main difference between PCDATA and CDATA is

PCDATA - Basically used for ELEMENTS while

CDATA - Used for Attributes of XML i.e ATTLIST

Check if specific input file is empty

Method 1

if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}

Method 2

if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}

Statistics: combinations in Python

Why not write it yourself? It's a one-liner or such:

from operator import mul    # or mul=lambda x,y:x*y
from fractions import Fraction

def nCk(n,k): 
  return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )

Test - printing Pascal's triangle:

>>> for n in range(17):
...     print ' '.join('%5d'%nCk(n,k) for k in range(n+1)).center(100)
...     
                                                   1                                                
                                                1     1                                             
                                             1     2     1                                          
                                          1     3     3     1                                       
                                       1     4     6     4     1                                    
                                    1     5    10    10     5     1                                 
                                 1     6    15    20    15     6     1                              
                              1     7    21    35    35    21     7     1                           
                           1     8    28    56    70    56    28     8     1                        
                        1     9    36    84   126   126    84    36     9     1                     
                     1    10    45   120   210   252   210   120    45    10     1                  
                  1    11    55   165   330   462   462   330   165    55    11     1               
               1    12    66   220   495   792   924   792   495   220    66    12     1            
            1    13    78   286   715  1287  1716  1716  1287   715   286    78    13     1         
         1    14    91   364  1001  2002  3003  3432  3003  2002  1001   364    91    14     1      
      1    15   105   455  1365  3003  5005  6435  6435  5005  3003  1365   455   105    15     1   
    1    16   120   560  1820  4368  8008 11440 12870 11440  8008  4368  1820   560   120    16     1
>>> 

PS. edited to replace int(round(reduce(mul, (float(n-i)/(i+1) for i in range(k)), 1))) with int(reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1)) so it won't err for big N/K

Better way to find index of item in ArrayList?

ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index

int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
    Log.e(TAG, "Object not found in List");
} else {
    Log.i(TAG, "" + position);
}

Output: List Index : 7

If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.

Done

Format Float to n decimal places

Here's a quick sample using the DecimalFormat class mentioned by Nick.

float f = 12.345f;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));

The output of the print statement will be 12.35. Notice that it will round it for you.

Is floating point math broken?

A lot of good answers have been posted, but I'd like to append one more.

Not all numbers can be represented via floats/doubles For example, the number "0.2" will be represented as "0.200000003" in single precision in IEEE754 float point standard.

Model for store real numbers under the hood represent float numbers as

enter image description here

Even though you can type 0.2 easily, FLT_RADIX and DBL_RADIX is 2; not 10 for a computer with FPU which uses "IEEE Standard for Binary Floating-Point Arithmetic (ISO/IEEE Std 754-1985)".

So it is a bit hard to represent such numbers exactly. Even if you specify this variable explicitly without any intermediate calculation.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

You can also use named arguments which are optional and can be given in any order.

Set namedArguments = WScript.Arguments.Named

Here's a little helper function:

Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
  If WScript.Arguments.Named.Exists(argumentName) Then
    GetNamedArgument = WScript.Arguments.Named.Item(argumentName) 
  Else  
    GetNamedArgument = defaultValue
  End If
End Function

Example VBS:

'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg

Example Usage:

test.vbs /testArg:123

Get a specific bit from byte

[Flags]
enum Relays : byte
{
    relay0 = 1 << 0,
    relay1 = 1 << 1,
    relay2 = 1 << 2,
    relay3 = 1 << 3,
    relay4 = 1 << 4,
    relay5 = 1 << 5,
    relay6 = 1 << 6,
    relay7 = 1 << 7
}

public static bool GetRelay(byte b, Relays relay)
{
    return (Relays)b.HasFlag(relay);
}

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

As mentioned here (in French), this can happen when you have two versions of R installed on your computer. Uninstall the oldest one, then try your package installation again! It worked fine for me.

Difference between 'struct' and 'typedef struct' in C++?

Struct is to create a data type. The typedef is to set a nickname for a data type.

Remove ALL white spaces from text

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s instead:

.replace(/\s/g,'')

You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:

.replaceAll(/\s/g,'')

Using GitLab token to clone without authentication

As of 8.12, cloning using HTTPS + runner token is not supported anymore, as mentioned here:

In 8.12 we improved build permissions. Being able to clone project using runners token it is no supported from now on (it was actually working by coincidence and was never a fully fledged feature, so we changed that in 8.12). You should use build token instead.

This is widely documented here - https://docs.gitlab.com/ce/user/project/new_ci_build_permissions_model.html.

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

How to set a default Value of a UIPickerView

I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

The name 'ViewBag' does not exist in the current context

I had this problem after changing the Application's Default namespace in the Properties dialog.

The ./Views/Web.Config contained a reference to the old namespace

how to have two headings on the same line in html

Display property 'inline-block' will place both headers next to each other. You can run this code snippet to see it

_x000D_
_x000D_
<h1 style="display: inline-block" >Text 1</h1>
<h1 style="display: inline-block" >Text 2</h1>
_x000D_
_x000D_
_x000D_

enumerate() for dictionary in python

enumerate() when working on list actually gives the index and the value of the items inside the list. For example:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
    print(i, j)

gives

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

where the first column denotes the index of the item and 2nd column denotes the items itself.

In a dictionary

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
    print(i, j)

it gives the output

0 0
1 1
2 2
3 4
4 5
5 6
6 7

where the first column gives the index of the key:value pairs and the second column denotes the keys of the dictionary enumm.

So if you want the first column to be the keys and second columns as values, better try out dict.iteritems()(Python 2) or dict.items() (Python 3)

for i, j in enumm.items():
    print(i, j)

output

0 1
1 2
2 3
4 4
5 5
6 6
7 7

Voila

Can't bind to 'ngIf' since it isn't a known property of 'div'

Instead of [ngIf] you should use *ngIf like this:

<div *ngIf="isAuth" id="sidebar">

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

TL;DR $PATH fix

  1. Use pip install --user package_name to install a package that should include CLI executables.
  2. Launch a python shell and import package_name
  3. Find where lib/python/... occurs in the output and replace it all with bin
  4. It's likely to be $HOME/Library/Python/2.7/bin

Details

Because of the new System Integrity Protection in macOS 10.11 El Capitan, you can no longer sudo pip install. We won't debate the merits of that here.

Another answer explains that you should pip install --user which is correct. But they sent you to the back alleys to figure out what to do about your $PATH so that you could get access to installed executables. Luckily, I've already solved a similar need for an unrelated question.

Here is a transcript of how I solved the problem on one of my systems. I'm including it all rather just than the $PATH that worked for me, because your system may be different from mine. This process should work for everybody.

$ pip install --user jp
Collecting jp
  Downloading jp-0.2.4.tar.gz
Installing collected packages: jp
  Running setup.py install for jp ... done
Successfully installed jp-0.2.4

$ python -c 'import jp; print jp'
<module 'jp' from '/Users/bbronosky/Library/Python/2.7/lib/python/site-packages/jp/__init__.pyc'>

$ find /Users/bbronosky/Library/Python -type f -perm -100
/Users/bbronosky/Library/Python/2.7/bin/jp

$ which jp

$ echo -e '\n''export PATH=$HOME/Library/Python/2.7/bin:$PATH' >> ~/.bashrc

$ bash # starting a new bash process for demo, but you should open a new terminal

$ which jp
/Users/bbronosky/Library/Python/2.7/bin/jp

$ jp
usage: jp <expression> <filepath>

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

Access a JavaScript variable from PHP

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

macro for Hide rows in excel 2010

You almost got it. You are hiding the rows within the active sheet. which is okay. But a better way would be add where it is.

Rows("52:55").EntireRow.Hidden = False

becomes

activesheet.Rows("52:55").EntireRow.Hidden = False

i've had weird things happen without it. As for making it automatic. You need to use the worksheet_change event within the sheet's macro in the VBA editor (not modules, double click the sheet1 to the far left of the editor.) Within that sheet, use the drop down menu just above the editor itself (there should be 2 listboxes). The listbox to the left will have the events you are looking for. After that just throw in the macro. It should look like the below code,

Private Sub Worksheet_Change(ByVal Target As Range)
test1
end Sub

That's it. Anytime you change something, it will run the macro test1.

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

Below steps helped me fix this.

  • upgrade pip version
  • remove the created environment by using command rm -rf env-name
  • create environment using command python3 -m venv env-aide
  • now install the package and check

How to create a Date in SQL Server given the Day, Month and Year as Integers

Old Microsoft Sql Sever (< 2012)

RETURN dateadd(month, 12 * @year + @month - 22801, @day - 1)  

Running conda with proxy

I was able to get it working without putting in the username and password:

conda config --set proxy_servers.https https://address:port

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

Error: Configuration with name 'default' not found in Android Studio

Try:

git submodule init
git submodule update

How to remove all elements in String array in java?

Usually someone uses collections if something frequently changes.

E.g.

    List<String> someList = new ArrayList<String>();
    // initialize list
    someList.add("Mango");
    someList.add("....");
    // remove all elements
    someList.clear();
    // empty list

An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.

Copying data from one SQLite database to another

You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.

INSERT INTO X.TABLE SELECT * FROM Y.TABLE;

Or, if the columns are not matched up in order:

INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;

jQuery to serialize only elements within a div

No problem. Just use the following. This will behave exactly like serializing a form but using a div's content instead.

$('#divId :input').serialize();

Check https://jsbin.com/xabureladi/1 for a demonstration (https://jsbin.com/xabureladi/1/edit for the code)

Storing image in database directly or as base64 data?

I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).

Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.

Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).

While base64 is fine for transport, do not store your images base64 encoded.

Base64 provides no checksum or anything of any value for storage.

Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It's generally faster to read less bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you're regularly outputting the image in base64, then consider storing in base64.

Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves--you're sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).

If you still wish to store images base64 encoded, please, whatever you do, make sure you don't store base64 encoded data in a UTF8 column then index it.

How do I convert NSMutableArray to NSArray?

In objective-c :

NSArray *myArray = [myMutableArray copy];

In swift :

 var arr = myMutableArray as NSArray

Efficient way to do batch INSERTS with JDBC

How about using the INSERT ALL statement ?

INSERT ALL

INTO table_name VALUES ()

INTO table_name VALUES ()

...

SELECT Statement;

I remember that the last select statement is mandatory in order to make this request succeed. Don't remember why though. You might consider using PreparedStatement instead as well. lots of advantages !

Farid

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

How to use a variable inside a regular expression?

From python 3.6 on you can also use Literal String Interpolation, "f-strings". In your particular case the solution would be:

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
    ...do something

EDIT:

Since there have been some questions in the comment on how to deal with special characters I'd like to extend my answer:

raw strings ('r'):

One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:

In short:

Let's say instead of finding a word boundary \b after TEXTO you want to match the string \boundary. The you have to write:

TEXTO = "Var"
subject = r"Var\boundary"

if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
    print("match")

This only works because we are using a raw-string (the regex is preceded by 'r'), otherwise we must write "\\\\boundary" in the regex (four backslashes). Additionally, without '\r', \b' would not converted to a word boundary anymore but to a backspace!

re.escape:

Basically puts a backspace in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

NOTE: For any version >= python 3.7: !, ", %, ', ,, /, :, ;, <, =, >, @, and ` are not escaped. Only special characters with meaning in a regex are still escaped. _ is not escaped since Python 3.3.(s. here)

Curly braces:

If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let's say you want to match TEXTO followed by exactly 2 digits:

if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
    print("match")

MongoDB SELECT COUNT GROUP BY

I need some extra operation based on the result of aggregate function. Finally I've found some solution for aggregate function and the operation based on the result in MongoDB. I've a collection Request with field request, source, status, requestDate.

Single Field Group By & Count:

db.Request.aggregate([
    {"$group" : {_id:"$source", count:{$sum:1}}}
])

Multiple Fields Group By & Count:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}}
])

Multiple Fields Group By & Count with Sort using Field:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
    {$sort:{"_id.source":1}}
])

Multiple Fields Group By & Count with Sort using Count:

db.Request.aggregate([
    {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
    {$sort:{"count":-1}}
])

Replace one character with another in Bash

Use parameter substitution:

string=${string// /.}

NSString with \n or line break

\n\r seems working for me.

I am using Xcode 4.6 with IOS 6.0 as target. Tested on iPhone 4S. Try it by yourself.

Feng Chiu

React-Redux: Actions must be plain objects. Use custom middleware for async actions

You can't use fetch in actions without middleware. Actions must be plain objects. You can use a middleware like redux-thunk or redux-saga to do fetch and then dispatch another action.

Here is an example of async action using redux-thunk middleware.

export function checkUserLoggedIn (authCode) {
 let url = `${loginUrl}validate?auth_code=${authCode}`;
  return dispatch => {
    return fetch(url,{
      method: 'GET',
      headers: {
        "Content-Type": "application/json"
      }
      }
    )
      .then((resp) => {
        let json = resp.json();
       if (resp.status >= 200 && resp.status < 300) {
          return json;
        } else {
          return json.then(Promise.reject.bind(Promise));
        }
      })
      .then(
        json => {
          if (json.result && (json.result.status === 'error')) {
            dispatch(errorOccurred(json.result));
            dispatch(logOut());
          }
          else{
            dispatch(verified(json.result));
          }
        }
      )
      .catch((error) => {
        dispatch(warningOccurred(error, url));
      })
  }
}

Android get current Locale, not default

From getDefault's documentation:

Returns the user's preferred locale. This may have been overridden for this process with setDefault(Locale).

Also from the Locale docs:

The default locale is appropriate for tasks that involve presenting data to the user.

Seems like you should just use it.

In laymans terms, what does 'static' mean in Java?

Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.

Convert Json Array to normal Java list

You can use a String[] instead of an ArrayList<String>:

Hope it helps!

   private String[] getStringArray(JSONArray jsonArray) throws JSONException {
            if (jsonArray != null) {
                String[] stringsArray = new String[jsonArray.length()];
                for (int i = 0; i < jsonArray.length(); i++) {
                    stringsArray[i] = jsonArray.getString(i);
                }
                return stringsArray;
            } else
                return null;
        }

Create a date time with month and day only, no year

Anyway you need 'Year'.

In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.

You can create a custom combobox using this: Customizable ComboBox Drop-Down.

1- In VS create a user control.

2- See the code in the link above for impelemnting that control.

3- Create another user control and place in it 31 button or label and above them place a label to show months.

4- Place the control in step 3 in your custom combobox.

5- Place the control in setp 4 in step 1.

You now have a control with only days and months. You can use any year that you have in your database or ....

How to deep copy a list?

E0_copy is not a deep copy. You don't make a deep copy using list() (Both list(...) and testList[:] are shallow copies).

You use copy.deepcopy(...) for deep copying a list.

deepcopy(x, memo=None, _nil=[])
    Deep copy operation on arbitrary Python objects.

See the following snippet -

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b   # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]

Now see the deepcopy operation

>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b    # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

It means that one of the dependent dlls is compiled with a different run-time library.

Project -> Properties -> C/C++ -> Code Generation -> Runtime Library

Go over all the libraries and see that they are compiled in the same way.

More about this error in this link:

warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>

How to yum install Node.JS on Amazon Linux

For the v4 LTS version use:

curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -
yum -y install nodejs

For the Node.js v6 use:

curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -
yum -y install nodejs

I also ran into some problems when trying to install native addons on Amazon Linux. If you want to do this you should also install build tools:

yum install gcc-c++ make

Convert timestamp to date in MySQL query

To just get a date you can cast it

cast(user.registration as date)

and to get a specific format use date_format

date_format(registration, '%Y-%m-%d')

SQLFiddle demo

How to check syslog in Bash on Linux?

If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.

vi +'syntax on' /var/log/syslog

How to set dialog to show in full screen?

dialog = new Dialog(getActivity(),android.R.style.Theme_Translucent_NoTitleBar);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.loading_screen);
    Window window = dialog.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();

    wlp.gravity = Gravity.CENTER;
    wlp.flags &= ~WindowManager.LayoutParams.FLAG_BLUR_BEHIND;
    window.setAttributes(wlp);
    dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    dialog.show();

try this.

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Ruby objects and JSON serialization (without Rails)

If you're using 1.9.2 or above, you can convert hashes and arrays to nested JSON objects just using to_json.

{a: [1,2,3], b: 4}.to_json

In Rails, you can call to_json on Active Record objects. You can pass :include and :only parameters to control the output:

@user.to_json only: [:name, :email]

You can also call to_json on AR relations, like so:

User.order("id DESC").limit(10).to_json

You don't need to import anything and it all works exactly as you'd hope.

How can I convert a string to upper- or lower-case with XSLT?

<xsl:variable name="upper">UPPER CASE</xsl:variable>
<xsl:variable name="lower" select="translate($upper,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')"/>
<xsl:value-of select ="$lower"/>

//displays UPPER CASE as upper case

How to permanently add a private key with ssh-add on Ubuntu?

This worked for me.

ssh-agent /bin/sh
ssh-add /path/to/your/key

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

Because of old version I got this error. Then I changed to this version n error gone Using maven my pom.xml

<properties>  
    ...
    <jackson.version>2.5.2</jackson.version>
</properties>

<dependencies>
...
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
</dependencies>

my old version was '2.2.3'

Swift - Remove " character from string

If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:

if let value = text {
    print(value)
}

Now you've got the value without the "Optional" string that Swift adds when the value is not unwrapped before.

How to serialize Object to JSON?

Easy way to do it without annotations is to use Gson library

Simple as that:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

Rails Active Record find(:all, :order => ) issue

Could be two things. First,

This code is deprecated:

Model.find(:all, :order => ...)

should be:

Model.order(...).all

Find is no longer supported with the :all, :order, and many other options.

Second, you might have had a default_scope that was enforcing some ordering before you called find on Show.

Hours of digging around on the internet led me to a few useful articles that explain the issue:

How to determine the Boost version on a system?

As to me, you can first(find version.hpp the version variable is in it, if you know where it is(in ubuntu it usually in /usr/include/boost/version.hpp by default install)):

 locate `boost/version.hpp`

Second show it's version by:

 grep BOOST_LIB_VERSION /usr/include/boost/version.hpp

or

  grep BOOST_VERSION /usr/include/boost/version.hpp.

As to me, I have two version boost installed in my system. Output as below:

xy@xy:~$ locate boost/version.hpp |grep boost

/home/xy/boost_install/boost_1_61_0/boost/version.hpp
/home/xy/boost_install/lib/include/boost/version.hpp
/usr/include/boost/version.hpp

xy@xy:~$ grep BOOST_VERSION /usr/include/boost/version.hpp
#ifndef BOOST_VERSION_HPP
#define BOOST_VERSION_HPP
//  BOOST_VERSION % 100 is the patch level
//  BOOST_VERSION / 100 % 1000 is the minor version
//  BOOST_VERSION / 100000 is the major version
#define BOOST_VERSION 105800
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION

# or this way more readable
xy@xy:~$ grep BOOST_LIB_VERSION /usr/include/boost/version.hpp
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_58"

Show local installed version:

xy@xy:~$ grep BOOST_LIB_VERSION /home/xy/boost_install/lib/include/boost/version.hpp
//  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
#define BOOST_LIB_VERSION "1_61"

Change Title of Javascript Alert

You can't, this is determined by the browser, for the user's safety and security. For example you can't make it say "Virus detected" with a message of "Would you like to quarantine it now?"...at least not as an alert().

There are plenty of JavaScript Modal Dialogs out there though, that are far more customizable than alert().

Error: Cannot find module 'gulp-sass'

Just do npm update and then npm install gulp-sass --save-dev in your root folder, and then when you run you shouldn't have any issues.

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

How to set an HTTP proxy in Python 2.7?

cd C:\Python34\Scripts

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

pip.exe install PackageName

How do I handle newlines in JSON?

You could just escape your string on the server when writing the value of the JSON field and unescape it when retrieving the value in the client browser, for instance.

The JavaScript implementation of all major browsers have the unescape command.

Example:

On the server:

response.write "{""field1"":""" & escape(RS_Temp("textField")) & """}"

In the browser:

document.getElementById("text1").value = unescape(jsonObject.field1)

Child with max-height: 100% overflows parent

A good solution is to not use height on the parent and use it just on the child with View Port :

Fiddle Example: https://jsfiddle.net/voan3v13/1/

body, html {
  width: 100%;
  height: 100%;
}
.parent {
  width: 400px;
  background: green;
}

.child {
  max-height: 40vh;
  background: blue;
  overflow-y: scroll;
}

Why do I get permission denied when I try use "make" to install something?

Execute chmod 777 -R scripts/, it worked fine for me ;)

Using Custom Domains With IIS Express

David's solution is good. But I found the <script>alert(document.domain);</script> in the page still alerts "localhost" because the Project Url is still localhost even if it has been override with http://dev.example.com. Another issue I run into is that it alerts me the port 80 has already been in use even if I have disabled the Skype using the 80 port number as recommended by David Murdoch. So I have figured out another solution that is much easier:

  1. Run Notepad as administrator, and open the C:\Windows\System32\drivers\etc\hosts, add 127.0.0.1 mydomain, and save the file;
  2. Open the web project with Visual Studio 2013 (Note: must also run as administrator), right-click the project -> Properties -> Web, (lets suppose the Project Url under the "IIS Express" option is http://localhost:33333/), then change it from http://localhost:33333/ to http://mydomain:333333/ Note: After this change, you should neither click the "Create Virtual Directory" button on the right of the Project Url box nor click the Save button of the Visual Studio as they won't be succeeded. You can save your settings after next step 3.
  3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config, search for "33333:localhost", then update it to "33333:mydomain" and save the file.
  4. Save your setting as mentioned in step 2.
  5. Right click a web page in your visual studio, and click "View in Browser". Now the page will be opened under http://mydomain:333333/, and <script>alert(document.domain);</script> in the page will alert "mydomain".

Note: The port number listed above is assumed to be 33333. You need to change it to the port number set by your visual studio.

Post edited: Today I tried with another domain name and got the following error: Unable to launch the IIS Express Web server. Failed to register URL... Access is denied. (0x80070005). I exit the IIS Express by right clicking the IIS Express icon at the right corner in the Windows task bar, and then re-start my visual studio as administrator, and the issue is gone.

Parallel foreach with asynchronous lambda

I've created an extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism

    /// <summary>
    /// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
    /// </summary>
    /// <typeparam name="T">Type of IEnumerable</typeparam>
    /// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
    /// <param name="action">an async <see cref="Action" /> to execute</param>
    /// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
    /// Must be grater than 0</param>
    /// <returns>A Task representing an async operation</returns>
    /// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
    public static async Task ForEachAsyncConcurrent<T>(
        this IEnumerable<T> enumerable,
        Func<T, Task> action,
        int? maxDegreeOfParallelism = null)
    {
        if (maxDegreeOfParallelism.HasValue)
        {
            using (var semaphoreSlim = new SemaphoreSlim(
                maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
            {
                var tasksWithThrottler = new List<Task>();

                foreach (var item in enumerable)
                {
                    // Increment the number of currently running tasks and wait if they are more than limit.
                    await semaphoreSlim.WaitAsync();

                    tasksWithThrottler.Add(Task.Run(async () =>
                    {
                        await action(item).ContinueWith(res =>
                        {
                            // action is completed, so decrement the number of currently running tasks
                            semaphoreSlim.Release();
                        });
                    }));
                }

                // Wait for all tasks to complete.
                await Task.WhenAll(tasksWithThrottler.ToArray());
            }
        }
        else
        {
            await Task.WhenAll(enumerable.Select(item => action(item)));
        }
    }

Sample Usage:

await enumerable.ForEachAsyncConcurrent(
    async item =>
    {
        await SomeAsyncMethod(item);
    },
    5);

Is HTML considered a programming language?

No - there's a big prejudice in IT against web design; but in this case the "real" programmers are on pretty firm ground.

If you've done a lot of web design work you've probably done some JavaScript, so you can put that down under 'programming languages'; if you want to list HTML as well, then I agree with the answer that suggests "Technologies".

But unless you're targeting agents who're trying to tick boxes rather than find you a good job, a bare list of things you've used doesn't really look all that good. You're better off listing the projects you've worked on and detailing the technologies you used on each; that demonstrates that you've got real experience of using them rather than just that you know some buzzwords.

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

c++ custom compare function for std::sort()

Your comparison function is not even wrong.

Its arguments should be the type stored in the range, i.e. std::pair<K,V>, not const void*.

It should return bool not a positive or negative value. Both (bool)1 and (bool)-1 are true so your function says every object is ordered before every other object, which is clearly impossible.

You need to model the less-than operator, not strcmp or memcmp style comparisons.

See StrictWeakOrdering which describes the properties the function must meet.

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

Typescript sleep

For some reason the above accepted answer does not work in New versions of Angular (V6).

for that use this..

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

above worked for me.

Usage:

this.delay(3000);

OR more accurate way

this.delay(3000).then(any=>{
     //your task after delay.
});

Twig for loop for arrays with keys

I guess you want to do the "Iterating over Keys and Values"

As the doc here says, just add "|keys" in the variable you want and it will magically happen.

{% for key, user in users %}
    <li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}

It never hurts to search before asking :)

Automatically running a batch file as an administrator

The complete solution I found that worked was:

@echo off
cd /D "%~dp0"
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
"Put your command here"

credit for: https://stackoverflow.com/a/51472107/15087068

https://serverfault.com/a/95696

alert() not working in Chrome

Take a look at this thread: http://code.google.com/p/chromium/issues/detail?id=4158

The problem is caused by javascript method "window.open(URL, windowName[, windowFeatures])". If the 3rd parameter windowFeatures is specified, then alert box doesn't work in the popup constrained window in Chrome, here is a simplified reduction:

http://go/reductions/4158/test-home-constrained.html

If the 3rd parameter windowFeatures is ignored, then alert box works in the popup in Chrome(the popup is actually opened as a new tab in Chrome), like this:

http://go/reductions/4158/test-home-newtab.html

it doesn't happen in IE7, Firefox3 or Safari3, it's a chrome specific issue.

See also attachments for simplified reductions

What does elementFormDefault do in XSD?

Important to note with elementFormDefault is that it applies to locally defined elements, typically named elements inside a complexType block, as opposed to global elements defined on the top-level of the schema. With elementFormDefault="qualified" you can address local elements in the schema from within the xml document using the schema's target namespace as the document's default namespace.

In practice, use elementFormDefault="qualified" to be able to declare elements in nested blocks, otherwise you'll have to declare all elements on the top level and refer to them in the schema in nested elements using the ref attribute, resulting in a much less compact schema.

This bit in the XML Schema Primer talks about it: http://www.w3.org/TR/xmlschema-0/#NS

Where to place JavaScript in an HTML file?

The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder which will be available to all the files.

Command copy exited with code 4 when building - Visual Studio restart solves it

In my case my $(OutDir) was simply ..\..\Build\ i.e. some relative path. And, when I was trying to xcopy as follows xcopy /y "$(OutDir)Proj1.dll" "Anypath\anyfolder\" I was getting the exit code error 4.

What's happening was, this command was getting executed in the $(OutDir) (in my case build folder) itself and not the directory where the csproj file of the project was located (as we would normally expect). Hence, I kept getting File not found error (corresponding to exit code 4).

I couldn't figure this out until I wrote cd in the Post Build events, to print which directory this was getting executed in.

So, to summarize, if we're wishing to copy / xcopy files from the $(OutDir), either use "$(TargetDir)" (which is complete path for output directory) or need not specify any path at all.

What's the strangest corner case you've seen in C# or .NET?

What will this function do if called as Rec(0) (not under the debugger)?

static void Rec(int i)
{
    Console.WriteLine(i);
    if (i < int.MaxValue)
    {
        Rec(i + 1);
    }
}

Answer:

  • On 32-bit JIT it should result in a StackOverflowException
  • On 64-bit JIT it should print all the numbers to int.MaxValue

This is because the 64-bit JIT compiler applies tail call optimisation, whereas the 32-bit JIT does not.

Unfortunately I haven't got a 64-bit machine to hand to verify this, but the method does meet all the conditions for tail-call optimisation. If anybody does have one I'd be interested to see if it's true.

How to get a user's time zone?

NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];

The name will be something like "Australia/Sydney", or "Europe/Lisbon".

Since it sounds like you might only care about the continent, that might be all you need.

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

How to get the first five character of a String

Append five whitespace characters then cut off the first five and trim the result. The number of spaces you append should match the number you are cutting. Be sure to include the parenthesis before .Substring(0,X) or you'll append nothing.

string str = (yourStringVariable + "    ").Substring(0,5).Trim();

With this technique you won't have to worry about the ArgumentOutOfRangeException mentioned in other answers.

Can we have multiple <tbody> in same <table>?

I have created a JSFiddle where I have two nested ng-repeats with tables, and the parent ng-repeat on tbody. If you inspect any row in the table, you will see there are six tbody elements, i.e. the parent level.

HTML

<div>
        <table class="table table-hover table-condensed table-striped">
            <thead>
                <tr>
                    <th>Store ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Cost</th>
                    <th>Sales</th>
                    <th>Revenue</th>
                    <th>Employees</th>
                    <th>Employees H-sum</th>
                </tr>
            </thead>
            <tbody data-ng-repeat="storedata in storeDataModel.storedata">
                <tr id="storedata.store.storeId" class="clickableRow" title="Click to toggle collapse/expand day summaries for this store." data-ng-click="selectTableRow($index, storedata.store.storeId)">
                    <td>{{storedata.store.storeId}}</td>
                    <td>{{storedata.store.storeName}}</td>
                    <td>{{storedata.store.storeAddress}}</td>
                    <td>{{storedata.store.storeCity}}</td>
                    <td>{{storedata.data.costTotal}}</td>
                    <td>{{storedata.data.salesTotal}}</td>
                    <td>{{storedata.data.revenueTotal}}</td>
                    <td>{{storedata.data.averageEmployees}}</td>
                    <td>{{storedata.data.averageEmployeesHours}}</td>
                </tr>
                <tr data-ng-show="dayDataCollapse[$index]">
                    <td colspan="2">&nbsp;</td>
                    <td colspan="7">
                        <div>
                            <div class="pull-right">
                                <table class="table table-hover table-condensed table-striped">
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>Date [YYYY-MM-dd]</th>
                                            <th>Cost</th>
                                            <th>Sales</th>
                                            <th>Revenue</th>
                                            <th>Employees</th>
                                            <th>Employees H-sum</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr data-ng-repeat="dayData in storeDataModel.storedata[$index].data.dayData">
                                            <td class="pullright">
                                                <button type="btn btn-small" title="Click to show transactions for this specific day..." data-ng-click=""><i class="icon-list"></i>
                                                </button>
                                            </td>
                                            <td>{{dayData.date}}</td>
                                            <td>{{dayData.cost}}</td>
                                            <td>{{dayData.sales}}</td>
                                            <td>{{dayData.revenue}}</td>
                                            <td>{{dayData.employees}}</td>
                                            <td>{{dayData.employeesHoursSum}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

( Side note: This fills up the DOM if you have a lot of data on both levels, so I am therefore working on a directive to fetch data and replace, i.e. adding into DOM when clicking parent and removing when another is clicked or same parent again. To get the kind of behavior you find on Prisjakt.nu, if you scroll down to the computers listed and click on the row (not the links). If you do that and inspect elements you will see that a tr is added and then removed if parent is clicked again or another. )

"Exception has been thrown by the target of an invocation" error (mscorlib)

I'd suggest checking for an inner exception. If there isn't one, check your logs for the exception that occurred immediately prior to this one.

This isn't a web-specific exception, I've also encountered it in desktop-app development. In short, what's happening is that the thread receiving this exception is running some asynchronous code (via Invoke(), e.g.) and that code that's being run asynchronously is exploding with an exception. This target invocation exception is the aftermath of that failure.

If you haven't already, place some sort of exception logging wrapper around the asynchronous callbacks that are being invoked when you trigger this error. Event handlers, for instance. That ought to help you track down the problem.

Good luck!

How can I get the session object if I have the entity-manager?

See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:

Session session = entityManager.unwrap(Session.class);

How comment a JSP expression?

your <%= //map.size() %> doesnt simply work because it should have been

<% //= map.size() %>

Find which commit is currently checked out in Git

You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect session (note that options 1-4 will also work when you're not doing a bisect):

  1. git show.
  2. git log -1.
  3. Bash prompt.
  4. git status.
  5. git bisect visualize.

I'll explain each option in detail below.

Option 1: git show

As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect), you can use git show with the -s option to suppress patch output:

$ git show --oneline -s
a9874fd Merge branch 'epic-feature'

Option 2: git log -1

You can also simply do git log -1 to find out which commit you're currently on.

$ git log -1 --oneline
c1abcde Add feature-003

Option 3: Bash prompt

In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde checked out:

# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $

# Prompt at detached HEAD state 
user ~ (c1abcde...) $

Option 4: git status

Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:

$ git status
# HEAD detached at c1abcde <== RIGHT HERE

Option 5: git bisect visualize

Finally, while you're doing a git bisect, you can also simply use git bisect visualize or its built-in alias git bisect view to launch gitk, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:

git bisect visualize 
git bisect view # shorter, means same thing

enter image description here

SQL Data Reader - handling Null column values

There are a lot of answers here with useful info (and some wrong info) spread about, I'd like to bring it all together.

The short answer to the question is to check for DBNull - almost everyone agrees on this bit :)

Rather than using a helper method to read nullable values per SQL data type a generic method allows us to address this with a lot less code. However, you can't have a single generic method for both nullable value types and reference types, this is discussed at length in Nullable type as a generic parameter possible? and C# generic type constraint for everything nullable.

So, following on from the answers from @ZXX and @getpsyched we end up with this, 2 methods for getting nullable values and I've added a 3rd for non-null values (it completes the set based on method naming).

public static T? GetNullableValueType<T>(this SqlDataReader sqlDataReader, string columnName) where T : struct
{
    int columnOrdinal = sqlDataReader.GetOrdinal(columnName);
    return sqlDataReader.IsDBNull(columnOrdinal) ? (T?)null : sqlDataReader.GetFieldValue<T>(columnOrdinal);
}

public static T GetNullableReferenceType<T>(this SqlDataReader sqlDataReader, string columnName) where T : class
{
    int columnOrdinal = sqlDataReader.GetOrdinal(columnName);
    return sqlDataReader.IsDBNull(columnOrdinal) ? null : sqlDataReader.GetFieldValue<T>(columnOrdinal);
}

public static T GetNonNullValue<T>(this SqlDataReader sqlDataReader, string columnName)
{
    int columnOrdinal = sqlDataReader.GetOrdinal(columnName);
    return sqlDataReader.GetFieldValue<T>(columnOrdinal);
}

I usually use column names, alter these if you use column indexes. Based on these method names I can tell whether I'm expecting the data to be nullable or not, quite useful when looking at code written a long time ago.

Tips;

  • Not having nullable columns in the database avoids this issue. If you have control over the database then columns should be non-null by default and only nullable where necessary.
  • Don't cast database values with the C# 'as' operator because if the cast is wrong it will silently return null.
  • Using a default value expression will change database nulls to non-null values for value types like int, datetime, bit etc.

Lastly, whilst testing the above methods across all SQL Server data types I discovered you can't directly get a char[] from a SqlDataReader, if you want a char[] you will have to get a string and use ToCharArray().

How to Join to first row

try this

SELECT
   Orders.OrderNumber,
   LineItems.Quantity, 
   LineItems.Description
FROM Orders
   INNER JOIN (
      SELECT
         Orders.OrderNumber,
         Max(LineItem.LineItemID) AS LineItemID
       FROM Orders 
          INNER JOIN LineItems
          ON Orders.OrderNumber = LineItems.OrderNumber
       GROUP BY Orders.OrderNumber
   ) AS Items ON Orders.OrderNumber = Items.OrderNumber
   INNER JOIN LineItems 
   ON Items.LineItemID = LineItems.LineItemID

How to remove all the punctuation in a string? (Python)

This works, but there might be better solutions.

asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking

How do I set the path to a DLL file in Visual Studio?

I know this question had been answered years ago, but for those like me who needed to change where the debugger starts the application, change the command property under Project Properties -> Debugging.

How do I make a composite key with SQL Server Management Studio?

create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO


ALTER TABLE myTable
    ADD  PRIMARY KEY (Column1,Column2)
GO

How to check for null in Twig?

How to set default values in twig: http://twig.sensiolabs.org/doc/filters/default.html

{{ my_var | default("my_var doesn't exist") }}

Or if you don't want it to display when null:

{{ my_var | default("") }}

Are loops really faster in reverse?

Using the prefix increment operator is somewhat faster. With the postfix, the compiler must retain the previous value as the result of the expression.

for (var i = 0; i < n; ++i) {
  do_stuff();
}

A smart interpreter or compiler will see that the result of i++ is not used and not store the result of the expression, but not all js engines do.

Warning: The method assertEquals from the type Assert is deprecated

You're using junit.framework.Assert instead of org.junit.Assert.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

HTML "overlay" which allows clicks to fall through to elements behind it

My team ran into this issue and resolved it very nicely.

  • add a class "passthrough" or something to each element you want clickable and which is under the overlay.
  • for each ".passthrough" element append a div and position it exactly on top of its parent. add class "element-overlay" to this new div.
  • The ".element-overlay" css should have a high z-index (above the page's overlay), and the elements should be transparent.

This should resolve your problem as the events on the ".element-overlay" should bubble up to ".passthrough". If you still have problems (we did not see any so far) you can play around with the binding.

This is an enhancement to @jvenema's solution.

The nice thing about this is that

  • you don't pass through ALL events to ALL elements. Just the ones you want. (resolved @jvenema's argument)
  • All events will work properly. (hover for example).

If you have any problems please let me know so I can elaborate.

How to get a DOM Element from a JQuery Selector

You can access the raw DOM element with:

$("table").get(0);

or more simply:

$("table")[0];

There isn't actually a lot you need this for however (in my experience). Take your checkbox example:

$(":checkbox").click(function() {
  if ($(this).is(":checked")) {
    // do stuff
  }
});

is more "jquery'ish" and (imho) more concise. What if you wanted to number them?

$(":checkbox").each(function(i, elem) {
  $(elem).data("index", i);
});
$(":checkbox").click(function() {
  if ($(this).is(":checked") && $(this).data("index") == 0) {
    // do stuff
  }
});

Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

How would you make two <div>s overlap?

Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.

#logo
{
    position: absolute:
    z-index: 2000;
    left: 100px;
    width: 100px;
    height: 50px;
}

How can I check if a scrollbar is visible?

I'm going to extend on this even further for those poor souls who, like me, use one of the modern js frameworks and not JQuery and have been wholly abandoned by the people of this thread :

this was written in Angular 6 but if you write React 16, Vue 2, Polymer, Ionic, React-Native, you'll know what to do to adapt it. And it's the whole component so it should be easy.

import {ElementRef, AfterViewInit} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.html',
  styleUrls: ['./app.scss']
})
export class App implements AfterViewInit {
scrollAmount;

constructor(
  private fb: FormBuilder,
  private element: ElementRef 
) {}

ngAfterViewInit(){
  this.scrollAmount = this.element.nativeElement.querySelector('.elem-list');
  this.scrollAmount.addEventListener('wheel', e => { //you can put () instead of e
  // but e is usefull if you require the deltaY amount.
    if(this.scrollAmount.scrollHeight > this.scrollAmount.offsetHeight){
       // there is a scroll bar, do something!
    }else{
       // there is NO scroll bar, do something!
    }
  });
}
}

in the html there would be a div with class "elem-list" which is stylized in the css or scss to have a height and an overflow value that isn't hidden. (so auto or sroll )

I trigger this eval upon a scroll event because my end goal was to have "automatic focus scrolls" which decide whether they are scrolling the whole set of components horizontally if said components have no vertical scroll available and otherwise only scroll the innards of one of the components vertically.

but you can place the eval elsewhere to have it be triggered by something else.

the important thing to remember here, is you're never Forced back into using JQuery, there's always a way to access the same functionalities it has without using it.

Difference between Java SE/EE/ME?

As I come across this question, I found the information provided on the Oracle's tutorial very complete and worth to share:

The Java Programming Language Platforms

There are four platforms of the Java programming language:

  • Java Platform, Standard Edition (Java SE)

  • Java Platform, Enterprise Edition (Java EE)

  • Java Platform, Micro Edition (Java ME)

  • JavaFX

All Java platforms consist of a Java Virtual Machine (VM) and an application programming interface (API). The Java Virtual Machine is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. Each Java platform provides a virtual machine and an API, and this allows applications written for that platform to run on any compatible system with all the advantages of the Java programming language: platform-independence, power, stability, ease-of-development, and security.

Java SE

When most people think of the Java programming language, they think of the Java SE API. Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.

Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java ME

The Java ME platform provides an API and a small-footprint virtual machine for running Java programming language applications on small devices, like mobile phones. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services.

JavaFX

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. JavaFX applications use hardware-accelerated graphics and media engines to take advantage of higher-performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked data sources. JavaFX applications may be clients of Java EE platform services.

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

How to convert a python numpy array to an RGB image with Opencv 2.4?

If anyone else simply wants to display a black image as a background, here e.g. for 500x500 px:

import cv2
import numpy as np

black_screen  = np.zeros([500,500,3])
cv2.imshow("Simple_black", black_screen)
cv2.waitKey(0)

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

Android open pdf file

The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
}   

Get index of element as child relative to parent

something like:

$("ul#wizard li").click(function () {
  var index = $("ul#wizard li").index(this);
  alert("index is: " + index)
});

How to remove element from array in forEach loop?

The following will give you all the elements which is not equal to your special characters!

review = jQuery.grep( review, function ( value ) {
    return ( value !== '\u2022 \u2022 \u2022' );
} );

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

When you clearly look at the console, it will give you two examples. Implement any of these.

<input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone:true}">

or

<input [(ngModel)]="person.firstName" name="first">

XSLT - How to select XML Attribute by Attribute?

There are two problems with your xpath - first you need to remove the child selector from after Data like phihag mentioned. Also you forgot to include root in your xpath. Here is what you want to do:

select="/root/DataSet/Data[@Value1='2']/@Value2"

How to ignore the certificate check when ssl

Adding to Sani's and blak3r's answers, I've added the following to the startup code for my application, but in VB:

'** Overriding the certificate validation check.
Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True

Seems to do the trick.

How to display a list of images in a ListView in Android?

 package studRecords.one;

 import java.util.List;
 import java.util.Vector;

 import android.app.Activity;
 import android.app.ListActivity;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ParseException;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.TextView;



public class studRecords extends ListActivity 
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;

static final String[] names = new String[]
{
      "Name (Stud1)", "Name (Stud2)",   
      "Name (Stud3)","Name (Stud4)" 
};

static final String[] usn = new String[]
{
      "1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};

private Integer[] imgid = 
{
  R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
  R.drawable.stud4
};

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlist);

    layoutx = (LayoutInflater) getSystemService(
    Activity.LAYOUT_INFLATER_SERVICE);
    listValue = new Vector<RowData>();
    for(int i=0;i<names.length;i++)
    {
        try
        {
            rd = new RowData(names[i],usn[i],i);
        } 
        catch (ParseException e) 
        {
            e.printStackTrace();
        }
        listValue.add(rd);
    }


   CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
                                     R.id.detail, listValue);
   setListAdapter(adapter);
   getListView().setTextFilterEnabled(true);
}
   public void onListItemClick(ListView parent, View v, int position,long id)
   {            


       listName = names[position];
       listUsn = usn[position];
       images = imgid[position];




       Intent myIntent = new Intent();
       Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
       startActivity(myIntent);

   }
   private class RowData
   {

       protected String mNames;
       protected String mUsn;
       protected int mId;
       RowData(String title,String detail,int id){
       mId=id;
       mNames = title;
       mUsn = detail;
    }
       @Override
    public String toString()
       {
               return mNames+" "+mUsn+" "+mId;
       }
  }

              private class CustomAdapter extends ArrayAdapter<RowData> 
          {
      public CustomAdapter(Context context, int resource,
      int textViewResourceId, List<RowData> objects)
      {               
            super(context, resource, textViewResourceId, objects);
      }
      @Override
      public View getView(int position, View convertView, ViewGroup parent)
      {   
           ViewHolder holder = null;
           TextView title = null;
           TextView detail = null;
           ImageView i11=null;
           RowData rowData= getItem(position);
           if(null == convertView)
           {
                convertView = layoutx.inflate(R.layout.list, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
           }
         holder = (ViewHolder) convertView.getTag();
         i11=holder.getImage();
         i11.setImageResource(imgid[rowData.mId]);
         title = holder.gettitle();
         title.setText(rowData.mNames);
         detail = holder.getdetail();
         detail.setText(rowData.mUsn);                                                     

         return convertView;
      }

        private class ViewHolder 
        {
            private View mRow;
            private TextView title = null;
            private TextView detail = null;
            private ImageView i11=null; 
            public ViewHolder(View row)
            {
                    mRow = row;
            }
            public TextView gettitle()
            {
                 if(null == title)
                 {
                     title = (TextView) mRow.findViewById(R.id.title);
                 }
                 return title;
            }     
            public TextView getdetail()
            {
                if(null == detail)
                {
                    detail = (TextView) mRow.findViewById(R.id.detail);
                }
                return detail;
            }
            public ImageView getImage()
            {
                    if(null == i11)
                    {
                        i11 = (ImageView) mRow.findViewById(R.id.img);
                    }
                    return i11;
            }   
        }
   } 
 }

//mainlist.xml

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

ImportError: No module named requests

The only thing that worked for me:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
pip install requests

C linked list inserting node at the end

The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till end and then change the next of last node to new node.

/* Given a reference (pointer to pointer) to the head
   of a list and an int, appends a new node at the end  */


    void append(struct node** head_ref, int new_data)
    {
    /* 1. allocate node */
         struct node* new_node = (struct node*) malloc(sizeof(struct node));

        struct node *last = *head_ref;  /* used in step 5*/

    /* 2. put in the data  */
        new_node->data  = new_data;

    /* 3. This new node is going to be the last node, so make next 
          of it as NULL*/
        new_node->next = NULL;

    /* 4. If the <a href="#">Linked List</a> is empty, then make the new node as head */
        if (*head_ref == NULL)
        {
       *head_ref = new_node;
       return;
        }  

    /* 5. Else traverse till the last node */
        while (last->next != NULL)
        last = last->next;

    /* 6. Change the next of last node */
        last->next = new_node;
        return;    
}

HTML form submit to PHP script

<form method="POST" action="chk_kw.php">
    <select name="website_string"> 
        <option selected="selected"></option>
        <option value="abc">abc</option>
        <option value="def">def</option>
        <option value="hij">hij</option>   
    </select>
    <input type="submit">
</form>


  • As your form gets more complex, you can a quick check at top of your php script using print_r($_POST);, it'll show what's being submitted an the respective element name.
  • To get the submitted value of the element in question do:

    $website_string = $_POST['website_string'];

Calculate cosine similarity given 2 sentence strings

Try this. Download the file 'numberbatch-en-17.06.txt' from https://conceptnet.s3.amazonaws.com/downloads/2017/numberbatch/numberbatch-en-17.06.txt.gz and extract it. The function 'get_sentence_vector' uses a simple sum of word vectors. However it can be improved by using weighted sum where weights are proportional to Tf-Idf of each word.

import math
import numpy as np

std_embeddings_index = {}
with open('path/to/numberbatch-en-17.06.txt') as f:
    for line in f:
        values = line.split(' ')
        word = values[0]
        embedding = np.asarray(values[1:], dtype='float32')
        std_embeddings_index[word] = embedding

def cosineValue(v1,v2):
    "compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
    sumxx, sumxy, sumyy = 0, 0, 0
    for i in range(len(v1)):
        x = v1[i]; y = v2[i]
        sumxx += x*x
        sumyy += y*y
        sumxy += x*y
    return sumxy/math.sqrt(sumxx*sumyy)


def get_sentence_vector(sentence, std_embeddings_index = std_embeddings_index ):
    sent_vector = 0
    for word in sentence.lower().split():
        if word not in std_embeddings_index :
            word_vector = np.array(np.random.uniform(-1.0, 1.0, 300))
            std_embeddings_index[word] = word_vector
        else:
            word_vector = std_embeddings_index[word]
        sent_vector = sent_vector + word_vector

    return sent_vector

def cosine_sim(sent1, sent2):
    return cosineValue(get_sentence_vector(sent1), get_sentence_vector(sent2))

I did run for the given sentences and found the following results

s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
s3 = "What is this string ? Totally not related to the other two lines ."

print cosine_sim(s1, s2) # Should give high cosine similarity
print cosine_sim(s1, s3) # Shouldn't give high cosine similarity value
print cosine_sim(s2, s3) # Shouldn't give high cosine similarity value

0.9851735249068168
0.6570885718962608
0.6589335425458225

Angular 2.0 and Modal Dialog

I use ngx-bootstrap for my project.

You can find the demo here

The github is here

How to use:

  1. Install ngx-bootstrap

  2. Import to your module

// RECOMMENDED (doesn't work with system.js)
import { ModalModule } from 'ngx-bootstrap/modal';
// or
import { ModalModule } from 'ngx-bootstrap';

@NgModule({
  imports: [ModalModule.forRoot(),...]
})
export class AppModule(){}
  1. Simple static modal
<button type="button" class="btn btn-primary" (click)="staticModal.show()">Static modal</button>
<div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}"
tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
   <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title pull-left">Static modal</h4>
         <button type="button" class="close pull-right" aria-label="Close" (click)="staticModal.hide()">
         <span aria-hidden="true">&times;</span>
         </button>
      </div>
      <div class="modal-body">
         This is static modal, backdrop click will not close it.
         Click <b>&times;</b> to close modal.
      </div>
   </div>
</div>
</div>

In LINQ, select all values of property X where X != null

get one column in the distinct select and ignore null values:

 var items = db.table.Where(p => p.id!=null).GroupBy(p => p.id)
                                .Select(grp => grp.First().id)
                                .ToList();