Programs & Examples On #Wh keyboard ll

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

Calculate correlation with cor(), only for numerical columns

Another option would be to just use the excellent corrr package https://github.com/drsimonj/corrr and do

require(corrr)
require(dplyr)

myData %>% 
   select(x,y,z) %>%  # or do negative or range selections here
   correlate() %>%
   rearrange() %>%  # rearrange by correlations
   shave() # Shave off the upper triangle for a cleaner result

Steps 3 and 4 are entirely optional and are just included to demonstrate the usefulness of the package.

Append same text to every cell in a column in Excel

It's simple...

=CONCATENATE(A1, ",")

Example: if [email protected] is in the A1 cell then write in another cell: =CONCATENATE(A1, ",")

[email protected] After this formula you will get [email protected],

For remove formula: copy that cell and use Alt + E + S + V or paste special value.

iOS - Build fails with CocoaPods cannot find header files

If none of the above worked for you and you are finding this error because you just switched to use_frameworks! in your Podfile, read on:

I tried all the solutions above and a lot more before learning that it isn't about search header paths at all in my particular case; it's that when you switch to use_frameworks! in your Podfile you no longer need to include frameworks in your bridging header, and in fact Xcode will throw the very unhelpful "unable to find header" error.

What you need to do is remove all imports from your bridging header file, and instead use the Swift import Module in your individual Swift files as needed, just like you would for Swift frameworks.

AND if you are using any of the framework headers in your Obj-C classes (in my case we have a convenience class that used the FBSDK) you need to change it from a local to global import (this means change #import "Module.h" to #import <Module/Module.h>, which should autocomplete for you when you begin to type the framework name. In my case it was <AFNetworking/AFHTTPRequestOperationManager.h>).

Edit: I've since learned that doing an @import Module uses the umbrella file which is even safer.

iOS application: how to clear notifications?

Got it from here. It works for iOS 9

UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
    UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
    //Cancelling local notification
    [app cancelLocalNotification:oneEvent];
}

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Use these following commands, this will solve the error:

sudo apt-get install postgresql

then fire:

sudo apt-get install python-psycopg2

and last:

sudo apt-get install libpq-dev

JavaScript post request like a form submit

If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this:

 var form = new Element('form',
                        {method: 'post', action: 'http://example.com/'});
 form.insert(new Element('input',
                         {name: 'q', value: 'a', type: 'hidden'}));
 $(document.body).insert(form);
 form.submit();

Scanner vs. StringTokenizer vs. String.Split

StringTokenizer was always there. It is the fastest of all, but the enumeration-like idiom might not look as elegant as the others.

split came to existence on JDK 1.4. Slower than tokenizer but easier to use, since it is callable from the String class.

Scanner came to be on JDK 1.5. It is the most flexible and fills a long standing gap on the Java API to support an equivalent of the famous Cs scanf function family.

Testing if a site is vulnerable to Sql Injection

Any input from a client are ways to be vulnerable. Including all forms and the query string. This includes all HTTP verbs.

There are 3rd party solutions that can crawl an application and detect when an injection could happen.

Is there a way to break a list into columns?

If you are looking for a solution that works in IE as well, you could float the list elements to the left. However, this will result in a list that snakes around, like this:

item 1 | item 2 | item 3
item 4 | item 5

Instead of neat columns, like:

item 1 | item 4
item 2 | 
item 3 | 

The code to do that would be:

ul li {
  width:10em;
  float:left;
}

You could add a border-bottom to the lis to make the flow of the items from left to right more apparent.

Can CSS detect the number of children an element has?

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don't you just love CSS3?

CodePen Example:

Sources:

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

How do you connect to a MySQL database using Oracle SQL Developer?

My experience with windows client and linux/mysql server:

When sqldev is used in a windows client and mysql is installed in a linux server meaning, sqldev network access to mysql.

Assuming mysql is already up and running and the databases to be accessed are up and functional:

• Ensure the version of sqldev (32 or 64). If 64 and to avoid dealing with path access copy a valid 64 version of msvcr100.dll into directory ~\sqldeveloper\jdev\bin.

a. Open the file msvcr100.dll in notepad and search for first occurrence of “PE “

 i. “PE  d” it is 64.

ii. “PE  L” it is 32.

b. Note: if sqldev is 64 and msvcr100.dll is 32, the application gets stuck at startup.

• For sqldev to work with mysql there is need of the JDBC jar driver. Download it from mysql site.

a. Driver name = mysql-connector-java-x.x.xx

b. Copy it into someplace related to your sqldeveloper directory.

c. Set it up in menu sqldev Tools/Preferences/Database/Third Party JDBC Driver (add entry)

• In Linux/mysql server change file /etc/mysql/mysql.conf.d/mysqld.cnf look for

bind-address = 127.0.0.1 (this linux localhost)

and change to

bind-address = xxx.xxx.xxx.xxx (this linux server real IP or machine name if DNS is up)

• Enter to linux mysql and grant needed access for example

# mysql –u root -p

GRANT ALL ON . to root@'yourWindowsClientComputerName' IDENTIFIED BY 'mysqlPasswd';

flush privileges;

restart mysql - sudo /etc/init.d/mysql restart

• Start sqldev and create a new connection

a. user = root

b. pass = (your mysql pass)

c. Choose MySql tab

 i.   Hostname = the linux IP hostname

 ii.  Port     = 3306 (default for mysql)

 iii. Choose Database = (from pull down the mysql database you want to use)

 iv.  save and connect

That is all I had to do in my case.

Thank you,

Ale

React onClick function fires on render

Because you are calling that function instead of passing the function to onClick, change that line to this:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

How do I encode/decode HTML entities in Ruby?

You can use htmlascii gem:

Htmlascii.convert string

Auto-fit TextView for Android

If you are looking for something easier:

 public MyTextView extends TextView{

    public void resize(String text, float textViewWidth, float textViewHeight) {
       Paint p = new Paint();
       Rect bounds = new Rect();
       p.setTextSize(1);
       p.getTextBounds(text, 0, text.length(), bounds);
       float widthDifference = (textViewWidth)/bounds.width();
       float heightDifference = (textViewHeight);
       textSize = Math.min(widthDifference, heightDifference);
       setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}

How do I find numeric columns in Pandas?

You can use the undocumented function _get_numeric_data() to filter only numeric columns:

df._get_numeric_data()

Example:

In [32]: data
Out[32]:
   A  B
0  1  s
1  2  s
2  3  s
3  4  s

In [33]: data._get_numeric_data()
Out[33]:
   A
0  1
1  2
2  3
3  4

Note that this is a "private method" (i.e., an implementation detail) and is subject to change or total removal in the future. Use with caution.

HTML CSS How to stop a table cell from expanding

<table border="1" width="183" style='table-layout:fixed'>
  <col width="67">
  <col width="75">
  <col width="41">
  <tr>
    <td>First Column</td>
    <td>Second Column</td>
    <td>Third Column</td>
  </tr>
  <tr>
    <td>Row 1</td>
    <td>Text</td>
    <td align="right">1</td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td>Abcdefg</td>
    <td align="right">123</td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td>Abcdefghijklmnop</td>
    <td align="right">123456</td>
  </tr>
</table>

I know it's old school, but give that a try, it works.

may also want to add this:

<style>
  td {overflow:hidden;}
</style>

Of course, you'd put this in a separate linked stylesheet, and not inline... wouldn't you ;)

Binding Button click to a method

You have various possibilies. The most simple and the most ugly is:

XAML

<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/> 

Code Behind

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    FrameworkElement fe=sender as FrameworkElement;
    ((YourClass)fe.DataContext).DoYourCommand();     
} 

Another solution (better) is to provide a ICommand-property on your YourClass. This command will have already a reference to your YourClass-object and therefore can execute an action on this class.

XAML

<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>

Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.

Why is `input` in Python 3 throwing NameError: name... is not defined

In operating systems like Ubuntu python comes preinstalled. So the default version is python 2.7 you can confirm the version by typing below command in your terminal

python -V

if you installed it but didn't set default version you will see

python 2.7

in terminal. I will tell you how to set the default python version in Ubuntu.

A simple safe way would be to use an alias. Place this into ~/.bashrc or ~/.bash_aliases file:

alias python=python3

After adding the above in the file, run the command below:

source ~/.bash_aliases or source ~/.bashrc

now check python version again using python -V

if python version 3.x.x one, then the error is in your syntax like using print with parenthesis. change it to

test = input("enter the test")
print(test)

How can I commit files with git?

When you run git commit with no arguments, it will open your default editor to allow you to type a commit message. Saving the file and quitting the editor will make the commit.

It looks like your default editor is Vi or Vim. The reason "weird stuff" happens when you type is that Vi doesn't start in insert mode - you have to hit i on your keyboard first! If you don't want that, you can change it to something simpler, for example:

git config --global core.editor nano

Then you'll load the Nano editor (assuming it's installed!) when you commit, which is much more intuitive for users who've not used a modal editor such as Vi.

That text you see on your screen is just to remind you what you're about to commit. The lines are preceded by # which means they're comments, i.e. Git ignores those lines when you save your commit message. You don't need to type a message per file - just enter some text at the top of the editor's buffer.

To bypass the editor, you can provide a commit message as an argument, e.g.

git commit -m "Added foo to the bar"

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

join list of lists in python

I had a similar problem when I had to create a dictionary that contained the elements of an array and their count. The answer is relevant because, I flatten a list of lists, get the elements I need and then do a group and count. I used Python's map function to produce a tuple of element and it's count and groupby over the array. Note that the groupby takes the array element itself as the keyfunc. As a relatively new Python coder, I find it to me more easier to comprehend, while being Pythonic as well.

Before I discuss the code, here is a sample of data I had to flatten first:

