Programs & Examples On #Splist

Best way to resolve file path too long exception

As the cause of the error is obvious, here's some information that should help you solve the problem:

See this MS article about Naming Files, Paths, and Namespaces

Here's a quote from the link:

Maximum Path Length Limitation In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

And a few workarounds (taken from the comments):

There are ways to solve the various problems. The basic idea of the solutions listed below is always the same: Reduce the path-length in order to have path-length + name-length < MAX_PATH. You may:

  • Share a subfolder
  • Use the commandline to assign a drive letter by means of SUBST
  • Use AddConnection under VB to assign a drive letter to a path

Getting Image from URL (Java)

Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

LocalDate to java.util.Date and vice versa simplest conversion?

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

Python equivalent of D3.js

For those who recommended pyd3, it is no longer under active development and points you to vincent. vincent is also no longer under active development and recommends using altair.

So if you want a pythonic d3, use altair.

Safely limiting Ansible playbooks to a single machine?

There's also a cute little trick that lets you specify a single host on the command line (or multiple hosts, I guess), without an intermediary inventory:

ansible-playbook -i "imac1-local," user.yml

Note the comma (,) at the end; this signals that it's a list, not a file.

Now, this won't protect you if you accidentally pass a real inventory file in, so it may not be a good solution to this specific problem. But it's a handy trick to know!

Alternative to mysql_real_escape_string without connecting to DB

From further research, I've found:

http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html

Security Fix:

An SQL-injection security hole has been found in multi-byte encoding processing. The bug was in the server, incorrectly parsing the string escaped with the mysql_real_escape_string() C API function.

This vulnerability was discovered and reported by Josh Berkus and Tom Lane as part of the inter-project security collaboration of the OSDB consortium. For more information about SQL injection, please see the following text.

Discussion. An SQL injection security hole has been found in multi-byte encoding processing. An SQL injection security hole can include a situation whereby when a user supplied data to be inserted into a database, the user might inject SQL statements into the data that the server will execute. With regards to this vulnerability, when character set-unaware escaping is used (for example, addslashes() in PHP), it is possible to bypass the escaping in some multi-byte character sets (for example, SJIS, BIG5 and GBK). As a result, a function such as addslashes() is not able to prevent SQL-injection attacks. It is impossible to fix this on the server side. The best solution is for applications to use character set-aware escaping offered by a function such mysql_real_escape_string().

However, a bug was detected in how the MySQL server parses the output of mysql_real_escape_string(). As a result, even when the character set-aware function mysql_real_escape_string() was used, SQL injection was possible. This bug has been fixed.

Workarounds. If you are unable to upgrade MySQL to a version that includes the fix for the bug in mysql_real_escape_string() parsing, but run MySQL 5.0.1 or higher, you can use the NO_BACKSLASH_ESCAPES SQL mode as a workaround. (This mode was introduced in MySQL 5.0.1.) NO_BACKSLASH_ESCAPES enables an SQL standard compatibility mode, where backslash is not considered a special character. The result will be that queries will fail.

To set this mode for the current connection, enter the following SQL statement:

SET sql_mode='NO_BACKSLASH_ESCAPES';

You can also set the mode globally for all clients:

SET GLOBAL sql_mode='NO_BACKSLASH_ESCAPES';

This SQL mode also can be enabled automatically when the server starts by using the command-line option --sql-mode=NO_BACKSLASH_ESCAPES or by setting sql-mode=NO_BACKSLASH_ESCAPES in the server option file (for example, my.cnf or my.ini, depending on your system). (Bug#8378, CVE-2006-2753)

See also Bug#8303.

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I have the same question.

You should add some dependencies in build.gradle, just looks like this

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':libcocos2dx')
    compile 'com.google.firebase:firebase-ads:11.6.0'
// the key point line
    compile 'com.google.android.gms:play-services-auth:11.6.0'
}

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

How do I calculate a trendline for a graph?

This is the way i calculated the slope: Source: http://classroom.synonym.com/calculate-trendline-2709.html

class Program
    {
        public double CalculateTrendlineSlope(List<Point> graph)
        {
            int n = graph.Count;
            double a = 0;
            double b = 0;
            double bx = 0;
            double by = 0;
            double c = 0;
            double d = 0;
            double slope = 0;

            foreach (Point point in graph)
            {
                a += point.x * point.y;
                bx = point.x;
                by = point.y;
                c += Math.Pow(point.x, 2);
                d += point.x;
            }
            a *= n;
            b = bx * by;
            c *= n;
            d = Math.Pow(d, 2);

            slope = (a - b) / (c - d);
            return slope;
        }
    }

    class Point
    {
        public double x;
        public double y;
    }

Mysql command not found in OS X 10.7

Use these two commands in your terminal

alias mysql=/usr/local/mysql/bin/mysql
mysql --user=root -p

Then it will ask you to enter password of your user pc

Enter password:

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Basically, you get connections in the Sleep state when :

  • a PHP script connects to MySQL
  • some queries are executed
  • then, the PHP script does some stuff that takes time
    • without disconnecting from the DB
  • and, finally, the PHP script ends
    • which means it disconnects from the MySQL server

So, you generally end up with many processes in a Sleep state when you have a lot of PHP processes that stay connected, without actually doing anything on the database-side.

A basic idea, so : make sure you don't have PHP processes that run for too long -- or force them to disconnect as soon as they don't need to access the database anymore.


Another thing, that I often see when there is some load on the server :

  • There are more and more requests coming to Apache
    • which means many pages to generate
  • Each PHP script, in order to generate a page, connects to the DB and does some queries
  • These queries take more and more time, as the load on the DB server increases
  • Which means more processes keep stacking up

A solution that can help is to reduce the time your queries take -- optimizing the longest ones.

How to generate classes from wsdl using Maven and wsimport?

I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure

the version management system (svn/etc.) would always notice changed sources

With git it is not true. So you can just configure jaxws-maven-plugin to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxws-maven-plugin</artifactId>
        <version>2.6</version>

    <dependencies>
      <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-fluent-api</artifactId>
        <version>3.0</version>
      </dependency>
      <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-tools</artifactId>
        <version>2.3.0</version>
      </dependency>
    </dependencies>

    <executions>
      <execution>
        <goals>
          <goal>wsimport</goal>
        </goals>
        <configuration>
          <packageName>som.path.generated</packageName>
          <xjcArgs>
            <xjcArg>-Xfluent-api</xjcArg>
          </xjcArgs>
          <verbose>true</verbose>
          <keep>true</keep> <!--used by default-->
          <sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
          <wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
          <wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
        </configuration>
      </execution>
    </executions>
  </plugin>

Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:

A a = new A()
  .withField1(value1)
  .withField2(value2);

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

Move the most recent commit(s) to a new branch with Git

Much simpler solution using git stash

Here's a far simpler solution for commits to the wrong branch. Starting on branch master that has three mistaken commits:

git reset HEAD~3
git stash
git checkout newbranch
git stash pop

When to use this?

  • If your primary purpose is to roll back master
  • You want to keep file changes
  • You don't care about the messages on the mistaken commits
  • You haven't pushed yet
  • You want this to be easy to memorize
  • You don't want complications like temporary/new branches, finding and copying commit hashes, and other headaches

What this does, by line number

  1. Undoes the last three commits (and their messages) to master, yet leaves all working files intact
  2. Stashes away all the working file changes, making the master working tree exactly equal to the HEAD~3 state
  3. Switches to an existing branch newbranch
  4. Applies the stashed changes to your working directory and clears the stash

You can now use git add and git commit as you normally would. All new commits will be added to newbranch.

What this doesn't do

  • It doesn't leave random temporary branches cluttering your tree
  • It doesn't preserve the mistaken commit messages, so you'll need to add a new commit message to this new commit
  • Update! Use up-arrow to scroll through your command buffer to reapply the prior commit with its commit message (thanks @ARK)

Goals

The OP stated the goal was to "take master back to before those commits were made" without losing changes and this solution does that.

I do this at least once a week when I accidentally make new commits to master instead of develop. Usually I have only one commit to rollback in which case using git reset HEAD^ on line 1 is a simpler way to rollback just one commit.

Don't do this if you pushed master's changes upstream

Someone else may have pulled those changes. If you are only rewriting your local master there's no impact when it's pushed upstream, but pushing a rewritten history to collaborators can cause headaches.

Are HTTP headers case-sensitive?

They are not case sensitive. In fact NodeJS web server explicitly converts them to lower-case, before making them available in the request object.

It's important to note here that all headers are represented in lower-case only, regardless of how the client actually sent them. This simplifies the task of parsing headers for whatever purpose.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

If all you need as a way to parse a dynamic string and load components by their selectors, you may also find the ngx-dynamic-hooks library useful. I initially created this as part of a personal project but didn't see anything like it around, so I polished it up a bit and made it public.

Some tidbids:

  • You can load any components into a dynamic string by their selector (or any other pattern of your choice!)
  • Inputs and outputs can be se just like in a normal template
  • Components can be nested without restrictions
  • You can pass live data from the parent component into the dynamically loaded components (and even use it to bind inputs/outputs)
  • You can control which components can load in each outlet and even which inputs/outputs you can give them
  • The library uses Angular's built-in DOMSanitizer to be safe to use even with potentially unsafe input.

Notably, it does not rely on a runtime-compiler like some of the other responses here. Because of that, you can't use template syntax. On the flipside, this means it works in both JiT and AoT-modes as well as both Ivy and the old template engine, as well as being much more secure to use in general.

See it in action in this Stackblitz.

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

Query-string encoding of a Javascript Object

I've written a package just for that: object-query-string :)

Supports nested objects, arrays, custom encoding functions etc. Lightweight & jQuery free.

// TypeScript
import { queryString } from 'object-query-string';

// Node.js
const { queryString } = require("object-query-string");

const query = queryString({
    filter: {
        brands: ["Audi"],
        models: ["A4", "A6", "A8"],
        accidentFree: true
    },
    sort: 'mileage'
});

returns

filter[brands][]=Audi&filter[models][]=A4&filter[models][]=A6&filter[models][]=A8&filter[accidentFree]=true&sort=milage

Short rot13 function - Python

A one-liner to rot13 a string S:

S.translate({a : a + (lambda x: 1 if x>=0 else -1)(77 - a) * 13 for a in range(65, 91)})

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

Is there a 'box-shadow-color' property?

A quick and copy/paste you can use for Chrome and Firefox would be: (change the stuff after the # to change the color)

-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
-border-radius: 10px;
-moz-box-shadow: 0 0 15px 5px #666;
-webkit-box-shadow: 0 0 15px 05px #666;

Matt Roberts' answer is correct for webkit browsers (safari, chrome, etc), but I thought someone out there might want a quick answer rather than be told to learn to program to make some shadows.

How do I build a graphical user interface in C++?

Since I've already been where you are right now, I think I can "answer" you.

The fact is there is no easy way to make a GUI. GUI's are highly dependent on platform and OS specific code, that's why you should start reading your target platform/OS documentation on window management APIs. The good thing is: there are plenty of libraries that address these limitations and abstract architecture differences into a single multi-platform API. Those suggested before, GTK and Qt, are some of these libraries.

But even these are a little too complicated, since lots of new concepts, data types, namespaces and classes are introduced, all at once. For this reason, they use to come bundled with some GUI WYSIWYG editor. They pretty much make programming software with GUIs possible.

To sum it up, there are also non free "environments" for GUI development such as Visual Studio from Microsoft. For those with Delphi experience backgrounds, Visual Studio may be more familiar. There are also free alternatives to the full Visual Studio environment supplied from Microsoft: Visual Studio Express, which is more than enough for starting on GUI development.

Get list of passed arguments in Windows batch script (.bat)

You can use For Commad,to get list of Arg.

Help : For /? Help : Setlocal /?

Here is my way =

@echo off
::For Run Use This = cmd /c ""Args.cmd" Hello USER Scientist etc"
setlocal EnableDelayedExpansion
set /a Count=0
for %%I IN (%*) DO (
 Echo Arg_!Count! = %%I
 set /a Count+=1 
)
Echo Count Of Args = !Count!
Endlocal

Do not need Shift command.

Custom ImageView with drop shadow

I've built upon the answer above - https://stackoverflow.com/a/11155031/2060486 - to create a shadow around ALL sides..

 private static final int GRAY_COLOR_FOR_SHADE = Color.argb(50, 79, 79, 79);

// this method takes a bitmap and draws around it 4 rectangles with gradient to create a
// shadow effect.
public static Bitmap addShadowToBitmap(Bitmap origBitmap) {
    int shadowThickness = 13; // can be adjusted as needed
    int bmpOriginalWidth = origBitmap.getWidth();
    int bmpOriginalHeight = origBitmap.getHeight();
    int bigW = bmpOriginalWidth + shadowThickness * 2; // getting dimensions for a bigger bitmap with margins
    int bigH = bmpOriginalHeight + shadowThickness * 2;
    Bitmap containerBitmap = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.ARGB_8888);
    Bitmap copyOfOrigBitmap = Bitmap.createScaledBitmap(origBitmap, bmpOriginalWidth, bmpOriginalHeight, false);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas canvas = new Canvas(containerBitmap); // drawing the shades on the bigger bitmap
    //right shade - direction of gradient is positive x (width)
    Shader rightShader = new LinearGradient(bmpOriginalWidth, 0, bigW, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(rightShader);
    canvas.drawRect(bigW - shadowThickness, shadowThickness, bigW, bigH - shadowThickness, paint);
    //bottom shade - direction is positive y (height)
    Shader bottomShader = new LinearGradient(0, bmpOriginalHeight, 0, bigH, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(bottomShader);
    canvas.drawRect(shadowThickness, bigH - shadowThickness, bigW - shadowThickness, bigH, paint);
    //left shade - direction is negative x
    Shader leftShader = new LinearGradient(shadowThickness, 0, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(leftShader);
    canvas.drawRect(0, shadowThickness, shadowThickness, bigH - shadowThickness, paint);
    //top shade - direction is negative y
    Shader topShader = new LinearGradient(0, shadowThickness, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(topShader);
    canvas.drawRect(shadowThickness, 0, bigW - shadowThickness, shadowThickness, paint);
    // starting to draw bitmap not from 0,0 to get margins for shade rectangles
    canvas.drawBitmap(copyOfOrigBitmap, shadowThickness, shadowThickness, null);
    return containerBitmap;
}

Change the color in the const as you see fit.

Get records with max value for each group of grouped SQL results

Improving axiac's solution to avoid selecting multiple rows per group while also allowing for use of indexes

SELECT o.*
FROM `Persons` o 
  LEFT JOIN `Persons` b 
      ON o.Group = b.Group AND o.Age < b.Age
  LEFT JOIN `Persons` c 
      ON o.Group = c.Group AND o.Age = c.Age and o.id < c.id
WHERE b.Age is NULL and c.id is null

SyntaxError: unexpected EOF while parsing

Here is one of my mistakes that produced this exception: I had a try block without any except or finally blocks. This will not work:

try:
    lets_do_something_beneficial()

To fix this, add an except or finally block:

try:
    lets_do_something_beneficial()
finally:
    lets_go_to_sleep()

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

You can think it as a CSS style visibility & display.

<div style="visibility:visible; display:block">
    This is View.VISIBLE : Content is displayed normally.
</div>

<div style="visibility:hidden; display:block">
    This is View.INVISIBLE : Content is not displayed, but div still takes up place, but empty.
</div>

<div style="display:none">
    This is View.GONE : Container div is not shown, you can say the content is not displayed.
</div>

Python: count repeated elements in the list

lst = ["a", "b", "a", "c", "c", "a", "c"]
temp=set(lst)
result={}
for i in temp:
    result[i]=lst.count(i)
print result

Output:

{'a': 3, 'c': 3, 'b': 1}

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

json_encode/json_decode - returns stdClass instead of Array in PHP

To answer the actual question:

Why does PHP turn the JSON Object into a class?

Take a closer look at the output of the encoded JSON, I've extended the example the OP is giving a little bit:

$array = array(
    'stuff' => 'things',
    'things' => array(
        'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
    )
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}

The JSON format was derived from the same standard as JavaScript (ECMAScript Programming Language Standard) and if you would look at the format it looks like JavaScript. It is a JSON object ({} = object) having a property "stuff" with value "things" and has a property "things" with it's value being an array of strings ([] = array).

JSON (as JavaScript) doesn't know associative arrays only indexed arrays. So when JSON encoding a PHP associative array, this will result in a JSON string containing this array as an "object".

Now we're decoding the JSON again using json_decode($arrayEncoded). The decode function doesn't know where this JSON string originated from (a PHP array) so it is decoding into an unknown object, which is stdClass in PHP. As you will see, the "things" array of strings WILL decode into an indexed PHP array.

Also see:


Thanks to https://www.randomlists.com/things for the 'things'

Facebook API "This app is in development mode"

  • Development mode is for testing
  • Go to https://developers.facebook.com/apps, then App Review -> Select No for Your app is in development and unavailable to the public
  • Go to Roles -> Testers, enter the Facebook user Id of the users you want to enable testing

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

What is so bad about singletons?

Vince Huston has these criteria, which seem reasonable to me:

Singleton should be considered only if all three of the following criteria are satisfied:

  • Ownership of the single instance cannot be reasonably assigned
  • Lazy initialization is desirable
  • Global access is not otherwise provided for

If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting.

How to Sort Date in descending order From Arraylist Date in android?

Just add like this in case 1: like this

 case 0:
     list = DBAdpter.requestUserData(assosiatetoken);
     Collections.sort(list, byDate);
     for (int i = 0; i < list.size(); i++) {
         if (list.get(i).lastModifiedDate != null) {
             lv.setAdapter(new MyListAdapter(
                     getApplicationContext(), list));
         }
     }
     break;

and put this method at end of the your class

static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

    public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = sdf.parse(ord1.lastModifiedDate);
            d2 = sdf.parse(ord2.lastModifiedDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
    //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
    }
};

Differences between Lodash and Underscore.js

I am not sure if that is what OP meant, but I came across this question because I was searching for a list of issues I have to keep in mind when migrating from Underscore.js to Lodash.

I would really appreciate if someone posted an article with a complete list of such differences. Let me start with the things I've learned the hard way (that is, things which made my code explode on production:/):

  • _.flatten in Underscore.js is deep by default, and you have to pass true as second argument to make it shallow. In Lodash it is shallow by default and passing true as second argument will make it deep! :)
  • _.last in Underscore.js accepts a second argument which tells how many elements you want. In Lodash there is no such option. You can emulate this with .slice
  • _.first (same issue)
  • _.template in Underscore.js can be used in many ways, one of which is providing the template string and data and getting HTML back (or at least that's how it worked some time ago). In Lodash you receive a function which you should then feed with the data.
  • _(something).map(foo) works in Underscore.js, but in Lodash I had to rewrite it to _.map(something,foo). Perhaps that was just a TypeScript-issue.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

Maybe not very elegant, but it does the job:

exec(open("script.py").read())

How to change an Android app's name?

It depends what you want to do. I personally wanted to rename my project so it didn't say MainActivity at the top of the app and underneath the icon on my phone menu.

To do this I went into the Android Manifest.xml file and edited

<activity
        android:name=".MainActitivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

And edited the android:name=".Mynewname" and then edited the string title_activity_main in the strings.xml file to match the name.

Hope that helps!

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Mock functions in Go

If you change your function definition to use a variable instead:

var get_page = func(url string) string {
    ...
}

You can override it in your tests:

func TestDownloader(t *testing.T) {
    get_page = func(url string) string {
        if url != "expected" {
            t.Fatal("good message")
        }
        return "something"
    }
    downloader()
}

Careful though, your other tests might fail if they test the functionality of the function you override!

The Go authors use this pattern in the Go standard library to insert test hooks into code to make things easier to test:

Batch script loop

I have 2 answers Methods 1: Insert Javascript into Batch

@if (@a==@b) @end /*

:: batch portion

@ECHO OFF

cscript /e:jscript "%~f0"


:: JScript portion */

Input Javascript here

( I don't know much about JavaScript )

Method 2: Loop in Batch

   @echo off
    set loopcount=5
    :loop
    echo Hello World!
    set /a loopcount=loopcount-1
    if %loopcount%==0 goto exitloop
    goto loop
    :exitloop
    pause

(Thanks FluorescentGreen5)

AWK: Access captured group from line pattern

This is something I need all the time so I created a bash function for it. It's based on glenn jackman's answer.

Definition

Add this to your .bash_profile etc.

function regex { gawk 'match($0,/'$1'/, ary) {print ary['${2:-'0'}']}'; }

Usage

Capture regex for each line in file

$ cat filename | regex '.*'

Capture 1st regex capture group for each line in file

$ cat filename | regex '(.*)' 1

Add padding on view programmatically

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

Xcode variables

The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.

How to disable/enable select field using jQuery?

Just simply use:

var update_pizza = function () {
     $("#pizza_kind").prop("disabled", !$('#pizza').prop('checked'));
};

update_pizza();
$("#pizza").change(update_pizza);

DEMO ?

Adding values to a C# array

Based on the answer of Thracx (I don't have enough points to answer):

public static T[] Add<T>(this T[] target, params T[] items)
    {
        // Validate the parameters
        if (target == null) {
            target = new T[] { };
        }
        if (items== null) {
            items = new T[] { };
        }

        // Join the arrays
        T[] result = new T[target.Length + items.Length];
        target.CopyTo(result, 0);
        items.CopyTo(result, target.Length);
        return result;
    }

This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.

Assign format of DateTime with data annotations?

Use EditorFor rather than TextBoxFor

SQL Server 2008- Get table constraints

You Can Get With This Query

Unique Constraint,

Default Constraint With Value,

Foreign Key With referenced Table And Column

And Primary Key Constraint.

Select C.*, (Select definition From sys.default_constraints Where object_id = C.object_id) As dk_definition,
(Select definition From sys.check_constraints Where object_id = C.object_id) As ck_definition,
(Select name From sys.objects Where object_id = D.referenced_object_id) As fk_table,
(Select name From sys.columns Where column_id = D.parent_column_id And object_id = D.parent_object_id) As fk_col
From sys.objects As C
Left Join (Select * From sys.foreign_key_columns) As D On D.constraint_object_id = C.object_id 
Where C.parent_object_id = (Select object_id From sys.objects Where type = 'U'
And name = 'Table Name Here');

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

For IntelliJ 2019, JDK 13 and gRPC:

Intellij IDEA -> Preferences -> Build, Execution, Deployment -> Build Tools -> Gradle -> Gradle JVM

and Select correct version.

you might also have to adding below line in your build.gradle dependencies

compileOnly group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'

Error while trying to run project: Unable to start program. Cannot find the file specified

For me it was the virus scanner not liking the fact I have in my exe filename multiple periods.

i.e

project.class.console.exe <- won't run

console.exe <- will run

Hope it helps.

Does C# have an equivalent to JavaScript's encodeURIComponent()?

For a Windows Store App, you won't have HttpUtility. Instead, you have:

For an URI, before the '?':

  • System.Uri.EscapeUriString("example.com/Stack Overflow++?")
    • -> "example.com/Stack%20Overflow++?"

For an URI query name or value, after the '?':

  • System.Uri.EscapeDataString("Stack Overflow++")
    • -> "Stack%20Overflow%2B%2B"

For a x-www-form-urlencoded query name or value, in a POST content:

  • System.Net.WebUtility.UrlEncode("Stack Overflow++")
    • -> "Stack+Overflow%2B%2B"

A cycle was detected in the build path of project xxx - Build Path Problem

This could happen when you have several projects that include each other in JAR form. What I did was remove all libraries and project dependencies on buildpath, for all projects. Then, one at a time, I added the project dependencies on the Project Tab, but only the ones needed. This is because you can add a project which in turn has itself referenced or another project which is referencing some other project with this self-referencing issue.

This resolved my issue.

XSLT string replace

I keep hitting this answer. But none of them list the easiest solution for xsltproc (and probably most XSLT 1.0 processors):

  1. Add the exslt strings name to the stylesheet, i.e.:
<xsl:stylesheet
  version="1.0"
  xmlns:str="http://exslt.org/strings"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  1. Then use it like:
<xsl:value-of select="str:replace(., ' ', '')"/>

When should you use constexpr capability in C++11?

Your basic example serves he same argument as that of constants themselves. Why use

static const int x = 5;
int arr[x];

over

int arr[5];

Because it's way more maintainable. Using constexpr is much, much faster to write and read than existing metaprogramming techniques.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

The above answer only adds the sqljdbc4.jar to the local repository. As a result, when creating the final project jar for distribution, sqljdbc4 will again be missing as was indicated in the comment by @Tony regarding runtime error.

Microsoft (and Oracle and other third party providers) restrict the distribution of their software as per the ENU/EULA. Therefore those software modules do not get added in Maven produced jars for distribution. There are hacks to get around it (such as providing the location of the 3rd party jar file at runtime), but as a developer you must be careful about violating the licensing.

A better approach for jdbc connectors/drivers is to use jTDS, which is compatible to most DBMS's, more reliable, faster (as per benchmarks), and distributed under GNU license. It will make your life much easier to use this than trying to pound the square peg into the round hole following any of the other techniques above.

Use a JSON array with objects with javascript

This is your dataArray:

[
   {
      "id":28,
      "Title":"Sweden"
   },
   {
      "id":56,
      "Title":"USA"
   },
   {
      "id":89,
      "Title":"England"
   }
]

Then parseJson can be used:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
    var ID = this.id;
    var TITLE = this.Title;
});

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
{
    @Html.Partial("_partialView", planVM)
}

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
<div>
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>
</div>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
    @Html.EditorForModel()
</div>
}

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

When should I use the new keyword in C++?

If you are writing in C++ you are probably writing for performance. Using new and the free store is much slower than using the stack (especially when using threads) so only use it when you need it.

As others have said, you need new when your object needs to live outside the function or object scope, the object is really large or when you don't know the size of an array at compile time.

Also, try to avoid ever using delete. Wrap your new into a smart pointer instead. Let the smart pointer call delete for you.

There are some cases where a smart pointer isn't smart. Never store std::auto_ptr<> inside a STL container. It will delete the pointer too soon because of copy operations inside the container. Another case is when you have a really large STL container of pointers to objects. boost::shared_ptr<> will have a ton of speed overhead as it bumps the reference counts up and down. The better way to go in that case is to put the STL container into another object and give that object a destructor that will call delete on every pointer in the container.

Get total of Pandas column

You should use sum:

Total = df['MyColumn'].sum()
print (Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.

Parsing string as JSON with single quotes?

The JSON standard requires double quotes and will not accept single quotes, nor will the parser.

If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str.replace(/'/g, '"') and you should end up with valid JSON.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

I already have the same problem and I just change as below:

@XmlRootElement -> @XmlRootElement(name="Group")

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

The simplest and most fun way (imo) is glob

foreach (glob("*.*") as $filename) {
    echo $filename."<br />";
}

But the standard way is to use the directory functions.

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: .".$file."<br />";
        }
        closedir($dh);
    }
}

There are also the SPL DirectoryIterator methods. If you are interested

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

How can I create persistent cookies in ASP.NET?

//add cookie

var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2); 
Response.Cookies.Add(panelIdCookie);