{ "_id" : ObjectId("4fe3a90783157d765d000011"), "status" : [ "opencalais" ],
  "content_length" : 688, "open_calais_extract" : { "entities" : [
  {"type" :"Person","name" : "Iman Samdura","rel_score" : 0.223 }, 
  {"type" : "Company",  "name" : "Associated Press",    "rel_score" : 0.321 },          
  {"type" : "Country",  "name" : "Indonesia",   "rel_score" : 0.321 }, ... ]},
  "title" : "Indonesia Police Arrest Bali Bomb Planner", "time" : "06:42  ET",         
  "filename" : "021121bn.01", "month" : "November", "utctime" : 1037836800,
  "date" : "November 21, 2002", "news_type" : "bn", "day" : "21" }

It is a query result from Mongo. The code below flattens a collection of such lists.

def flatten_list(items):
  return sorted([entity['name'] for entity in [entities for sublist in  
   [item['open_calais_extract']['entities'] for item in items] 
   for entities in sublist])

First, I would extract all the "entities" collection, and then for each entities collection, iterate over the dictionary and extract the name attribute.

How can I convert byte size into a human-readable format in Java?

Byte Units allows you to do it like this:

long input1 = 1024;
long input2 = 1024 * 1024;

Assert.assertEquals("1 KiB", BinaryByteUnit.format(input1));
Assert.assertEquals("1 MiB", BinaryByteUnit.format(input2));

Assert.assertEquals("1.024 KB", DecimalByteUnit.format(input1, "#.0"));
Assert.assertEquals("1.049 MB", DecimalByteUnit.format(input2, "#.000"));

NumberFormat format = new DecimalFormat("#.#");
Assert.assertEquals("1 KiB", BinaryByteUnit.format(input1, format));
Assert.assertEquals("1 MiB", BinaryByteUnit.format(input2, format));

I have written another library called storage-units that allows you to do it like this:

String formattedUnit1 = StorageUnits.formatAsCommonUnit(input1, "#");
String formattedUnit2 = StorageUnits.formatAsCommonUnit(input2, "#");
String formattedUnit3 = StorageUnits.formatAsBinaryUnit(input1);
String formattedUnit4 = StorageUnits.formatAsBinaryUnit(input2);
String formattedUnit5 = StorageUnits.formatAsDecimalUnit(input1, "#.00", Locale.GERMAN);
String formattedUnit6 = StorageUnits.formatAsDecimalUnit(input2, "#.00", Locale.GERMAN);
String formattedUnit7 = StorageUnits.formatAsBinaryUnit(input1, format);
String formattedUnit8 = StorageUnits.formatAsBinaryUnit(input2, format);

Assert.assertEquals("1 kB", formattedUnit1);
Assert.assertEquals("1 MB", formattedUnit2);
Assert.assertEquals("1.00 KiB", formattedUnit3);
Assert.assertEquals("1.00 MiB", formattedUnit4);
Assert.assertEquals("1,02 kB", formattedUnit5);
Assert.assertEquals("1,05 MB", formattedUnit6);
Assert.assertEquals("1 KiB", formattedUnit7);
Assert.assertEquals("1 MiB", formattedUnit8);

In case you want to force a certain unit, do this:

String formattedUnit9 = StorageUnits.formatAsKibibyte(input2);
String formattedUnit10 = StorageUnits.formatAsCommonMegabyte(input2);

Assert.assertEquals("1024.00 KiB", formattedUnit9);
Assert.assertEquals("1.00 MB", formattedUnit10);

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

How to create cross-domain request?

@RestController
@RequestMapping(value = "/profile")
@CrossOrigin(origins="*")
public class UserProfileController {

SpringREST provides @CrossOrigin annotations where (origins="*") allow access to REST APIS from any source.

We can add it to respective API or entire RestController.

force Maven to copy dependencies into target/lib

It's a heavy solution for embedding heavy dependencies, but Maven's Assembly Plugin does the trick for me.

@Rich Seller's answer should work, although for simpler cases you should only need this excerpt from the usage guide:

<project>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.2</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

Sum function in VBA

Function is not a property/method from range.

If you want to sum values then use the following:

Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))

EDIT:

if you want the formula then use as follows:

Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"

'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).

In case you are allways going to use the same range address then you can use as Rory sugested:

Range("A1").Formula ="=Sum(A2:B3)"

Recursive file search using PowerShell

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat

Will also work

how to set image from url for imageView

You can use either Picasso or Glide.

Picasso.with(context)
   .load(your_url)
   .into(imageView);


Glide.with(context)
   .load(your_url)
   .into(imageView);

Can I safely delete contents of Xcode Derived data folder?

Just created a github repo with a small script, that creates a RAM disk. If you point your DerivedData folder to /Volumes/ramdisk, after ejecting disk all files will be gone.

It speeds up compiling, also eliminates this problem

xc-launch repo

Best launched using DTerm

How can I change Eclipse theme?

In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

How to reformat JSON in Notepad++?

You can view in Notepad++ no problem now (maybe older versions were bugged?)

for win64: You can find the latest plugin here: https://github.com/kapilratnani/JSON-Viewer/releases . The latest zip file contains a .dll file.

And then follow the github priject README instructions:

  1. Paste the file "NPPJSONViewer.dll" to Notepad++ plugin folder
  2. open a document containing a JSON string
  3. Select JSON fragment and navigate to plugins/JSON Viewer/show JSON Viewer or press "Ctrl+Alt+Shift+J"
  4. Voila!! if the JSON is valid, it will be shown in a Treeview

It should be the same process for win32 but I cannot personally verify it.

Flutter position stack widget in center

You can try this too:

Center(
  child: Stack(
    children: [],
  ),
)

break statement in "if else" - java

The "break" command does not work within an "if" statement.

If you remove the "break" command from your code and then test the code, you should find that the code works exactly the same without a "break" command as with one.

"Break" is designed for use inside loops (for, while, do-while, enhanced for and switch).

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

Two problems:

1 - You never told Git to start tracking any file

You write that you ran

git init
git commit -m "first commit"

and that, at that stage, you got

nothing added to commit but untracked files present (use "git add" to track).

Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):

Hey Git, you see that README.md file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...

For that you need to stage the files of interest, using

git add README.md

before running

git commit -m "some descriptive message"

2 - You haven't set up the remote repository

You then ran

git remote add origin https://github.com/VijayNew/NewExample.git

After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get

enter image description here

Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with

git push -u origin master

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

Alert handling in Selenium WebDriver (selenium 2) with Java

You could try

 try{
        if(webDriver.switchTo().alert() != null){
           Alert alert = webDriver.switchTo().alert();
           alert.getText();
           //etc.
        }
    }catch(Exception e){}

If that doesn't work, you could try looping through all the window handles and see if the alert exists. I'm not sure if the alert opens as a new window using selenium.

for(String s: webDriver.getWindowHandles()){
 //see if alert exists here.
}

Read input numbers separated by spaces

You'll want to:

  • Read in an entire line from the console
  • Tokenize the line, splitting along spaces.
  • Place those split pieces into an array or list
  • Step through that array/list, performing your prime/perfect/etc tests.

What has your class covered along these lines so far?

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

Putty: Getting Server refused our key Error

In my case, is a permission problem.

I changed the log level to DEBUG3, and in /var/log/secure I see this line:

Authentication refused: bad ownership or modes for directory

Googled and I found this post:

https://www.daveperrett.com/articles/2010/09/14/ssh-authentication-refused/

chmod g-w /home/your_user
chmod 700 /home/your_user/.ssh
chmod 600 /home/your_user/.ssh/authorized_keys

Basically, it tells me to:

  • get rid of group w permission of your user home dir
  • change permission to 700 of the .ssh dir
  • change permission to 600 of the authorized_keys file.

And that works.

Another thing is that even I enabled root login, I cannot get root to work. Better use another user.

Accessing post variables using Java Servlets

POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.

Is it possible to clone html element objects in JavaScript / JQuery?

Yes, you can copy children of one element and paste them into the other element:

var foo1 = jQuery('#foo1');
var foo2 = jQuery('#foo2');

foo1.html(foo2.children().clone());

Proof: http://jsfiddle.net/de9kc/

How can I mock the JavaScript window object using Jest?

If it's similar to the window location problem at window.location.href can't be changed in tests. #890, you could try (adjusted):

delete global.window.open;
global.window = Object.create(window);
global.window.open = jest.fn();

How to echo out the values of this array?

Here is a simple routine for an array of primitive elements:

for ($i = 0; $i < count($mySimpleArray); $i++)
{
   echo $mySimpleArray[$i] . "\n";
}

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Some time has passed since this question was asked (and answered) but another option is to override the Accept header on the server during request processing using a MessageHandler as below:

public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
    {
        var someOtherCondition = false;
        var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
        if (someOtherCondition && accHeader.Contains("application/xml"))
        {
            request.Headers.Remove("Accept");
            request.Headers.Add("Accept", "application/json");
        }
        return await base.SendAsync(request, cancellationToken);
    }
}

Where someOtherCondition can be anything including browser type, etc. This would be for conditional cases where only sometimes do we want to override the default content negotiation. Otherwise as per other answers, you would simply remove an unnecessary formatter from the configuration.

You'll need to register it of course. You can either do this globally:

  public static void Register(HttpConfiguration config) {
      config.MessageHandlers.Add(new ForceableContentTypeDelegationHandler());
  }

or on a route by route basis:

config.Routes.MapHttpRoute(
   name: "SpecialContentRoute",
   routeTemplate: "api/someUrlThatNeedsSpecialTreatment/{id}",
   defaults: new { controller = "SpecialTreatment" id = RouteParameter.Optional },
   constraints: null,
   handler: new ForceableContentTypeDelegationHandler()
);

And since this is a message handler it will run on both the request and response ends of the pipeline much like an HttpModule. So you could easily acknowledge the override with a custom header:

public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request,
                CancellationToken cancellationToken)
    {
        var wasForced = false;
        var someOtherCondition = false;
        var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
        if (someOtherCondition && accHeader.Contains("application/xml"))
        {
            request.Headers.Remove("Accept");
            request.Headers.Add("Accept", "application/json");
            wasForced = true;
        }

        var response =  await base.SendAsync(request, cancellationToken);
        if (wasForced){
          response.Headers.Add("X-ForcedContent", "We overrode your content prefs, sorry");
        }
        return response;
    }
}

Argument Exception "Item with Same Key has already been added"

That Exception is thrown if there is already a key in the dictionary when you try to add the new one.

There must be more than one line in rct3Lines with the same first word. You can't have 2 entries in the same dictionary with the same key.

You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply

rct3Features[items[0]]=items[1]

but, if not you may want to test if the key already exists with:

if(rect3Features.ContainsKey(items[0]))
{
    //Do something
} 
else 
{
    //Do something else
}

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

In my case it was $NODE_PATH missing:

NODE="/home/ubuntu/local/node" #here your user account after home
NODE_PATH="/usr/local/lib/node_modules" 
PATH="$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:$NODE/bin:$NODE/lib/node_modules"

To check just echo $NODE_PATH empty means it is not set. Add them to .bashrc is recommended.

C# Numeric Only TextBox Control

You can check the Ascii value by e.keychar on KeyPress event of TextBox.

By checking the AscII value you can check for number or character.

Similarly you can write logic to check the Email ID.

CSS fixed width in a span

Well, there's always the brute force method:

<li><pre>    The lazy dog.</pre></li>
<li><pre>AND The lazy cat.</pre></li>
<li><pre>OR  The active goldfish.</pre></li>

Or is that what you meant by "padding" the text? That's an ambiguous work in this context.

This sounds kind of like a homework question. I hope you're not trying to get us to do your homework for you?

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

Checking if a variable is an integer

I have had a similar issue before trying to determine if something is a string or any sort of number whatsoever. I have tried using a regular expression, but that is not reliable for my use case. Instead, you can check the variable's class to see if it is a descendant of the Numeric class.

if column.class < Numeric
  number_to_currency(column)
else
  column.html_safe
end

In this situation, you could also substitute for any of the Numeric descendants: BigDecimal, Date::Infinity, Integer, Fixnum, Float, Bignum, Rational, Complex

Multiple Inheritance in C#

Yes using Interface is a hassle because anytime we add a method in the class we have to add the signature in the interface. Also, what if we already have a class with a bunch of methods but no Interface for it? we have to manually create Interface for all the classes that we want to inherit from. And the worst thing is, we have to implement all methods in the Interfaces in the child class if the child class is to inherit from the multiple interface.

By following Facade design pattern we can simulate inheriting from multiple classes using accessors. Declare the classes as properties with {get;set;} inside the class that need to inherit and all public properties and methods are from that class, and in the constructor of the child class instantiate the parent classes.

For example:

 namespace OOP
 {
     class Program
     {
         static void Main(string[] args)
         {
             Child somechild = new Child();
             somechild.DoHomeWork();
             somechild.CheckingAround();
             Console.ReadLine();
         }
     }

     public class Father 
     {
         public Father() { }
         public void Work()
         {
             Console.WriteLine("working...");
         }
         public void Moonlight()
         {
             Console.WriteLine("moonlighting...");
         }
     }


     public class Mother 
     {
         public Mother() { }
         public void Cook()
         {
             Console.WriteLine("cooking...");
         }
         public void Clean()
         {
             Console.WriteLine("cleaning...");
         }
     }


     public class Child 
     {
         public Father MyFather { get; set; }
         public Mother MyMother { get; set; }

         public Child()
         {
             MyFather = new Father();
             MyMother = new Mother();
         }

         public void GoToSchool()
         {
             Console.WriteLine("go to school...");
         }
         public void DoHomeWork()
         {
             Console.WriteLine("doing homework...");
         }
         public void CheckingAround()
         {
             MyFather.Work();
             MyMother.Cook();
         }
     }


 }

with this structure class Child will have access to all methods and properties of Class Father and Mother, simulating multiple inheritance, inheriting an instance of the parent classes. Not quite the same but it is practical.

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Get full path of the files in PowerShell

[alternative syntax]

For some people, directional pipe operators are not their taste, but they rather prefer chaining. See some interesting opinions on this topic shared in roslyn issue tracker: dotnet/roslyn#5445.

Based on the case and the context, one of this approach can be considered implicit (or indirect). For example, in this case using pipe against enumerable requires special token $_ (aka PowerShell's "THIS" token) might appear distasteful to some.

For such fellas, here is a more concise, straight-forward way of doing it with dot chaining:

(gci . -re -fi *.txt).FullName

(<rant> Note that PowerShell's command arguments parser accepts the partial parameter names. So in addition to -recursive; -recursiv, -recursi, -recurs, -recur, -recu, -rec and -re are accepted, but unfortunately not -r .. which is the only correct choice that makes sense with single - character (if we go by POSIXy UNIXy conventions)! </rant>)

How to add a button dynamically in Android?

try this:

for (int i = 1; i <= 20; i++) {
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    Button btn = new Button(this);
    btn.setId(i);
    final int id_ = btn.getId();
    btn.setText("button " + id_);
    btn.setBackgroundColor(Color.rgb(70, 80, 90));
    linear.addView(btn, params);
    btn1 = ((Button) findViewById(id_));
    btn1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Toast.makeText(view.getContext(),
                    "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                    .show();
        }
    });
}

Chrome DevTools Devices does not detect device when plugged in

Samsung phone + PC with Windows

First of all you need to turn on USB debugging on your phone:

  1. Settings / About phone / Software information / Build number (tap it 7 times to turn on developer mode)
  2. Settings / Developer options / USB debugging (turn it on)

Then on your PC:

  1. Install Samsung USB driver https://developer.samsung.com/mobile/android-usb-driver.html
  2. Install ADB https://forum.xda-developers.com/showthread.php?t=2317790 (in the forum scroll down to the section "Downloads" to get the newest version of ADB)
  3. After ADB installation CMD should pop up -> start ADB with command "adb devices" (for example "C:\Program Files (x86)\Minimal ADB and Fastboot> adb devices")
  4. Connect your phone to your PC with USB cable
  5. Alert about the connection should pop up on your phone (allow it)
  6. In Chrome on your PC open Developer tools / More tools / Remote devices and you should finally see your phone being detected

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

If you want to run a single independent queued operation and you’re not concerned with other concurrent operations, you can use the global concurrent queue:

dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

This will return a concurrent queue with the given priority as outlined in the documentation:

DISPATCH_QUEUE_PRIORITY_HIGH Items dispatched to the queue will run at high priority, i.e. the queue will be scheduled for execution before any default priority or low priority queue.

DISPATCH_QUEUE_PRIORITY_DEFAULT Items dispatched to the queue will run at the default priority, i.e. the queue will be scheduled for execution after all high priority queues have been scheduled, but before any low priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_LOW Items dispatched to the queue will run at low priority, i.e. the queue will be scheduled for execution after all default priority and high priority queues have been scheduled.

DISPATCH_QUEUE_PRIORITY_BACKGROUND Items dispatched to the queue will run at background priority, i.e. the queue will be scheduled for execution after all higher priority queues have been scheduled and the system will run items on this queue on a thread with background status as per setpriority(2) (i.e. disk I/O is throttled and the thread’s scheduling priority is set to lowest value).

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

This gist will do most of the work for you showing a menu when there are multiple devices connected:

$ adb $(android-select-device) shell
1) 02783201431feeee device 3) emulator-5554
2) 3832380FA5F30000 device 4) emulator-5556
Select the device to use, <Q> to quit:

To avoid typing you can just create an alias that included the device selection as explained here.

Can we import XML file into another XML file?

You could use an external (parsed) general entity.

You declare the entity like this:

<!ENTITY otherFile SYSTEM "otherFile.xml">

Then you reference it like this:

&otherFile;

A complete example:

<?xml version="1.0" standalone="no" ?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "otherFile.xml">
]>
<doc>
  <foo>
    <bar>&otherFile;</bar>
  </foo>
</doc>

When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.

If the "otherFile.xml" contained: <baz>this is my content</baz>

Then the XML would be evaluated and "seen" by an XML parser as:

<?xml version="1.0" standalone="no" ?>
<doc>
  <foo>
    <bar><baz>this is my content</baz></bar>
  </foo>
</doc>

A few references that might be helpful:

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

How to add/update child entities when updating a parent entity in EF

@Charles McIntosh really gave me the answer for my situation in that the passed in model was detached. For me what ultimately worked was saving the passed in model first... then continuing to add the children as I already was before:

public async Task<IHttpActionResult> GetUPSFreight(PartsExpressOrder order)
{
    db.Entry(order).State = EntityState.Modified;
    db.SaveChanges();
  ...
}

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db.

There is no default config file, so you will either need to specify this when starting mongod with:

 mongod --config /etc/mongodb.conf

.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.

Note: to check the dbpath and command-line options for a running mongod, connect via the mongo shell and run:

db.serverCmdLineOpts()

In particular, if a custom dbpath is set it will be the value of:

db.serverCmdLineOpts().parsed.dbpath           // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath   // MongoDB 2.6+

How to check if an array is empty?

To check array is null:

int arr[] = null;
if (arr == null) {
 System.out.println("array is null");
}

To check array is empty:

arr = new int[0];
if (arr.length == 0) {
 System.out.println("array is empty");
}

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

I had the error after trying to select a subset of rows:

df = df.reindex(index=my_index)

Turns out that my_index contained values that were not contained in df.index, so the reindex function inserted some new rows and filled them with nan.

Subset data to contain only columns whose names match a condition

Using dplyr you can:

df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))

Using jQuery to compare two arrays of Javascript objects

I was also looking for this today and found: http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD

Don't know if that's a good solution though they do mention some performance considerations taken into account.

I like the idea of a jQuery helper method. @David I'd rather see your compare method to work like:

jQuery.compare(a, b)

I doesn't make sense to me to be doing:

$(a).compare(b)

where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.