//read cookie

    var httpCookie = Request.Cookies["panelIdCookie"];
                if (httpCookie != null)
                {
                    panelId = Convert.ToInt32(httpCookie["panelId"]);
                }

Python 3 string.join() equivalent?

There are method join for string objects:

".".join(("a","b","c"))

Why does .json() return a promise?

Why does response.json return a promise?

Because you receive the response as soon as all headers have arrived. Calling .json() gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.

Why do I get the value if I return the promise from the then handler?

Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.

You can use

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.

Lock screen orientation (Android)

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

How do I loop through a date range?

I have a Range class in MiscUtil which you could find useful. Combined with the various extension methods, you could do:

foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
                                   .Step(DayInterval.Days())
{
    // Do something with the date
}

(You may or may not want to exclude the end - I just thought I'd provide it as an example.)

This is basically a ready-rolled (and more general-purpose) form of mquander's solution.

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

How do you get the logical xor of two variables in Python?

You can always use the definition of xor to compute it from other logical operations:

(a and not b) or (not a and b)

But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is:

bool(a) ^ bool(b)

The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since bool is just a subclass of int, but is implemented to only have the values 0 and 1. And logical xor is equivalent to bitwise xor when the domain is restricted to 0 and 1.

So the logical_xor function would be implemented like:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

Credit to Nick Coghlan on the Python-3000 mailing list.

Correct Way to Load Assembly, Find Class and Call Run() Method

When you build your assembly, you can call AssemblyBuilder.SetEntryPoint, and then get it back from the Assembly.EntryPoint property to invoke it.

Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main:

static void Run(string[] args)

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

Format Instant to String

Time Zone

To format an Instant a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.

The time-zone can be added directly to the formatter using withZone().

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

If you specifically want an ISO-8601 format with no explicit time-zone (as the OP asked), with the time-zone implicitly UTC, you need

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

Generating String

Now use that formatter to generate the String representation of your Instant.

Instant instant = Instant.now();
String output = formatter.format( instant );

Dump to console.

System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );

When run.

formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34

How to submit http form using C#

Here is a sample script that I recently used in a Gateway POST transaction that receives a GET response. Are you using this in a custom C# form? Whatever your purpose, just replace the String fields (username, password, etc.) with the parameters from your form.

private String readHtmlPage(string url)
   {

    //setup some variables

    String username  = "demo";
    String password  = "password";
    String firstname = "John";
    String lastname  = "Smith";

    //setup some variables end

      String result = "";
      String strPost = "username="+username+"&password="+password+"&firstname="+firstname+"&lastname="+lastname;
      StreamWriter myWriter = null;

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
      objRequest.Method = "POST";
      objRequest.ContentLength = strPost.Length;
      objRequest.ContentType = "application/x-www-form-urlencoded";

      try
      {
         myWriter = new StreamWriter(objRequest.GetRequestStream());
         myWriter.Write(strPost);
      }
      catch (Exception e) 
      {
         return e.Message;
      }
      finally {
         myWriter.Close();
      }

      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
      using (StreamReader sr = 
         new StreamReader(objResponse.GetResponseStream()) )
      {
         result = sr.ReadToEnd();

         // Close and clean up the StreamReader
         sr.Close();
      }
      return result;
   } 

awk without printing newline

I guess many people are entering in this question looking for a way to avoid the new line in awk. Thus, I am going to offer a solution to just that, since the answer to the specific context was already solved!

In awk, print automatically inserts a ORS after printing. ORS stands for "output record separator" and defaults to the new line. So whenever you say print "hi" awk prints "hi" + new line.

This can be changed in two different ways: using an empty ORS or using printf.

Using an empty ORS

awk -v ORS= '1' <<< "hello
man"

This returns "helloman", all together.

The problem here is that not all awks accept setting an empty ORS, so you probably have to set another record separator.

awk -v ORS="-" '{print ...}' file

For example:

awk -v ORS="-" '1' <<< "hello
man"

Returns "hello-man-".

Using printf (preferable)

While print attaches ORS after the record, printf does not. Thus, printf "hello" just prints "hello", nothing else.

$ awk 'BEGIN{print "hello"; print "bye"}'
hello
bye
$ awk 'BEGIN{printf "hello"; printf "bye"}'
hellobye

Finally, note that in general this misses a final new line, so that the shell prompt will be in the same line as the last line of the output. To clean this, use END {print ""} so a new line will be printed after all the processing.

$ seq 5 | awk '{printf "%s", $0}'
12345$
#    ^ prompt here

$ seq 5 | awk '{printf "%s", $0} END {print ""}'
12345

Pretty Printing JSON with React

const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")

const JSONDisplayer = ({children}) => (
    <div>
        <pre>{getJsonIndented(children)}</pre>
    </div>
)

Then you can easily use it:

const Demo = (props) => {
   ....
   return <JSONDisplayer>{someObj}<JSONDisplayer>
}

Batch file to run a command in cmd within a directory

CMD.EXE will not execute internal commands contained inside the string. Only actual files can be launched with that string.

You will need to actually call a batch file to do what you want.

BAT1.bat

start cmd.exe /k bat2.bat

BAT2.bat

cd C:\activiti-5.9\setup
ant demo.start

You may want to create a folder called BAT, and add it's location to your path. So if you create C:\BAT, add C:\BAT\; to the path. The path is located at:

    click -> Start -> right-click Computer -> Properties ->
    click -> Avanced System Settings -> Environment Variables
   select -> Path (From either list. User Variables are specific to 
                   your profile, System Variables are, duh, system-wide.)
    Click -> Edit
Press the -> the [END] or [HOME] key.
     Type -> C:\BAT\;
    Click -> OK -> OK

Now place all your batch files in C:\BAT and they will be found, regardless of the current directory.

What is the purpose of meshgrid in Python / NumPy?

The purpose of meshgrid is to create a rectangular grid out of an array of x values and an array of y values.

So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a rectangular grid, we need every combination of the x and y points.

This is going to be 25 points, right? So if we wanted to create an x and y array for all of these points, we could do the following.

x[0,0] = 0    y[0,0] = 0
x[0,1] = 1    y[0,1] = 0
x[0,2] = 2    y[0,2] = 0
x[0,3] = 3    y[0,3] = 0
x[0,4] = 4    y[0,4] = 0
x[1,0] = 0    y[1,0] = 1
x[1,1] = 1    y[1,1] = 1
...
x[4,3] = 3    y[4,3] = 4
x[4,4] = 4    y[4,4] = 4

This would result in the following x and y matrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.

x =   0 1 2 3 4        y =   0 0 0 0 0
      0 1 2 3 4              1 1 1 1 1
      0 1 2 3 4              2 2 2 2 2
      0 1 2 3 4              3 3 3 3 3
      0 1 2 3 4              4 4 4 4 4

We can then plot these to verify that they are a grid:

plt.plot(x,y, marker='.', color='k', linestyle='none')

enter image description here

Obviously, this gets very tedious especially for large ranges of x and y. Instead, meshgrid can actually generate this for us: all we have to specify are the unique x and y values.

xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);

Now, when we call meshgrid, we get the previous output automatically.

xx, yy = np.meshgrid(xvalues, yvalues)

plt.plot(xx, yy, marker='.', color='k', linestyle='none')

enter image description here

Creation of these rectangular grids is useful for a number of tasks. In the example that you have provided in your post, it is simply a way to sample a function (sin(x**2 + y**2) / (x**2 + y**2)) over a range of values for x and y.

Because this function has been sampled on a rectangular grid, the function can now be visualized as an "image".

enter image description here

Additionally, the result can now be passed to functions which expect data on rectangular grid (i.e. contourf)

Rails params explained?