Also regarding sorting and 'caching' the sorted arrays:

  • I don't think sorting once at the start of the method instead of every time through the loop is 'caching'. The sort will still happen every time you call compare(b). That's just semantics, but...
  • for (var i = 0; t[i]; i++) { ...this loop finishes early if your t array contains a false value in it somewhere, so $([1, 2, 3, 4]).compare([1, false, 2, 3]) returns true!
  • More importantly the array sort() method sorts the array in place, so doing var b = t.sort() ...doesn't create a sorted copy of the original array, it sorts the original array and also assigns a reference to it in b. I don't think the compare method should have side-effects.

It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)

In which case I think the code for it would be:

jQuery.extend({
    compare: function (arrayA, arrayB) {
        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        var a = jQuery.extend(true, [], arrayA);
        var b = jQuery.extend(true, [], arrayB);
        a.sort(); 
        b.sort();
        for (var i = 0, l = a.length; i < l; i++) {
            if (a[i] !== b[i]) { 
                return false;
            }
        }
        return true;
    }
});

var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];

jQuery.compare(a, b);
// false

jQuery.compare(b, c);
// true

// c is still unsorted [3, 4, 2]

Creating an empty list in Python

I do not really know about it, but it seems to me, by experience, that jpcgt is actually right. Following example: If I use following code

t = [] # implicit instantiation
t = t.append(1)

in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.

t = t.append(2)

I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by

t = list() # explicit instantiation

then it works fine.

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

Print DIV content by JQuery

There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.

Css:

#SelectorToPrint{
     display: none;
}

Script:

  $("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})

This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.

Global variables in header file

You should not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

(Note: In C, int i; is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)

Save the plots into a PDF

If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):

import matplotlib.pyplot as plt

f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()

f.savefig("foo.pdf", bbox_inches='tight')

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

The rules (which did not change in C++11):

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
    • identifiers containing adjacent underscores (or "double underscore")
  • Reserved in the global namespace:
    • identifiers beginning with an underscore
  • Also, everything in the std namespace is reserved. (You are allowed to add template specializations, though.)

From the 2003 C++ Standard:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:

7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
  • Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
  • All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
  • Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.

No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

154) The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.

Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:

  • Names beginning with a capital E followed a digit or uppercase letter:
    • may be used for additional error code names.
  • Names that begin with either is or to followed by a lowercase letter
    • may be used for additional character testing and conversion functions.
  • Names that begin with LC_ followed by an uppercase letter
    • may be used for additional macros specifying locale attributes.
  • Names of all existing mathematics functions suffixed with f or l are reserved
    • for corresponding functions that operate on float and long double arguments, respectively.
  • Names that begin with SIG followed by an uppercase letter are reserved
    • for additional signal names.
  • Names that begin with SIG_ followed by an uppercase letter are reserved
    • for additional signal actions.
  • Names beginning with str, mem, or wcs followed by a lowercase letter are reserved
    • for additional string and array functions.
  • Names beginning with PRI or SCN followed by any lowercase letter or X are reserved
    • for additional format specifier macros
  • Names that end with _t are reserved
    • for additional type names.

While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.


Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.

After doing research on this article I no longer end my identifiers with _t as this is reserved by the POSIX standard.

The rule about any identifier ending with _t surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.

CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.

FileNotFoundException..Classpath resource not found in spring?

Best way to handle such error-"Use Annotation". spring.xml-<context:component-scan base-package=com.SpringCollection.SpringCollection"/>

add annotation in that class for which you want to use Bean ID(i am using class "First")-

@Component

public class First {

Changes In Main Class**-

ApplicationContext context = new AnnotationConfigApplicationContext(First.class); use this.

SyntaxError: Use of const in strict mode?

For me it was more simple to solve, just going to the Node web site, get and install the LTS version.

What is newline character -- '\n'

Try this:

$ sed -e $'s/\n/\n\n/g' states

Pass a string parameter in an onclick function

You can use this:

'<input id="test" type="button" value="' + result.name + '" />'

$(document)..on('click', "#test", function () {
    alert($(this).val());
});

It worked for me.

Cut off text in string after/before separator in powershell

$pos = $name.IndexOf(";")
$leftPart = $name.Substring(0, $pos)
$rightPart = $name.Substring($pos+1)

Internally, PowerShell uses the String class.

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

Import / Export database with SQL Server Server Management Studio

I wanted to share with you my solution to export a database with Microsoft SQL Server Management Studio.

To Export your database

  1. Open a new request
  2. Copy paste this script
DECLARE @BackupFile NVARCHAR(255);
SET @BackupFile = 'c:\database-backup_2020.07.22.bak';
PRINT @BackupFile;
BACKUP DATABASE [%databaseName%] TO DISK = @BackupFile;

Don't forget to replace %databaseName% with the name of the database you want to export.

Note that this method gives a lighter file than from the menu.

To import this file from SQL Server Management Studio. Don't forget to delete your database beforehand.

  1. Click restore database

Click restore database

  1. Add the backup file Add the backup file

  2. Validate

Enjoy! :) :)

Can you do a partial checkout with Subversion?

Subversion 1.5 introduces sparse checkouts which may be something you might find useful. From the documentation:

... sparse directories (or shallow checkouts) ... allows you to easily check out a working copy—or a portion of a working copy—more shallowly than full recursion, with the freedom to bring in previously ignored files and subdirectories at a later time.

JavaScript: Global variables after Ajax requests

It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

I think you can simplify this by just adding the necessary CSS properties to your special scrollable menu class..

CSS:

.scrollable-menu {
    height: auto;
    max-height: 200px;
    overflow-x: hidden;
}

HTML

       <ul class="dropdown-menu scrollable-menu" role="menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li><a href="#">Action</a></li>
            ..
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
       </ul>

Working example: https://www.bootply.com/86116

Bootstrap 4

Another example for Bootstrap 4 using flexbox

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

How can I convert a string to an int in Python?

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

Best HTML5 markup for sidebar

Based on this HTML5 Doctor diagram, I'm thinking this may be the best markup:

<aside class="sidebar">
    <article id="widget_1" class="widget">...</article>
    <article id="widget_2" class="widget">...</article>
    <article id="widget_3" class="widget">...</article>
</aside> <!-- end .sidebar -->

I think it's clear that <aside> is the appropriate element as long as it's outside the main <article> element.

Now, I'm thinking that <article> is also appropriate for each widget in the aside. In the words of the W3C:

The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

How to create a number picker dialog?

A Simple Example:

layout/billing_day_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <NumberPicker
        android:id="@+id/number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/apply_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/number_picker"
        android:text="Apply" />

</RelativeLayout>

NumberPickerActivity.java

import android.app.Activity;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.NumberPicker;

public class NumberPickerActivity extends Activity 
{

  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.billing_day_dialog);
    NumberPicker np = (NumberPicker)findViewById(R.id.number_picker);
    np.setMinValue(1);// restricted number to minimum value i.e 1
    np.setMaxValue(31);// restricked number to maximum value i.e. 31
    np.setWrapSelectorWheel(true); 

    np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() 
    {

      @Override
      public void onValueChange(NumberPicker picker, int oldVal, int newVal) 
      {

       // TODO Auto-generated method stub

       String Old = "Old Value : ";

       String New = "New Value : ";

      }
    });

     Log.d("NumberPicker", "NumberPicker");

   }

}/* NumberPickerActivity */

AndroidManifest.xml : Specify theme for the activity as dialogue theme.

<activity
  android:name="org.npn.analytics.call.NumberPickerActivity"
  android:theme="@android:style/Theme.Holo.Dialog"
  android:label="@string/title_activity_number_picker" >
</activity>

Hope it will help.

How can I print the contents of an array horizontally?

int[] n=new int[5];

for (int i = 0; i < 5; i++)
{
    n[i] = i + 100;
}

foreach (int j in n)
{
    int i = j - 100;

    Console.WriteLine("Element [{0}]={1}", i, j);
    i++;
}

Export result set on Dbeaver to CSV

The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.

Sorting a list with stream.sorted() in Java

This is a simple example :

List<String> citiesName = Arrays.asList( "Delhi","Mumbai","Chennai","Banglore","Kolkata");
System.out.println("Cities : "+citiesName);
List<String> sortedByName = citiesName.stream()
                .sorted((s1,s2)->s2.compareTo(s1))
                        .collect(Collectors.toList());
System.out.println("Sorted by Name : "+ sortedByName);

It may be possible that your IDE is not getting the jdk 1.8 or upper version to compile the code.

Set the Java version 1.8 for Your_Project > properties > Project Facets > Java version 1.8

What do multiple arrow functions mean in javascript?

That is a curried function

First, examine this function with two parameters …

const add = (x, y) => x + y
add(2, 3) //=> 5

Here it is again in curried form …

const add = x => y => x + y

Here is the same1 code without arrow functions …

const add = function (x) {
  return function (y) {
    return x + y
  }
}

Focus on return

It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.

const f = someParam => returnValue

So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add

const add = x => (y => x + y)

In other words add of some number returns a function

add(2) // returns (y => 2 + y)

Calling curried functions

So in order to use our curried function, we have to call it a bit differently …

add(2)(3)  // returns 5

This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …

const add2 = add(2) // returns function(y) { return 2 + y }
add2(3)             // returns 5

Applying our new understanding to your code

related: ”What’s the difference between binding, partial application, and currying?”

OK, now that we understand how that works, let's look at your code

handleChange = field => e => {
  e.preventDefault()
  /// Do something here
}

We'll start by representing it without using arrow functions …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  };
};

However, because arrow functions lexically bind this, it would actually look more like this …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  }.bind(this)
}.bind(this)

Maybe now we can see what this is doing more clearly. The handleChange function is creating a function for a specified field. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange function, we can eliminate all the duplicated code that would result in setting up change listeners for each field. Cool!

1 Here I did not have to lexically bind this because the original add function does not use any context, so it is not important to preserve it in this case.


Even more arrows