Params contains the following three groups of parameters:

  1. User supplied parameters
    • GET (http://domain.com/url?param1=value1&param2=value2 will set params[:param1] and params[:param2])
    • POST (e.g. JSON, XML will automatically be parsed and stored in params)
    • Note: By default, Rails duplicates the user supplied parameters and stores them in params[:user] if in UsersController, can be changed with wrap_parameters setting
  2. Routing parameters
    • match '/user/:id' in routes.rb will set params[:id]
  3. Default parameters
    • params[:controller] and params[:action] is always available and contains the current controller and action

MSVCP140.dll missing

Your friend's PC is missing the runtime support DLLs for your program:

SQL Error: ORA-00913: too many values

For me this works perfect

insert into oehr.employees select * from employees where employee_id=99

I am not sure why you get error. The nature of the error code you have produced is the columns didn't match.

One good approach will be to use the answer @Parodo specified

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

debug1: identity file /Users/tudouya/.ssh/vm/vm_id_rsa.pub type 1

It appears that you're trying to use the wrong key file. The file with the ".pub" extension contains the public portion of the key. The corresponding file without the ".pub" extension contains the private part of the key. When you run an ssh client to connect to a remote server, you have to provide the private key file to the ssh client.

You probably have a line in the your .ssh/config file (or /etc/ssh_config) which looks like this:

IdentityFile .../.ssh/vm/vm_id_rsa.pub

You need to remove the ".pub" extension from the filename:

IdentityFile .../.ssh/vm/vm_id_rsa

Parse v. TryParse

If the string can not be converted to an integer, then

  • int.Parse() will throw an exception
  • int.TryParse() will return false (but not throw an exception)

Test process.env with Jest

Jest's setupFiles is the proper way to handle this, and you need not install dotenv, nor use an .env file at all, to make it work.

jest.config.js:

module.exports = {
  setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};

.jest/setEnvVars.js:

process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'

That's it.

sql how to cast a select query

And when you use a case :

CASE
WHEN TB1.COD IS NULL THEN
    TB1.COD || ' - ' || TB1.NAME
ELSE
    TB1.COD || ' - ' || TB1.NAME || ' - ' || TB.NM_TABELAFRETE
END AS NR_FRETE,

How to change Visual Studio 2012,2013 or 2015 License Key?

I had the same problem and wanted to change the product key to another. Unfortunate it's not as easy as it was on VS2010.

The following steps work:

  • Remove the registry key containing the license information: HKEY_CLASSES_ROOT\Licenses\77550D6B-6352-4E77-9DA3-537419DF564B

  • If you can't find the key, use sysinternals ProcessMonitor to check the registry access of VS2012 to locate the correct key which is always in HKEY_CLASSES_ROOT\Licenses

  • After you remove this key, VS2012 will tell you that it's license information is incorrect. Go to "Programs and features" and repair VS2012.

  • After the repair, VS2012 is reverted to a 30 day trial and you can enter a new product key. This could also be used to stay in a trial version loop and never enter a producy key.

Is Fortran easier to optimize than C for heavy calculations?

Generally FORTRAN is slower than C. C can use hardware level pointers allowing the programmer to hand-optimize. FORTRAN (in most cases) doesn't have access to hardware memory addressing hacks. (VAX FORTRAN is another story.) I've used FORTRAN on and off since the '70's. (Really.)

However, starting in the 90's FORTRAN has evolved to include specific language constructs that can be optimized into inherently parallel algorithms that can really scream on a multi-core processor. For example, automatic Vectorizing allows multiple processors to handle each element in a vector of data concurrently. 16 processors -- 16 element vector -- processing takes 1/16th the time.

In C, you have to manage your own threads and design your algorithm carefully for multi-processing, and then use a bunch of API calls to make sure that the parallelism happens properly.

In FORTRAN, you only have to design your algorithm carefully for multi-processing. The compiler and run-time can handle the rest for you.

You can read a little about High Performance Fortran, but you find a lot of dead links. You're better off reading about Parallel Programming (like OpenMP.org) and how FORTRAN supports that.

How do I check for a network connection?

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <summary>
    /// Indicates whether any network connection is available
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable()
    {
        return IsNetworkAvailable(0);
    }

    /// <summary>
    /// Indicates whether any network connection is available.
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable(long minimumSpeed)
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            // discard because of standard reasons
            if ((ni.OperationalStatus != OperationalStatus.Up) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
                continue;

            // this allow to filter modems, serial, etc.
            // I use 10000000 as a minimum speed for most cases
            if (ni.Speed < minimumSpeed)
                continue;

            // discard virtual cards (virtual box, virtual pc, etc.)
            if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
                (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
                continue;

            // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
            if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
                continue;

            return true;
        }
        return false;
    }

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

How to embed fonts in HTML?

No, there isn't a decent solution for body type, unless you're willing to cater only to those with bleeding-edge browsers.

Microsoft has WEFT, their own proprietary font-embedding technology, but I haven't heard it talked about in years, and I know no one who uses it.

I get by with sIFR for display type (headlines, titles of blog posts, etc.) and using one of the less-worn-out web-safe fonts for body type (like Trebuchet MS). If you're bored with all the web-safe fonts, you're probably defining the term too narrowly — look at this matrix of stock fonts that ship with major OSes and chances are you'll be able to find a font cascade that will catch nearly all web users.

For instance: font-family: "Lucida Grande", "Verdana", sans-serif is a common font cascade; OS X comes with Lucida Grande, but those with Windows will get Verdana, a web-safe font with letters of similar size and shape to Lucida Grande. Linux users will also get Verdana if they've installed the web-safe fonts package that exists in most distros' package managers, or else they'll fall back to an ordinary sans-serif.

Detecting when the 'back' button is pressed on a navbar

The best way is to use the UINavigationController delegate methods

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

Using this you can know what controller is showing the UINavigationController.

if ([viewController isKindOfClass:[HomeController class]]) {
    NSLog(@"Show home controller");
}

What is the "hasClass" function with plain JavaScript?

_x000D_
_x000D_
// 1. Use if for see that classes:_x000D_
_x000D_
if (document.querySelector(".section-name").classList.contains("section-filter")) {_x000D_
  alert("Grid section");_x000D_
  // code..._x000D_
}
_x000D_
<!--2. Add a class in the .html:-->_x000D_
_x000D_
<div class="section-name section-filter">...</div>
_x000D_
_x000D_
_x000D_

How to recover MySQL database from .myd, .myi, .frm files

For those that have Windows XP and have MySQL server 5.5 installed - the location for the database is C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.5\data, unless you changed the location within the MySql Workbench installation GUI.

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

How do I copy a string to the clipboard?

Code snippet to copy the clipboard:

Create a wrapper Python code in a module named (clipboard.py):

import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Clipboard
def setText(text):
    Clipboard.SetText(text)

def getText():
    return Clipboard.GetText()

Then import the above module into your code.

import io
import clipboard
code = clipboard.getText()
print code
code = "abcd"
clipboard.setText(code)

I must give credit to the blog post Clipboard Access in IronPython.

wamp server does not start: Windows 7, 64Bit

You can open the Windows event viewer to try to get more information about the errors : in the "Application" section of the Windows logs, there is a good chance you will find error messages from Apache. (At least I found what was wrong in my case there !)

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:

easy_install

aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc

aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/

aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).

Problem:

  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

How to sort alphabetically while ignoring case sensitive?

I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.

You should almost always use a Collator for dictionary based sorting.

For case insensitive collator searching for the English language you do the following:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);

Last segment of URL in jquery

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));

Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.

If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);

Is it possible to pass parameters programmatically in a Microsoft Access update query?

I just tested this and it works in Access 2010.

Say you have a SELECT query with parameters:

PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));

You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].

Now you create an UPDATE query based on that query:

UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));

You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].

You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:

Sub paramTest()
    Dim qdf As DAO.QueryDef
    Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
    qdf!startID = 1  ' specify
    qdf!endID = 2    '     parameters
    qdf.Execute
    Set qdf = Nothing
End Sub

Python List vs. Array - when to use?

The standard library arrays are useful for binary I/O, such as translating a list of ints to a string to write to, say, a wave file. That said, as many have already noted, if you're going to do any real work then you should consider using NumPy.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

i Just enabled TCP/IP,VIA,Named Pipes in Sql Server Configuration manager , My problem got solved refer this for more info Resolving Named Pipes Error 40

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

Exit single-user mode

SSMS in general uses several connections to the database behind the scenes.

You will need to kill these connections before changing the access mode.

First, make sure the object explorer is pointed to a system database like master.

Second, execute a sp_who2 and find all the connections to database 'my_db'. Kill all the connections by doing KILL { session id } where session id is the SPID listed by sp_who2.

Third, open a new query window.

Execute the following code.

-- Start in master
USE MASTER;

-- Add users
ALTER DATABASE [my_db] SET MULTI_USER
GO

See my blog article on managing database files. This was written for moving files, but user management is the same.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I think this means that

  • You are using JDK9 or later
  • Your project uses maven-compiler-plugin with an old version which defaults to Java 5.

You have three options to solve this

  1. Downgrade to JDK7 or JDK8 (meh)
  2. Use maven-compiler-plugin version or later, because

    NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6 See https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#target

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
    </plugin>
    
  3. Indicate to the maven-compiler-plugin to use source level 6 and target 6 (or later).

    Best practice recommended by https://maven.apache.org/plugins/maven-compiler-plugin/

    Also note that at present the default source setting is 1.6 and the default target setting is 1.6, independently of the JDK you run Maven with. You are highly encouraged to change these defaults by setting source and target as described in Setting the -source and -target of the Java Compiler.

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
    </plugin>
    

    or use

    <properties>
      <maven.compiler.source>1.6</maven.compiler.source>
      <maven.compiler.target>1.6</maven.compiler.target>
    </properties>
    

self referential struct definition?

Another convenient method is to pre-typedef the structure with,structure tag as:

//declare new type 'Node', as same as struct tag
typedef struct Node Node;
//struct with structure tag 'Node'
struct Node
{
int data;
//pointer to structure with custom type as same as struct tag
Node *nextNode;
};
//another pointer of custom type 'Node', same as struct tag
Node *node;

How do I make calls to a REST API using C#?

Since you are using Visual Studio 11 Beta, you will want to use the latest and greatest. The new Web API contains classes for this.

See HttpClient: http://wcf.codeplex.com/wikipage?title=WCF%20HTTP

Hive Alter table change Column Name

Change Column Name/Type/Position/Comment:

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

Example:

CREATE TABLE test_change (a int, b int, c int);

// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.

df.sample(frac=1)

How to reset a select element with jQuery

In your case (and in most use cases I have seen), all you need is:

$("#baba").val("");

Demo.

Reading file contents on the client-side in javascript in various browsers

Edited to add information about the File API

Since I originally wrote this answer, the File API has been proposed as a standard and implemented in most browsers (as of IE 10, which added support for FileReader API described here, though not yet the File API). The API is a bit more complicated than the older Mozilla API, as it is designed to support asynchronous reading of files, better support for binary files and decoding of different text encodings. There is some documentation available on the Mozilla Developer Network as well as various examples online. You would use it as follows:

var file = document.getElementById("fileForUpload").files[0];
if (file) {
    var reader = new FileReader();
    reader.readAsText(file, "UTF-8");
    reader.onload = function (evt) {
        document.getElementById("fileContents").innerHTML = evt.target.result;
    }
    reader.onerror = function (evt) {
        document.getElementById("fileContents").innerHTML = "error reading file";
    }
}

Original answer

There does not appear to be a way to do this in WebKit (thus, Safari and Chrome). The only keys that a File object has are fileName and fileSize. According to the commit message for the File and FileList support, these are inspired by Mozilla's File object, but they appear to support only a subset of the features.

If you would like to change this, you could always send a patch to the WebKit project. Another possibility would be to propose the Mozilla API for inclusion in HTML 5; the WHATWG mailing list is probably the best place to do that. If you do that, then it is much more likely that there will be a cross-browser way to do this, at least in a couple years time. Of course, submitting either a patch or a proposal for inclusion to HTML 5 does mean some work defending the idea, but the fact that Firefox already implements it gives you something to start with.

How to use Redirect in the new react-router-dom of Reactjs

you can write a hoc for this purpose and write a method call redirect, here is the code:

import React, {useState} from 'react';
import {Redirect} from "react-router-dom";

const RedirectHoc = (WrappedComponent) => () => {
    const [routName, setRoutName] = useState("");
    const redirect = (to) => {
        setRoutName(to);
    };


    if (routName) {
        return <Redirect to={"/" + routName}/>
    }
    return (
        <>
            <WrappedComponent redirect={redirect}/>
        </>
    );
};

export default RedirectHoc;

How to overplot a line on a scatter plot in python?

import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

# Sample data
x = np.arange(10)
y = 5 * x + 10

# Fit with polyfit
b, m = polyfit(x, y, 1)

plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show()

enter image description here

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

a href link for entire div in HTML/CSS

What I would do is put a span inside the <a> tag, set the span to block, and add size to the span, or just apply the styling to the <a> tag. Definitely handle the positioning in the <a> tag style. Add an onclick event to the a where JavaScript will catch the event, then return false at the end of the JavaScript event to prevent default action of the href and bubbling of the click. This works in cases with or without JavaScript enabled, and any AJAX can be handled in the Javascript listener.

If you're using jQuery, you can use this as your listener and omit the onclick in the a tag.

$('#idofdiv').live("click", function(e) {
    //add stuff here
    e.preventDefault; //or use return false
}); 

this allows you to attach listeners to any changed elements as necessary.

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

Compare two columns using pandas

One way is to use a Boolean series to index the column df['one']. This gives you a new column where the True entries have the same value as the same row as df['one'] and the False values are NaN.

The Boolean series is just given by your if statement (although it is necessary to use & instead of and):

>>> df['que'] = df['one'][(df['one'] >= df['two']) & (df['one'] <= df['three'])]
>>> df
    one two three   que
0   10  1.2 4.2      10
1   15  70  0.03    NaN
2   8   5   0       NaN

If you want the NaN values to be replaced by other values, you can use the fillna method on the new column que. I've used 0 instead of the empty string here:

>>> df['que'] = df['que'].fillna(0)
>>> df
    one two three   que
0   10  1.2   4.2    10
1   15   70  0.03     0
2    8    5     0     0

Maven: Command to update repository after adding dependency to POM

mvn install (or mvn package) will always work.

You can use mvn compile to download compile time dependencies or mvn test for compile time and test dependencies but I prefer something that always works.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

Jquery submit form

Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :

$(".nextbutton").click(function() { 
  $("#formID")[0].submit();
});

Extract values in Pandas value_counts()

Code

train["label_Name"].value_counts().to_frame()

where : label_Name Mean column_name

result (my case) :-

0    29720 
1     2242 
Name: label, dtype: int64

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

Running the new Intel emulator for Android

You might need to turn on virtualization in your BIOS, most manufacturers disable it by default. Intel HAX requires CPU virtualization to be enabled.

CSS Calc Viewport Units Workaround?

<div>It's working fine.....</div>

div
{
     height: calc(100vh - 8vw);
    background: #000;
    overflow:visible;
    color: red;
}

Check here this css code right now support All browser without Opera

just check this

Live

see Live preview by jsfiddle

See Live preview by codepen.io

HTTP Status 404 - The requested resource (/) is not available

I had the same problem with my localhost project using Eclipse Luna, Maven and Tomcat - the Tomcat homepage would appear fine, however my project would get the 404 error.

After trying many suggested solutions (updating spring .jar file, changing properties of the Tomcat server, add/remove project, change JRE from 1.6 to 7 etc) which did not fix the issue, what worked for me was to just Refresh my project. It seems Eclipse does not automatically refresh the project after a (Maven) build. In Eclipse 3.3.1 there was a 'Refresh Automatically' option under Preferences > General > Workspace however that option doesn't look to be in Luna.

  1. Maven clean-install on the project.
  2. ** Right-click the project and select 'Refresh'. **
  3. Right-click the Eclipse Tomcat server and select 'Clean'.
  4. Right-click > Publish and then start the Tomcat server.

Generating sql insert into for Oracle

You might execute something like this in the database:

select "insert into targettable(field1, field2, ...) values(" || field1 || ", " || field2 || ... || ");"
from targettable;

Something more sophisticated is here.

how to end ng serve or firebase serve

Can use

killall -9 

The killall command can be used to send a signal to a particular process by using its name. It means if you have five versions of the same program running, the killall command will kill all five.

Or you can use

pgrep "ng serve"

which will find the process id of ng and then you can use following command.

kill -9 <process_id>

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

This is how I implemented it with map. It should run in O(n) time and should kinda be easy to gasp.

_x000D_
_x000D_
    var first_array=[1,1,2,3,4,4,5,6];_x000D_
    var find_dup=new Map;_x000D_
_x000D_
    for (const iterator of first_array) {_x000D_
            // if present value++_x000D_
            if(find_dup.has(iterator)){ _x000D_
                find_dup.set(iterator,find_dup.get(iterator)+1); _x000D_
            }else{_x000D_
            // else add it_x000D_
                find_dup.set(iterator,1);_x000D_
            }_x000D_
        }_x000D_
    console.log(find_dup.get(2));
_x000D_
_x000D_
_x000D_

Then you can find_dup.get(key) to find if it has duplicates (it should give > 1).

how to check if a datareader is null or empty

I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:

public static class DataReaderExtensions
{
    public static bool IsDBNull( this IDataReader dataReader, string columnName )
    {
        return dataReader[columnName] == DBNull.Value;
    }
}

Kevin

How do I prevent a form from being resized by the user?

If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:

    Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
    Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)

Of course all choices of a formborderstyle beginning with Fixed will do.

CSS ''background-color" attribute not working on checkbox inside <div>

The Best solution to change background checkbox color