More than two arrow functions can be sequenced, if necessary -

const three = a => b => c =>
  a + b + c

const four = a => b => c => d =>
  a + b + c + d

three (1) (2) (3) // 6

four (1) (2) (3) (4) // 10

Curried functions are capable of surprising things. Below we see $ defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -

_x000D_
_x000D_
const $ = x => k =>_x000D_
  $ (k (x))_x000D_
  _x000D_
const add = x => y =>_x000D_
  x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
  x * y_x000D_
  _x000D_
$ (1)           // 1_x000D_
  (add (2))     // + 2 = 3_x000D_
  (mult (6))    // * 6 = 18_x000D_
  (console.log) // 18_x000D_
  _x000D_
$ (7)            // 7_x000D_
  (add (1))      // + 1 = 8_x000D_
  (mult (8))     // * 8 = 64_x000D_
  (mult (2))     // * 2 = 128_x000D_
  (mult (2))     // * 2 = 256_x000D_
  (console.log)  // 256
_x000D_
_x000D_
_x000D_

Partial application

Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -

const partial = (f, ...a) => (...b) =>
  f (...a, ...b)

const add3 = (x, y, z) =>
  x + y + z

partial (add3) (1, 2, 3)   // 6

partial (add3, 1) (2, 3)   // 6

partial (add3, 1, 2) (3)   // 6

partial (add3, 1, 2, 3) () // 6

partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3

Here's a working demo of partial you can play with in your own browser -

_x000D_
_x000D_
const partial = (f, ...a) => (...b) =>_x000D_
  f (...a, ...b)_x000D_
  _x000D_
const preventDefault = (f, event) =>_x000D_
  ( event .preventDefault ()_x000D_
  , f (event)_x000D_
  )_x000D_
  _x000D_
const logKeypress = event =>_x000D_
  console .log (event.which)_x000D_
  _x000D_
document_x000D_
  .querySelector ('input[name=foo]')_x000D_
  .addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
_x000D_
_x000D_

Check if a string has white space

Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/" characters are sufficient.

/^\s+$/ is checking whether the string is ALL whitespace:

  • ^ matches the start of the string.
  • \s+ means at least 1, possibly more, spaces.
  • $ matches the end of the string.

Try replacing the regex with /\s/ (and no quotes)

Cut Java String at a number of character

You can use safe substring:

org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

How do I check if a Sql server string is null or empty

Use the LEN function to check for null or empty values. You can just use LEN(@SomeVarcharParm) > 0. This will return false if the value is NULL, '', or ' '. This is because LEN(NULL) returns NULL and NULL > 0 returns false. Also, LEN(' ') returns 0. See for yourself run:

SELECT 
 CASE WHEN NULL > 0 THEN 'NULL > 0 = true' ELSE 'NULL > 0 = false' END,
 CASE WHEN LEN(NULL) > 0 THEN 'LEN(NULL) = true' ELSE 'LEN(NULL) = false' END,
 CASE WHEN LEN('') > 0 THEN 'LEN('''') > 0 = true' ELSE 'LEN('''') > 0 = false' END,
 CASE WHEN LEN(' ') > 0 THEN 'LEN('' '') > 0 = true' ELSE 'LEN('' '') > 0 = false' END,
 CASE WHEN LEN(' test ') > 0 THEN 'LEN('' test '') > 0 = true' ELSE 'LEN('' test '') > 0 = false' END

RVM is not a function, selecting rubies with 'rvm use ...' will not work

It seems like your rvm does not load ".bash_profile" properly. I have done to fix it in MAC OS X or Ubuntu 14.04 by opening terminal and write:

source ~/.rvm/scripts/rvm

How to exit from the application and show the home screen?

Here's what i did:

SomeActivity.java

 @Override
    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(newIntent);
            finish();
    }

QuitAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      finish();
}

Basically what you did is cleared all activities from the stack and launch QuitAppActivity, that will finish the task.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

How to execute an Oracle stored procedure via a database link

for me, this worked

exec utl_mail.send@myotherdb(
  sender => '[email protected]',recipients => '[email protected], 
  cc => null, subject => 'my subject', message => 'my message'
); 

What is monkey patching?

First: monkey patching is an evil hack (in my opinion).

It is often used to replace a method on the module or class level with a custom implementation.

The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.

Best way to determine user's locale within browser

There's a difference between the user's preferred languages and the system/browser locale.

A user can configure preferred languages in the browser, and these will be used for navigator.language(s), and used when requesting resources from a server, to request content according to a list of language priorities.

However, the browser locale will decide how to render number, date, time and currency. This setting is likely the highest ranking language, but there is no guarantee. On Mac and Linux, the locale is decided by the system regardless of the user language preferences. On Windows is can be elected among the languages in the preferred list on Chrome.

By using Intl (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), developers can override/set the locale to use to render these things, but there are elements that cannot be overridden, such as the <input type="date"> format.

To properly extract this language, the only way I've found is:

(new Intl.NumberFormat()).resolvedOptions().locale

(Intl.NumberFormat().resolvedOptions().locale also seems to work)

This will create a new NumberFormat instance for the default locale and then reading back the locale of those resolved options.

Unable to Cast from Parent Class to Child Class

As for me it was enough to copy all property fields from the base class to the parent like this:

using System.Reflection;

public static ChildClass Clone(BaseClass b)
{
    ChildClass p = new ChildClass(...);

    // Getting properties of base class

    PropertyInfo[] properties = typeof(BaseClass).GetProperties();

    // Copy all properties to parent class

    foreach (PropertyInfo pi in properties)
    {
        if (pi.CanWrite)
            pi.SetValue(p, pi.GetValue(b, null), null);
    }

    return p;
}

An universal solution for any object can be found here

How can I extract a predetermined range of lines from a text file on Unix?

Standing on the shoulders of boxxar, I like this:

sed -n '<first line>,$p;<last line>q' input

e.g.

sed -n '16224,$p;16482q' input

The $ means "last line", so the first command makes sed print all lines starting with line 16224 and the second command makes sed quit after printing line 16428. (Adding 1 for the q-range in boxxar's solution does not seem to be necessary.)

I like this variant because I don't need to specify the ending line number twice. And I measured that using $ does not have detrimental effects on performance.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

-- or you could create a stored procedure ... first with Id creation

USE [db]
GO

/****** Object:  StoredProcedure [dbo].[procUtils_InsertGeneratorWithId]    Script Date: 06/13/2009 22:18:11 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


create PROC [dbo].[procUtils_InsertGeneratorWithId]    
(    
@domain_user varchar(50),    
@tableName varchar(100)    
)     


as    

--Declare a cursor to retrieve column specific information for the specified table    
DECLARE cursCol CURSOR FAST_FORWARD FOR     
SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName    
OPEN cursCol    
DECLARE @string nvarchar(3000) --for storing the first half of INSERT statement    
DECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement    
DECLARE @dataType nvarchar(1000) --data types returned for respective columns    
DECLARE @IDENTITY_STRING nvarchar ( 100 )    
SET @IDENTITY_STRING = ' '     
select  @IDENTITY_STRING    
SET @string='INSERT '+@tableName+'('    
SET @stringData=''    

DECLARE @colName nvarchar(50)    

FETCH NEXT FROM cursCol INTO @colName,@dataType    

IF @@fetch_status<>0    
 begin    
 print 'Table '+@tableName+' not found, processing skipped.'    
 close curscol    
 deallocate curscol    
 return    
END    

WHILE @@FETCH_STATUS=0    
BEGIN    
IF @dataType in ('varchar','char','nchar','nvarchar')    
BEGIN    
 --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+'    
 SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+'    
END    
ELSE    
if @dataType in ('text','ntext') --if the datatype is text or something else     
BEGIN    
 SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'    
END    
ELSE    
IF @dataType = 'money' --because money doesn't get converted from varchar implicitly    
BEGIN    
 SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'    
END    
ELSE     
IF @dataType='datetime'    
BEGIN    
 --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'    
 --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations    
 --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'    
 SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'    
  --                             'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations    
END    
ELSE     
IF @dataType='image'     
BEGIN    
 SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+'    
END    
ELSE --presuming the data type is int,bit,numeric,decimal     
BEGIN    
 --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'    
 --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'    
 SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+'    
END    

SET @string=@string+@colName+','    

FETCH NEXT FROM cursCol INTO @colName,@dataType    
END    
DECLARE @Query nvarchar(4000)    

SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName    
exec sp_executesql @query    
--select @query    

CLOSE cursCol    
DEALLOCATE cursCol    


  /*
USAGE

*/

GO

-- and second without iD INSERTION

USE [db]
GO

/****** Object:  StoredProcedure [dbo].[procUtils_InsertGenerator]    Script Date: 06/13/2009 22:20:52 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[procUtils_InsertGenerator]        
(        
@domain_user varchar(50),        
@tableName varchar(100)        
)         


as        

--Declare a cursor to retrieve column specific information for the specified table        
DECLARE cursCol CURSOR FAST_FORWARD FOR         


-- SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName        
/* NEW     
SELECT c.name , sc.data_type  FROM sys.extended_properties AS ep                   
INNER JOIN sys.tables AS t ON ep.major_id = t.object_id                   
INNER JOIN sys.columns AS c ON ep.major_id = c.object_id AND ep.minor_id                   
= c.column_id                   
INNER JOIN INFORMATION_SCHEMA.COLUMNS sc ON t.name = sc.table_name and                   
c.name = sc.column_name                   
WHERE t.name = @tableName and c.is_identity=0      
  */      

select object_name(c.object_id) "TABLE_NAME", c.name "COLUMN_NAME", s.name "DATA_TYPE"      
  from sys.columns c          
  join sys.systypes s on (s.xtype = c.system_type_id)          
  where object_name(c.object_id) in (select name from sys.tables where name not like 'sysdiagrams')          
   AND object_name(c.object_id) in (select name from sys.tables where [name]=@tableName  ) and c.is_identity=0 and s.name not like 'sysname'  




OPEN cursCol        
DECLARE @string nvarchar(3000) --for storing the first half of INSERT statement        
DECLARE @stringData nvarchar(3000) --for storing the data (VALUES) related statement        
DECLARE @dataType nvarchar(1000) --data types returned for respective columns        
DECLARE @IDENTITY_STRING nvarchar ( 100 )        
SET @IDENTITY_STRING = ' '         
select  @IDENTITY_STRING        
SET @string='INSERT '+@tableName+'('        
SET @stringData=''        

DECLARE @colName nvarchar(50)        

FETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType        

IF @@fetch_status<>0        
 begin        
 print 'Table '+@tableName+' not found, processing skipped.'        
 close curscol        
 deallocate curscol        
 return        
END        

WHILE @@FETCH_STATUS=0        
BEGIN        
IF @dataType in ('varchar','char','nchar','nvarchar')        
BEGIN        
 --SET @stringData=@stringData+'''''''''+isnull('+@colName+','''')+'''''',''+'        
 SET @stringData=@stringData+''''+'''+isnull('''''+'''''+'+@colName+'+'''''+''''',''NULL'')+'',''+'        
END        
ELSE        
if @dataType in ('text','ntext') --if the datatype is text or something else         
BEGIN        
 SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(2000)),'''')+'''''',''+'        
END        
ELSE        
IF @dataType = 'money' --because money doesn't get converted from varchar implicitly        
BEGIN        
 SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'        
END        
ELSE         
IF @dataType='datetime'        
BEGIN        
 --SET @stringData=@stringData+'''convert(datetime,''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+''''''),''+'        
 --SELECT 'INSERT Authorizations(StatusDate) VALUES('+'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations        
 --SET @stringData=@stringData+'''convert(money,''''''+isnull(cast('+@colName+' as varchar(200)),''0.0000'')+''''''),''+'        
 SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'        
  --                             'convert(datetime,'+isnull(''''+convert(varchar(200),StatusDate,121)+'''','NULL')+',121),)' FROM Authorizations        
END        
ELSE         
IF @dataType='image'         
BEGIN        
 SET @stringData=@stringData+'''''''''+isnull(cast(convert(varbinary,'+@colName+') as varchar(6)),''0'')+'''''',''+'        