_x000D_
_x000D_
input[type=checkbox] {_x000D_
    margin-right: 5px;_x000D_
    cursor: pointer;_x000D_
    font-size: 14px;_x000D_
    width: 15px;_x000D_
    height: 12px;_x000D_
    position: relative;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:after {_x000D_
    position: absolute;_x000D_
    width: 10px;_x000D_
    height: 15px;_x000D_
    top: 0;_x000D_
    content: " ";_x000D_
    background-color: #ff0000;_x000D_
    color: #fff;_x000D_
    display: inline-block;_x000D_
    visibility: visible;_x000D_
    padding: 0px 3px;_x000D_
    border-radius: 3px;_x000D_
  }_x000D_
  _x000D_
  input[type=checkbox]:checked:after {_x000D_
   content: "?";_x000D_
   font-size: 12px;_x000D_
  }
_x000D_
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>_x000D_
_x000D_
  <input type="checkbox" name="vehicle" value="Car" checked> I have a bus<br>
_x000D_
_x000D_
_x000D_

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

Multiple Indexes vs Multi-Column Indexes

If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically.

By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.

Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.

You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.

Check if a specific tab page is selected (active)

This can work as well.

if (tabControl.SelectedTab.Text == "tabText" )
{
    .. do stuff
}

Determining the path that a yum package installed to

I don't know about yum, but rpm -ql will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.

jQuery/JavaScript to replace broken images

This is JavaScript, should be cross browser compatible, and delivers without the ugly markup onerror="":

var sPathToDefaultImg = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
    validateImage = function( domImg ) {
        oImg = new Image();
        oImg.onerror = function() {
            domImg.src = sPathToDefaultImg;
        };
        oImg.src = domImg.src;
    },
    aImg = document.getElementsByTagName( 'IMG' ),
    i = aImg.length;

while ( i-- ) {
    validateImage( aImg[i] );
}

CODEPEN:

What does [object Object] mean? (JavaScript)

As @Matt answered the reason of [object object], I will expand on how to inspect the value of the object. There are three options on top of my mind:

  • JSON.stringify(JSONobject)
  • console.log(JSONobject)
  • or iterate over the object

Basic example.

var jsonObj={
    property1 : "one",
    property2 : "two",
    property3 : "three",
    property4 : "fourth",
};

var strBuilder = [];
for(key in jsonObj) {
  if (jsonObj.hasOwnProperty(key)) {
    strBuilder.push("Key is " + key + ", value is " + jsonObj[key] + "\n");
  }
}

alert(strBuilder.join(""));
// or console.log(strBuilder.join(""))

https://jsfiddle.net/b1u6hfns/

C++ correct way to return pointer to array from function

A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:

#include <assert.h>

int main() {
  int a[] = {1, 2, 3, 4, 5}; 

  int* pArr = a;
  int* pFirstElem = &(a[0]);

  assert(a == pArr);
  assert(a == pFirstElem);

  return 0;
}

This also means that passing an array to a function should be done via pointer (and not via int in[5]), and possibly along with the length of the array:

int* test(int* in, int len) {
    int* out = in;
    return out;
}

That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:

#include <iostream>

using namespace std;

int main() {
  int* pArr = 0;
  {
    int a[] = {1, 2, 3, 4, 5};
    pArr = a; // or test(a) if you wish
  }
  // a[] went out of scope here, but pArr holds a pointer to it

  // all bets are off, this can output "1", output 1st chapter
  // of "Romeo and Juliet", crash the program or destroy the
  // universe
  cout << pArr[0] << endl; // WRONG!

  return 0;
}

So if you don't feel competent enough, just use std::vector.

[answer to the updated question]

The correct way to write your test function is either this:

void test(int* a, int* b, int* c, int len) {
  for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
}
...
int main() {
   int a[5] = {...}, b[5] = {...}, c[5] = {};
   test(a, b, c, 5);
   // c now holds the result
}

Or this (using std::vector):

#include <vector>

vector<int> test(const vector<int>& a, const vector<int>& b) {
  vector<int> result(a.size());
  for (int i = 0; i < a.size(); ++i) {
    result[i] = a[i] + b[i];
  }
  return result; // copy will be elided
}

Pandas split column of lists into multiple columns

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])

How do I import a .dmp file into Oracle?

i got solution what you are getting as per imp help=y it is mentioned that imp is only valid for TRANSPORT_TABLESPACE as below:

Keyword  Description (Default)       Keyword      Description (Default)
--------------------------------------------------------------------------
USERID   username/password           FULL         import entire file (N)
BUFFER   size of data buffer         FROMUSER     list of owner usernames
FILE     input files (EXPDAT.DMP)    TOUSER       list of usernames
SHOW     just list file contents (N) TABLES       list of table names
IGNORE   ignore create errors (N)    RECORDLENGTH length of IO record
GRANTS   import grants (Y)           INCTYPE      incremental import type
INDEXES  import indexes (Y)          COMMIT       commit array insert (N)
ROWS     import data rows (Y)        PARFILE      parameter filename
LOG      log file of screen output   CONSTRAINTS  import constraints (Y)
DESTROY                overwrite tablespace data file (N)
INDEXFILE              write table/index info to specified file
SKIP_UNUSABLE_INDEXES  skip maintenance of unusable indexes (N)
FEEDBACK               display progress every x rows(0)
TOID_NOVALIDATE        skip validation of specified type ids
FILESIZE               maximum size of each dump file
STATISTICS             import precomputed statistics (always)
RESUMABLE              suspend when a space related error is encountered(N)
RESUMABLE_NAME         text string used to identify resumable statement
RESUMABLE_TIMEOUT      wait time for RESUMABLE
COMPILE                compile procedures, packages, and functions (Y)
STREAMS_CONFIGURATION  import streams general metadata (Y)
STREAMS_INSTANTIATION  import streams instantiation metadata (N)
DATA_ONLY              import only data (N)

The following keywords only apply to transportable tablespaces
TRANSPORT_TABLESPACE import transportable tablespace metadata (N)
TABLESPACES tablespaces to be transported into database
DATAFILES datafiles to be transported into database
TTS_OWNERS users that own data in the transportable tablespace set

So, Please create table space for your user:

CREATE TABLESPACE <tablespace name> DATAFILE <path to save, example: 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\ABC.dbf'> SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE 10G EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;

How to import an existing directory into Eclipse?

I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:

<projectDescription>
    <name>Project-Name</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
    </buildSpec>
    <natures>
    </natures>
</projectDescription>

2- Now instead of "Project-Name", write your project name, maybe current directory name

3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )

4- Now go to Eclips and open project and add your files to it.

When should I create a destructor?

It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.

It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.

In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.

A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.

Render HTML to an image

I don't expect this to be the best answer, but it seemed interesting enough to post.

Write an app that opens up your favorite browser to the desired HTML document, sizes the window properly, and takes a screen shot. Then, remove the borders of the image.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Convert NaN to 0 in javascript

Using a double-tilde (double bitwise NOT) - ~~ - does some interesting things in JavaScript. For instance you can use it instead of Math.floor or even as an alternative to parseInt("123", 10)! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?

We can exploit this property of a double-tilde to convert NaN to a number, and happily that number is zero!

console.log(~~NaN); // 0

Karma: Running a single test file from command line

First you need to start karma server with

karma start

Then, you can use grep to filter a specific test or describe block:

karma run -- --grep=testDescriptionFilter

CSS float right not working correctly

You have not used float:left command for your text.

boundingRectWithSize for NSAttributedString returning wrong size

Swift four version

let string = "A great test string."
let font = UIFont.systemFont(ofSize: 14)
let attributes: [NSAttributedStringKey: Any] = [.font: font]
let attributedString = NSAttributedString(string: string, attributes: attributes)
let largestSize = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)

//Option one (best option)
let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, largestSize, nil)

//Option two
let textSize = (string as NSString).boundingRect(with: largestSize, options: [.usesLineFragmentOrigin , .usesFontLeading], attributes: attributes, context: nil).size

//Option three
let textSize = attributedString.boundingRect(with: largestSize, options: [.usesLineFragmentOrigin , .usesFontLeading], context: nil).size

Measuring the text with the CTFramesetter works best as it provides integer sizes and handles emoji's and other unicode characters well.

Submit form on pressing Enter with AngularJS

If you only have one input you can use the form tag.

<form ng-submit="myFunc()" ...>

If you have more than one input, or don't want to use the form tag, or want to attach the enter-key functionality to a specific field, you can inline it to a specific input as follows:

<input ng-keyup="$event.keyCode == 13 && myFunc()" ...>

How do android screen coordinates work?

This picture will remove everyone's confusion hopefully which is collected from there.

Android screen coordinate

MySql server startup error 'The server quit without updating PID file '

Check if you have space left in your drive. I got this problem when no space left in my drive.

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

How to trigger a click on a link using jQuery

Well you have to setup the click event first then you can trigger it and see what happens:

//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
  evt.preventDefault();
  alert($(this).attr('href'));
});

// now the manual trigger
$myLink.trigger('click');

When to use NSInteger vs. int

On iOS, it currently does not matter if you use int or NSInteger. It will matter more if/when iOS moves to 64-bits.

Simply put, NSIntegers are ints in 32-bit code (and thus 32-bit long) and longs on 64-bit code (longs in 64-bit code are 64-bit wide, but 32-bit in 32-bit code). The most likely reason for using NSInteger instead of long is to not break existing 32-bit code (which uses ints).

CGFloat has the same issue: on 32-bit (at least on OS X), it's float; on 64-bit, it's double.

Update: With the introduction of the iPhone 5s, iPad Air, iPad Mini with Retina, and iOS 7, you can now build 64-bit code on iOS.

Update 2: Also, using NSIntegers helps with Swift code interoperability.

Specifying Font and Size in HTML table

First, try omitting the quotes from 12 and 24. Worth a shot.

Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:

<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>

Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .

Converting an int to std::string

You can use std::to_string in C++11

int i = 3;
std::string str = std::to_string(i);

Table variable error: Must declare the scalar variable "@temp"

You've declared @TEMP but in your insert statement used @temp. Case sensitive variable names.

Change @temp to @TEMP

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

A simple solution to exclude everything but integer numbers

_x000D_
_x000D_
<input  
    type="number"
    min="1" 
    step="1"
    onkeypress="return event.keyCode === 8 || event.charCode >= 48 && event.charCode <= 57">
_x000D_
_x000D_
_x000D_

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

How to produce an csv output file from stored procedure in SQL Server

I think it is possible to use bcp command. I am also new to this command but I followed this link and it worked for me.

Reimport a module in python while interactive

If you want to import a specific function or class from a module, you can do this:

import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Image scaling causes poor quality in firefox/internet explorer but not chrome

Remember that sizes on the web are increasing dramatically. 3 years ago, I did an overhaul to bring our 500 px wide site layout to 1000. Now, where many sites are doing the jump to 1200, we jumped past that and went to a 2560 max optimized for 1600 wide (or 80% depending on the content level) main content area with responsiveness to allow the exact same ratios and look and feel on a laptop (1366x768) and on mobile (1280x720 or smaller).