END        
ELSE --presuming the data type is int,bit,numeric,decimal         
BEGIN        
 --SET @stringData=@stringData+'''''''''+isnull(cast('+@colName+' as varchar(200)),''0'')+'''''',''+'        
 --SET @stringData=@stringData+'''convert(datetime,'+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+',121)+'''''+''''',''NULL'')+'',121),''+'        
 SET @stringData=@stringData+''''+'''+isnull('''''+'''''+convert(varchar(200),'+@colName+')+'''''+''''',''NULL'')+'',''+'        
END        

SET @string=@string+@colName+','        

FETCH NEXT FROM cursCol INTO @tableName , @colName,@dataType        
END        
DECLARE @Query nvarchar(4000)        

SET @query ='SELECT '''+substring(@string,0,len(@string)) + ') VALUES(''+ ' + substring(@stringData,0,len(@stringData)-2)+'''+'')'' FROM '+@tableName        
exec sp_executesql @query        
--select @query       

CLOSE cursCol        
DEALLOCATE cursCol        


  /*      

use poc     
go    

DECLARE @RC int      
DECLARE @domain_user varchar(50)      
DECLARE @tableName varchar(100)      

-- TODO: Set parameter values here.      
set @domain_user='yorgeorg'      
set @tableName = 'tbGui_WizardTabButtonAreas'      

EXECUTE @RC = [POC].[dbo].[procUtils_InsertGenerator]       
   @domain_user      
  ,@tableName      

*/
GO

Calculate the number of business days between two dates?

Since I can't comment. There is one more issue with the accepted solution where bank holidays are subtracted even when they are situated in the weekend. Seeing how other input is checked, it is only fitting that this is as well.

The foreach should therefore be:

    // subtract the number of bank holidays during the time interval
    foreach (DateTime bankHoliday in bankHolidays)
    {
        DateTime bh = bankHoliday.Date;

        // Do not subtract bank holidays when they fall in the weekend to avoid double subtraction
        if (bh.DayOfWeek == DayOfWeek.Saturday || bh.DayOfWeek == DayOfWeek.Sunday)
                continue;

        if (firstDay <= bh && bh <= lastDay)
            --businessDays;
    }

Copy map values to vector in STL

One way is to use functor:

 template <class T1, class T2>
    class CopyMapToVec
    {
    public: 
        CopyMapToVec(std::vector<T2>& aVec): mVec(aVec){}

        bool operator () (const std::pair<T1,T2>& mapVal) const
        {
            mVec.push_back(mapVal.second);
            return true;
        }
    private:
        std::vector<T2>& mVec;
    };


int main()
{
    std::map<std::string, int> myMap;
    myMap["test1"] = 1;
    myMap["test2"] = 2;

    std::vector<int>  myVector;

    //reserve the memory for vector
    myVector.reserve(myMap.size());
    //create the functor
    CopyMapToVec<std::string, int> aConverter(myVector);

    //call the functor
    std::for_each(myMap.begin(), myMap.end(), aConverter);
}

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

How to measure elapsed time

Even better!

long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds

Read the documentation about nanoTime()!

C - gettimeofday for computing time?

The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.


Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).

The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.

Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.

<<

JWT (JSON Web Token) automatic prolongation of expiration

I solved this problem by adding a variable in the token data:

softexp - I set this to 5 mins (300 seconds)

I set expiresIn option to my desired time before the user will be forced to login again. Mine is set to 30 minutes. This must be greater than the value of softexp.

When my client side app sends request to the server API (where token is required, eg. customer list page), the server checks whether the token submitted is still valid or not based on its original expiration (expiresIn) value. If it's not valid, server will respond with a status particular for this error, eg. INVALID_TOKEN.

If the token is still valid based on expiredIn value, but it already exceeded the softexp value, the server will respond with a separate status for this error, eg. EXPIRED_TOKEN:

(Math.floor(Date.now() / 1000) > decoded.softexp)

On the client side, if it received EXPIRED_TOKEN response, it should renew the token automatically by sending a renewal request to the server. This is transparent to the user and automatically being taken care of the client app.

The renewal method in the server must check if the token is still valid:

jwt.verify(token, secret, (err, decoded) => {})

The server will refuse to renew tokens if it failed the above method.

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

XMLHttpRequest cannot load an URL with jQuery

I am using WebAPI 3 and was facing the same issue. The issue has resolve as @Rytis added his solution. And I think in WebAPI 3, we don't need to define method RegisterWebApi.

My change was only in web.config file and is working.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 <add name="Access-Control-Allow-Methods" value="GET, POST" />
</customHeaders>
</httpProtocol> 

Thanks for you solution @Rytis!

Export and import table dump (.sql) using pgAdmin

Using PgAdmin step 1: select schema and right click and go to Backup..enter image description here

step 2: Give the file name and click the backup button.

enter image description here

step 3: In detail message copy the backup file path.

enter image description here

step 4:

Go to other schema and right click and go to Restore. (see step 1)

step 5:

In popup menu paste aboved file path to filename category and click Restore button.

enter image description here

OSX - How to auto Close Terminal window after the "exit" command executed.

You can also use this convoluted command, which does not trigger a warning about terminating its own process:
osascript -e "do shell script \"osascript -e \\\"tell application \\\\\\\"Terminal\\\\\\\" to quit\\\" &> /dev/null &\""; exit

This command is quite long, so you could define an alias (such as quit) in your bash profile:
alias quit='osascript -e "do shell script \"osascript -e \\\"tell application \\\\\\\"Terminal\\\\\\\" to quit\\\" &> /dev/null &\""; exit'

This would allow you to simply type quit into terminal without having to fiddle with any other settings.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

1.redirect return the request to the browser from server,then resend the request to the server from browser.

2.forward send the request to another servlet (servlet to servlet).

Bootstrap 3 unable to display glyphicon properly

Just in case :

For example, I just tryed <span class="icones glyphicon glyphicon-pen"> and after one hour i realized that this icon was not included in the bootstrap pack !! While the enveloppe icon was working fine..

Hope this helps

How to convert a Scikit-learn dataset to a Pandas dataset?

TOMDLt's solution is not generic enough for all the datasets in scikit-learn. For example it does not work for the boston housing dataset. I propose a different solution which is more universal. No need to use numpy as well.

from sklearn import datasets
import pandas as pd

boston_data = datasets.load_boston()
df_boston = pd.DataFrame(boston_data.data,columns=boston_data.feature_names)
df_boston['target'] = pd.Series(boston_data.target)
df_boston.head()

As a general function:

def sklearn_to_df(sklearn_dataset):
    df = pd.DataFrame(sklearn_dataset.data, columns=sklearn_dataset.feature_names)
    df['target'] = pd.Series(sklearn_dataset.target)
    return df

df_boston = sklearn_to_df(datasets.load_boston())

Convert a python UTC datetime to a local datetime using only python standard library?

A simple (but maybe flawed) way that works in Python 2 and 3:

import time
import datetime

def utc_to_local(dt):
    return dt - datetime.timedelta(seconds = time.timezone)

Its advantage is that it's trivial to write an inverse function

How to set header and options in axios?

This is a simple example of a configuration with headers and responseType:

var config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  responseType: 'blob'
};

axios.post('http://YOUR_URL', this.data, config)
  .then((response) => {
  console.log(response.data);
});

Content-Type can be 'application/x-www-form-urlencoded' or 'application/json' and it may work also 'application/json;charset=utf-8'

responseType can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'

In this example, this.data is the data you want to send. It can be a value or an Array. (If you want to send an object you'll probably have to serialize it)

Xcode - Warning: Implicit declaration of function is invalid in C99

I have the same warning (it's make my app cannot build). When I add C function in Objective-C's .m file, But forgot to declared it at .h file.

In jQuery, what's the best way of formatting a number to 2 decimal places?

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

How to check whether a str(variable) is empty or not?

For python 3, you can use bool()

>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True

How to move div vertically down using CSS

You could make your blue div position: relative and then give the div.title position:absolute; and bottom: 0px

Here is a working demo.. http://jsfiddle.net/gLaG6/

Insert PHP code In WordPress Page and Post

You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.

The easiest solution for this is creating a shortcode. Then you can use something like this

function input_func( $atts ) {
    extract( shortcode_atts( array(
        'type' => 'text',
        'name' => '',
    ), $atts ) );

    return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );

See the Shortcode_API.

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

Java 8: Difference between two LocalDateTime in multiple units

Here a single example using Duration and TimeUnit to get 'hh:mm:ss' format.

Duration dur = Duration.between(localDateTimeIni, localDateTimeEnd);
long millis = dur.toMillis();

String.format("%02d:%02d:%02d", 
        TimeUnit.MILLISECONDS.toHours(millis),
        TimeUnit.MILLISECONDS.toMinutes(millis) - 
        TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
        TimeUnit.MILLISECONDS.toSeconds(millis) - 
        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

Regex allow digits and a single dot

Try the following expression

/^\d{0,2}(\.\d{1,2})?$/.test()

Javascript - Open a given URL in a new tab by clicking a button

Use this:

<input type="button" value="button name" onclick="window.open('http://www.website.com/page')" />

Worked for me and it will open an actual new 'popup' window rather than a new full browser or tab. You can also add variables to it to stop it from showing specific browser traits as follows:

onclick="window.open(this.href,'popUpWindow','height=400,width=600,left=10,top=10,,scrollbars=yes,menubar=no'); return false;"

Distinct by property of class with LINQ

You can implement an IEqualityComparer and use that in your Distinct extension.

class CarEqualityComparer : IEqualityComparer<Car>
{
    #region IEqualityComparer<Car> Members

    public bool Equals(Car x, Car y)
    {
        return x.CarCode.Equals(y.CarCode);
    }

    public int GetHashCode(Car obj)
    {
        return obj.CarCode.GetHashCode();
    }

    #endregion
}

And then

var uniqueCars = cars.Distinct(new CarEqualityComparer());

Atom menu is missing. How do I re-enable

Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

If you are using XAMPP rather than WAMP, the path you go to is:

C:\xampp\phpMyAdmin\config.inc.php

Getting the SQL from a Django QuerySet

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

I've changed the recursion to iteration.

def MovingTheBall(listOfBalls,position,numCell):
while 1:
    stop=1
    positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
    for i in range(0,len(listOfBalls)):
        if positionTmp==listOfBalls[i].pos:
            stop=0
    if stop==1:
        if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
            stop=0
        else:
            return positionTmp

Works good :D

Waiting for Target Device to Come Online

  1. Another case is Android Emulator should be reinstalled. This can happen, when you install a higher version of Android Studio, then update SDK for it, and go back to previous one.

    Tools - Android - SDK Manager - SDK Tools - Android Emulator - uncheck, apply, check, apply

  2. Disable Docker app if you have it (Mac users).

  3. Restart emulator:

    Tools - Android - AVD Manager (or kill adb process in task manager).

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:

add(3,5)

which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

How do I make a branch point at a specific commit?

You can make master point at 1258f0d0aae this way:

git checkout master
git reset --hard 1258f0d0aae

But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.

Also, the git reset --hard command will throw away any uncommitted changes (i.e. those just in your working tree or the index).

You can also force an update to a branch with:

git branch -f master 1258f0d0aae

... but git won't let you do that if you're on master at the time.

Testing whether a value is odd or even

Use modulus:

function isEven(n) {
   return n % 2 == 0;
}

function isOdd(n) {
   return Math.abs(n % 2) == 1;
}

You can check that any value in Javascript can be coerced to a number with:

Number.isFinite(parseFloat(n))

This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

Add days to JavaScript Date

As simple as this:

new Date((new Date()).getTime() + (60*60*24*1000));

Regular expression to match DNS hostname or IP Address?

>>> my_hostname = "testhostn.ame"
>>> print bool(re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname))
True
>>> my_hostname = "testhostn....ame"
>>> print bool(re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname))
False
>>> my_hostname = "testhostn.A.ame"
>>> print bool(re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname))
True

How to implement "confirmation" dialog in Jquery UI dialog?

I ran into this myself and ended up with a solution, that is similar to several answers here, but implemented slightly differently. I didn't like many pieces of javascript, or a placeholder div somewhere. I wanted a generalized solution, that could then be used in HTML without adding javascript for each use. Here is what I came up with (this requires jquery ui):

Javascript:

$(function() {

  $("a.confirm").button().click(function(e) {

    e.preventDefault();

    var target = $(this).attr("href");
    var content = $(this).attr("title");
    var title = $(this).attr("alt");

    $('<div>' + content + '</div>'). dialog({
      draggable: false,
      modal: true,
      resizable: false,
      width: 'auto',
      title: title,
      buttons: {
        "Confirm": function() {
          window.location.href = target;
        },
        "Cancel": function() {
          $(this).dialog("close");
        }
      }
    });

  });

});

And then in HTML, no javascript calls or references are needed:

<a href="http://www.google.com/"
   class="confirm"
   alt="Confirm test"
   title="Are you sure?">Test</a>

Since the title attribute is used for the div content, the user can even get the confirmation question by hovering over the button (which is why i didn't user the title attribute for the tile). The title of the confirmation window is the content of the alt tag. The javascript snip can be included in a generalized .js include, and simply by applying a class you have a pretty confirmation window.

Spark dataframe: collect () vs select ()

To answer the questions directly:

Will collect() behave the same way if called on a dataframe?

Yes, spark.DataFrame.collect is functionally the same as spark.RDD.collect. They serve the same purpose on these different objects.

What about the select() method?

There is no such thing as spark.RDD.select, so it cannot be the same as spark.DataFrame.select.

Does it also work the same way as collect() if called on a dataframe?

The only thing that is similar between select and collect is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.

Here's my own description: collect is the opposite of sc.parallelize. select is the same as the SELECT in any SQL statement.

If you are still having trouble understanding what collect actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:

why is plotting with Matplotlib so slow?

To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook

However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.

Put these two lines before you import anything else from matplotlib:

import matplotlib
matplotlib.use('GTKAgg') 

Of course, there are various options to use instead of GTKAgg, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.

Get a CSS value with JavaScript

The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last. The last matching rule is the one which applies. Here is a working version:

function getStyleRuleValue(style, selector) {
  let value = null;
  for (let i = 0; i < document.styleSheets.length; i++) {
    const mysheet = document.styleSheets[i];
    const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    for (let j = 0; j < myrules.length; j++) {
      if (myrules[j].selectorText && 
          myrules[j].selectorText.toLowerCase() === selector) {
        value =  myrules[j].style[style];
      }
    }
  }
  return value;
}  

However, this simple search will not work in case of complex selectors.

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Undoing a git rebase

Let's say I rebase master to my feature branch and I get 30 new commits which break something. I've found that often it's easiest to just remove the bad commits.

git rebase -i HEAD~31

Interactive rebase for the last 31 commits (it doesn't hurt if you pick way too many).

Simply take the commits that you want to get rid of and mark them with "d" instead of "pick". Now the commits are deleted effectively undoing the rebase (if you remove only the commits you just got when rebasing).

Custom Adapter for List View

BaseAdapter is best custom adapter for listview.

Class MyAdapter extends BaseAdapter{}

and it has many functions such as getCount(), getView() etc.

Why does DEBUG=False setting make my django Static Files Access fail?

I agree with Marek Sapkota answer; But you can still use django URFConf to reallocate the url, if static file is requested.

Step 1: Define a STATIC_ROOT path in settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Step 2: Then collect the static files

$ python manage.py collectstatic

Step 3: Now define your URLConf that if static is in the beginning of url, access files from the static folder staticfiles. NOTE: This is your project's urls.py file:

from django.urls import re_path
from django.views.static import serve

urlpattern += [
  re_path(r'^static/(?:.*)$', serve, {'document_root': settings.STATIC_ROOT, })
]

Could not load file or assembly '***.dll' or one of its dependencies

1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays); 2) Make sure your project is built for x86 target (runs in 32-bit mode).

Follow this thread for more

Detecting a mobile browser

As many have stated, relying on the moving target of the user agent data is problematic. The same can be said for counting on screen size.

My approach is borrowed from a CSS technique to determine if the interface is touch:

Using only javascript (support by all modern browsers), a media query match can easily infer whether the device is mobile.

function isMobile() {
    var match = window.matchMedia || window.msMatchMedia;
    if(match) {
        var mq = match("(pointer:coarse)");
        return mq.matches;
    }
    return false;
}

Get the current cell in Excel VB

This may not help answer your question directly but is something I have found useful when trying to work with dynamic ranges that may help you out.

Suppose in your worksheet you have the numbers 100 to 108 in cells A1:C3:

          A    B    C  
1        100  101  102
2        103  104  105
3        106  107  108

Then to select all the cells you can use the CurrentRegion property:

Sub SelectRange()
Dim dynamicRange As Range

Set dynamicRange = Range("A1").CurrentRegion

End Sub

The advantage of this is that if you add new rows or columns to your block of numbers (e.g. 109, 110, 111) then the CurrentRegion will always reference the enlarged range (in this case A1:C4).

I have used CurrentRegion quite a bit in my VBA code and find it is most useful when working with dynmacially sized ranges. Also it avoids having to hard code ranges in your code.

As a final note, in my code you will see that I used A1 as the reference cell for CurrentRegion. It will also work no matter which cell you reference (try: replacing A1 with B2 for example). The reason is that CurrentRegion will select all contiguous cells based on the reference cell.

How do I serialize an object and save it to a file in Android?

I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:

Option1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

Option 2 is twice quicker than option 1

The option 2 inconvenience is that you have to make specific code for read:

Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);

How to use export with Python on Linux

import os
import shlex
from subprocess import Popen, PIPE


os.environ.update(key=value)

res = Popen(shlex.split("cmd xxx -xxx"), stdin=PIPE, stdout=PIPE, stderr=PIPE,
            env=os.environ, shell=True).communicate('y\ny\ny\n'.encode('utf8'))
stdout = res[0]
stderr = res[1]

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

What is the best way to left align and right align two div tags?

<style>
#div1, #div2 {
   float: left; /* or right */
}
</style>

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

A free tool to check C/C++ source code against a set of coding standards?

Check Metrix++ http://metrixplusplus.sourceforge.net/. It may require some extensions which are specific for your needs.

Is there a way to check which CSS styles are being used or not used on a web page?

Just for completeness and because it was asked in the comments - there's also the CSS audit tool in Chrome now for the same purpose. Some details here:

http://meeech.amihod.com/very-useful-find-unused-css-rules-with-google

Update index after sorting data-frame

You can reset the index using reset_index to get back a default index of 0, 1, 2, ..., n-1 (and use drop=True to indicate you want to drop the existing index instead of adding it as an additional column to your dataframe):

In [19]: df2 = df2.reset_index(drop=True)

In [20]: df2
Out[20]:
   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

Failed to decode downloaded font

If it is on the server (not in localhost), then try to upload the fonts manually, because sometimes the FTP client (for example, FileZilla) corrupts the files and it can cause the problem. For me, I uploaded manually using Cpanel interface.

Git push hangs when pushing to Github?

I had the same issue. Stop worrying and searching endless complicated solutions, just remove git and reinstall it.

sudo apt-get purge git
sudo apt-get autoremove
sudo apt-get install git

Thats it. It should work now

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

Read a variable in bash with a default value

#Script for calculating various values in MB
echo "Please enter some input: "
read input_variable
echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'

SSL: CERTIFICATE_VERIFY_FAILED with Python3

On Debian 9 I had to:

$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs

I'm not sure why, but this enviroment variable was never set.

Difference between \n and \r?

Just to add to the confusion, I've been working on a simple text editor using a TextArea element in an HTML page in a browser. In anticipation of compatibility woes with respect to CR/LF, I wrote the code to check the platform, and use whichever newline convention was applicable to the platform.

However, I discovered something interesting when checking the actual characters contained in the TextArea, via a small JavaScript function that generates the hex data corresponding to the characters.

For the test, I typed in the following text:

Hello, World[enter]

Goodbye, Cruel World[enter]

When I examined the text data, the byte sequence I obtained was this:

48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 0a 47 6f 6f 64 62 79 65 2c 20 43 72 75 65 6c 20 57 6f 72 6c 64 0a

Now, most people looking at this, and seeing 0a but no 0d bytes, would think that this output was obtained on a Unix/Linux platform. But, here's the rub: this sequence I obtained in Google Chrome on Windows 7 64-bit.

So, if you're using a TextArea element and examining the text, CHECK the output as I've done above, to make sure what actual character bytes are returned from your TextArea. I've yet to see if this differs on other platforms or other browsers, but it's worth bearing in mind if you're performing text processing via JavaScript, and you need to make that text processing platform independent.

The conventions covered in above posts apply to console output, but HTML elements, it appears, adhere to the UNIX/Linux convention. Unless someone discovers otherwise on a different platform/browser.

jQuery: Handle fallback for failed AJAX Request

You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:

function update() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000,
    success: function(data, textStatus ){
       alert('request successful');
    },
    fail: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}

EDIT I added a timeout to the $.ajax call and set it to five seconds.

JavaScript Array Push key value

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

_x000D_
_x000D_
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How to enable external request in IIS Express?

What helped me, was right clicking the 'IISExpress' icon, 'Show All applications'. Then selecting the website and I saw which aplicationhost.config it uses, and the the correction went perfectly.

IISExpress configuration

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

How to disable all <input > inside a form with jQuery?

In older versions you could use attr. As of jQuery 1.6 you should use prop instead:

$("#target :input").prop("disabled", true);

To disable all form elements inside 'target'. See :input:

Matches all input, textarea, select and button elements.

If you only want the <input> elements:

$("#target input").prop("disabled", true);

Can you put two conditions in an xslt test attribute?

From XML.com:

Like xsl:if instructions, xsl:when elements can have more elaborate contents between their start- and end-tags—for example, literal result elements, xsl:element elements, or even xsl:if and xsl:choose elements—to add to the result tree. Their test expressions can also use all the tricks and operators that the xsl:if element's test attribute can use, such as and, or, and function calls, to build more complex boolean expressions.

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

Why doesn't Java support unsigned ints?

The reason IMHO is because they are/were too lazy to implement/correct that mistake. Suggesting that C/C++ programmers does not understand unsigned, structure, union, bit flag... Is just preposterous.

Ether you were talking with a basic/bash/java programmer on the verge of beginning programming a la C, without any real knowledge this language or you are just talking out of your own mind. ;)

when you deal every day on format either from file or hardware you begin to question, what in the hell they were thinking.

A good example here would be trying to use an unsigned byte as a self rotating loop. For those of you who do not understand the last sentence, how on earth you call yourself a programmer.

DC

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

To send mail using Gmail SMTP, need to change your account setting. Login into your gmail accout then follow the link below to change your gmail account setting to send mail using your apps and program. https://www.google.com/settings/security/lesssecureapps

Note: This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)

eg -

~/myproject/mygitrepo/app/$ git diff app/TestFile.txt

should have been

~/myproject/mygitrepo/app/$ git diff TestFile.txt

"Missing return statement" within if / for / while

You have to add a return statement if the condition is false.

public String myMethod() {
    if(condition) {
        return x;
    }

//  if condition is false you HAVE TO return a string
//  you could return a string, a empty string or null
    return otherCondition;  
}

FYI:

Oracle docs for return statement

How to execute UNION without sorting? (SQL)

I notice this question gets quite a lot of views so I'll first address a question you didn't ask!

Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL with UNION. This has the effect of removing duplicates.

For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use

SELECT col1,
       col2,
       MIN(grp) AS source_group
FROM   (SELECT 1 AS grp,
               col1,
               col2
        FROM   t1
        UNION ALL
        SELECT 2 AS grp,
               col1,
               col2
        FROM   t2) AS t
GROUP  BY col1,
          col2
ORDER  BY MIN(grp),
          col1  

How do you comment out code in PowerShell?

There is a special way of inserting comments add the end of script:

....
exit 

Hi
Hello
We are comments
And not executed 

Anything after exit is not executed, and behave quite like comments.

Node Version Manager (NVM) on Windows

NVM Installation & usage on Windows

Below are the steps for NVM Installation on Windows:

NVM stands for node version manager, which will help to switch between node versions while also allowing to work with multiple npm versions.

  • Install nvm setup.
  • Use command nvm list to check list of installed node versions.
  • Example: Type nvm use 6.9.3 to switch versions.

For more info

Spring,Request method 'POST' not supported

In Jsp:

action="profile/proffiesional"

In Controller

@RequestMapping(value = "proffessional", method = RequestMethod.POST)

Spelling MisMatch !

AngularJS sorting by property

You should really improve your JSON structure to fix your problem:

$scope.testData = [
   {name:"CData", order: 1},
   {name:"BData", order: 2},
   {name:"AData", order: 3},
]

Then you could do

<li ng-repeat="test in testData | orderBy:order">...</li>

The problem, I think, is that the (key, value) variables are not available to the orderBy filter, and you should not be storing data in your keys anyways

HTTPS setup in Amazon EC2

One of the best resources I found was using let's encrypt, you do not need ELB nor cloudfront for your EC2 instance to have HTTPS, just follow the following simple instructions: let's encrypt Login to your server and follow the steps in the link.

It is also important as mentioned by others that you have port 443 opened by editing your security groups

You can view your certificate or any other website's by changing the site name in this link

Please do not forget that it is only valid for 90 days

SQL Server equivalent to MySQL enum data type?

CREATE FUNCTION ActionState_Preassigned()
RETURNS tinyint
AS
BEGIN
    RETURN 0
END

GO

CREATE FUNCTION ActionState_Unassigned()
RETURNS tinyint
AS
BEGIN
    RETURN 1
END

-- etc...

Where performance matters, still use the hard values.

Change :hover CSS properties with JavaScript

Had some same problems, used addEventListener for events "mousenter", "mouseleave":

let DOMelement = document.querySelector('CSS selector for your HTML element');

// if you want to change e.g color: 
let origColorStyle = DOMelement.style.color;

DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });

DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })

Or something else for style when cursor is above the DOMelement. DOMElement can be chosen by various ways.

How to write inside a DIV box with javascript

You can use one of the following methods:

document.getElementById('log').innerHTML = "text";

document.getElementById('log').innerText = "text";

document.getElementById('log').textContent = "text";

For Jquery:

$("#log").text("text");

$("#log").html("text");

Exit Shell Script Based on Process Exit Code

#
#------------------------------------------------------------------------------
# purpose: to run a command, log cmd output, exit on error
# usage:
# set -e; do_run_cmd_or_exit "$cmd" ; set +e
#------------------------------------------------------------------------------
do_run_cmd_or_exit(){
    cmd="$@" ;

    do_log "DEBUG running cmd or exit: \"$cmd\""
    msg=$($cmd 2>&1)
    export exit_code=$?

    # If occurred during the execution, exit with error
    error_msg="Failed to run the command:
        \"$cmd\" with the output:
        \"$msg\" !!!"

    if [ $exit_code -ne 0 ] ; then
        do_log "ERROR $msg"
        do_log "FATAL $msg"
        do_exit "$exit_code" "$error_msg"
    else
        # If no errors occurred, just log the message
        do_log "DEBUG : cmdoutput : \"$msg\""
    fi

}