Dynamic resizing is an integral part of this and will only become more-so as responsiveness becomes more and more important in 2013.

My smartphone has no trouble dealing with the content with 25 items on a page being resized - neither the computation for resizing nor the bandwidth. 3 seconds loads the page from fresh. Looks great on our 6 year old presentation laptop (1366x768) and on the projector (800x600).

Only on Mozilla Firefox does it look genuinely atrocious. It even looks just fine on IE8 (never used/updated since I installed it 2.5 years ago).

jQuery - select the associated label element of a input field

As long and your input and label elements are associated by their id and for attributes, you should be able to do something like this:

$('.input').each(function() { 
   $this = $(this);
   $label = $('label[for="'+ $this.attr('id') +'"]');
   if ($label.length > 0 ) {
       //this input has a label associated with it, lets do something!
   }
});

If for is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.

git pull keeping local changes

Update: this literally answers the question asked, but I think KurzedMetal's answer is really what you want.

Assuming that:

  1. You're on the branch master
  2. The upstream branch is master in origin
  3. You have no uncommitted changes

.... you could do:

# Do a pull as usual, but don't commit the result:
git pull --no-commit

# Overwrite config/config.php with the version that was there before the merge
# and also stage that version:
git checkout HEAD config/config.php

# Create the commit:
git commit -F .git/MERGE_MSG

You could create an alias for that if you need to do it frequently. Note that if you have uncommitted changes to config/config.php, this would throw them away.

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

HashMap with multiple values under the same key

Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.

Example:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

could be replaced with

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

would result in collection coll containing "A", "B", and "C".

How does the "this" keyword work?

This is the best explanation I've seen: Understand JavaScripts this with Clarity

The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope. Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.

There are Four Scenarios where this can be confusing:

  1. When we pass a method (that uses this) as an argument to be used as a callback function.
  2. When we use an inner function (a closure). It is important to take note that closures cannot access the outer function’s this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions.
  3. When a method which relies on this is assigned to a variable across contexts, in which case this references another object than originally intended.
  4. When using this along with the bind, apply, and call methods.

He gives code examples, explanations, and solutions, which I thought was very helpful.

OSError [Errno 22] invalid argument when use open() in Python

you should add one more "/" in the last "/" of path, that is: open('C:\Python34\book.csv') to open('C:\Python34\\book.csv'). For example:

import csv
with open('C:\Python34\\book.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='', quotechar='|')
    for row in spamreader:
        print(row)

Python threading. How do I lock a thread?

import threading 

# global variable x 
x = 0

def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1

def thread_task(): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        increment() 

def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0

    # creating threads 
    t1 = threading.Thread(target=thread_task) 
    t2 = threading.Thread(target=thread_task) 

    # start threads 
    t1.start() 
    t2.start() 

    # wait until threads finish their job 
    t1.join() 
    t2.join() 

if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))

Forcing a postback

No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.

Important note

Your code has a typo in your if statement in not exists(select...) part. Inner select statement has only one where condition while UserName condition is excluded from the not exists due to invalid brace completion. In any case you cave too many closing braces.

I assume this based on the fact that you're using two where conditions in update statement later on in your code.

Let's continue to my answer...

SQL Server 2008+ support MERGE statement

MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).

declare @clockDate date = '08/10/2012';
declare @userName = 'test';

merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
    update
    set BreakOut = getdate()
when not matched then
    insert (ClockDate, UserName, BreakOut)
    values (getdate(), source.UserName, getdate());

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

(HTML) Download a PDF file instead of opening them in browser when clicked

The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.

How to get the input from the Tkinter Text Widget?

I did come also in search of how to get input data from the Text widget. Regarding the problem with a new line on the end of the string. You can just use .strip() since it is a Text widget that is always a string.

Also, I'm sharing code where you can see how you can create multiply Text widgets and save them in the dictionary as form data, and then by clicking the submit button get that form data and do whatever you want with it. I hope it helps others. It should work in any 3.x python and probably will work in 2.7 also.

from tkinter import *
from functools import partial

class SimpleTkForm(object):
    def __init__(self):
        self.root = Tk()

    def myform(self):
        self.root.title('My form')
        frame = Frame(self.root, pady=10)
        form_data = dict()
        form_fields = ['username', 'password', 'server name', 'database name']
        cnt = 0
        for form_field in form_fields:
            Label(frame, text=form_field, anchor=NW).grid(row=cnt,column=1, pady=5, padx=(10, 1), sticky="W")
            textbox = Text(frame, height=1, width=15)
            form_data.update({form_field: textbox})
            textbox.grid(row=cnt,column=2, pady=5, padx=(3,20))
            cnt += 1

        conn_test = partial(self.test_db_conn, form_data=form_data)
        Button(frame, text='Submit', width=15, command=conn_test).grid(row=cnt,column=2, pady=5, padx=(3,20))
        frame.pack()
        self.root.mainloop()

    def test_db_conn(self, form_data):
        data = {k:v.get('1.0', END).strip() for k,v in form_data.items()}
        # validate data or do anything you want with it
        print(data)


if __name__ == '__main__':
    api = SimpleTkForm()
    api.myform()

What is the effect of extern "C" in C++?

It changes the linkage of a function in such a way that the function is callable from C. In practice that means that the function name is not mangled.

For each row in an R dataframe

I use this simple utility function:

rows = function(tab) lapply(
  seq_len(nrow(tab)),
  function(i) unclass(tab[i,,drop=F])
)

Or a faster, less clear form:

rows = function(x) lapply(seq_len(nrow(x)), function(i) lapply(x,"[",i))

This function just splits a data.frame to a list of rows. Then you can make a normal "for" over this list:

tab = data.frame(x = 1:3, y=2:4, z=3:5)
for (A in rows(tab)) {
    print(A$x + A$y * A$z)
}        

Your code from the question will work with a minimal modification:

for (well in rows(dataFrame)) {
  wellName <- well$name    # string like "H1"
  plateName <- well$plate  # string like "plate67"
  wellID <- getWellID(wellName, plateName)
  cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

How to scroll to top of page with JavaScript/jQuery?

$(function() {
    // the element inside of which we want to scroll
        var $elem = $('#content');

        // show the buttons
    $('#nav_up').fadeIn('slow');
    $('#nav_down').fadeIn('slow');  

        // whenever we scroll fade out both buttons
    $(window).bind('scrollstart', function(){
        $('#nav_up,#nav_down').stop().animate({'opacity':'0.2'});
    });
        // ... and whenever we stop scrolling fade in both buttons
    $(window).bind('scrollstop', function(){
        $('#nav_up,#nav_down').stop().animate({'opacity':'1'});
    });

        // clicking the "down" button will make the page scroll to the $elem's height
    $('#nav_down').click(
        function (e) {
            $('html, body').animate({scrollTop: $elem.height()}, 800);
        }
    );
        // clicking the "up" button will make the page scroll to the top of the page
    $('#nav_up').click(
        function (e) {
            $('html, body').animate({scrollTop: '0px'}, 800);
        }
    );
 });

Use This

What does [STAThread] do?

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

Read more info here (Archived, June 2009)

and

Why is STAThread required?

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

What linux shell command returns a part of a string?

In bash you can try this:

stringZ=abcABC123ABCabc
#       0123456789.....
#       0-based indexing.

echo ${stringZ:0:2} # prints ab

More samples in The Linux Documentation Project

How to change legend title in ggplot

The way i am going to tell you, will allow you to change the labels of legend, axis, title etc with a single formula and you don't need to use memorise multiple formulas. This will not affect the font style or the design of the labels/ text of titles and axis.

I am giving the complete answer of the question below.

 library(ggplot2)
 rating <- c(rnorm(200), rnorm(200, mean=.8))
 cond <-factor(rep(c("A", "B"), each = 200))
 df <- data.frame(cond,rating 
             )

 k<- ggplot(data=df, aes(x=rating, fill=cond))+ 
 geom_density(alpha = .3) +
 xlab("NEW RATING TITLE") +
 ylab("NEW DENSITY TITLE")

 # to change the cond to a different label
 k$labels$fill="New Legend Title"

 # to change the axis titles
 k$labels$y="Y Axis"
 k$labels$x="X Axis"
 k

I have stored the ggplot output in a variable "k". You can name it anything you like. Later I have used

k$labels$fill ="New Legend Title"

to change the legend. "fill" is used for those labels which shows different colours. If you have labels that shows sizes like 1 point represent 100, other point 200 etc then you can use this code like this-

k$labels$size ="Size of points"

and it will change that label title.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

How to join two sets in one line without using "|"

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

ASP.NET MVC3 Razor - Html.ActionLink style

Here's the signature.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

What you are doing is mixing the values and the htmlAttributes together. values are for URL routing.

You might want to do this.

@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null, 
     new { @style="text-transform:capitalize;" });

After submitting a POST form open a new window showing the result

var urlAction = 'whatever.php';
var data = {param1:'value1'};

var $form = $('<form target="_blank" method="POST" action="' + urlAction + '">');
$.each(data, function(k,v){
    $form.append('<input type="hidden" name="' + k + '" value="' + v + '">');
});
$form.submit();