Programs & Examples On #Httpunhandledexception

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

Base 64 encode and decode example code

for android API byte[] to Base64String encoder

byte[] data=new byte[];
String Base64encodeString=android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);

Reading a cell value in Excel vba and write in another Cell

The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:

For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next

If you do not want the symbols like colon to be inserted put an if condition in the loop.

Return multiple values from a function in swift

Swift 3

func getTime() -> (hour: Int, minute: Int,second: Int) {
        let hour = 1
        let minute = 20
        let second = 55
        return (hour, minute, second)
    }

To use :

let(hour, min,sec) = self.getTime()
print(hour,min,sec)

What are forward declarations in C++?

one quick addendum regarding: usually you put those forward references into a header file belonging to the .c(pp) file where the function/variable etc. is implemented. in your example it would look like this: add.h:

extern int add(int a, int b);

the keyword extern states that the function is actually declared in an external file (could also be a library etc.). your main.c would look like this:

#include 
#include "add.h"

int main()
{
.
.
.

Using import fs from 'fs'

In order to use import { readFileSync } from 'fs', you have to:

  1. Be using Node.js 10 or later
  2. Use the --experimental-modules flag (in Node.js 10), e.g. node --experimental-modules server.mjs (see #3 for explanation of .mjs)
  3. Rename the file extension of your file with the import statements, to .mjs, .js will not work, e.g. server.mjs

The other answers hit on 1 and 2, but 3 is also necessary. Also, note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production, but I will still probably use it.

Here's the Node.js 10 ESM documentation.

Is there a difference between /\s/g and /\s+/g?

In a match situation the first would return one match per whitespace, when the second would return a match for each group of whitespaces.

The result is the same because you're replacing it with an empty string. If you replace it with 'x' for instance, the results would differ.

str.replace(/\s/g, '') will return 'xxAxBxxCxxxDxEF '

while str.replace(/\s+/g, '') will return 'xAxBxCxDxEF '

because \s matches each whitespace, replacing each one with 'x', and \s+ matches groups of whitespaces, replacing multiple sequential whitespaces with a single 'x'.

Remove whitespaces inside a string in javascript

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

How to flush output after each `echo` call?

For those coming in 2018:

The ONLY Solution worked for me:

<?php

    if (ob_get_level() == 0) ob_start();
    for ($i = 0; $i<10; $i++){

        echo "<br> Line to show.";
        echo str_pad('',4096)."\n";    

        ob_flush();
        flush();
        sleep(2);
    }

    echo "Done.";

    ob_end_flush();
?>

and its very important to keep de "4096" part because it seems that "fills" the buffer...

Closing a file after File.Create

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

How do I use the includes method in lodash to check if an object is in the collection?

You could use find to solve your problem

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

How to pass parameters or arguments into a gradle task

You should consider passing the -P argument in invoking Gradle.

From Gradle Documentation :

--project-prop Sets a project property of the root project, for example -Pmyprop=myvalue. See Section 14.2, “Gradle properties and system properties”.

Considering this build.gradle

task printProp << {
    println customProp
}

Invoking Gradle -PcustomProp=myProp will give this output :

$ gradle -PcustomProp=myProp printProp
:printProp
myProp

BUILD SUCCESSFUL

Total time: 3.722 secs

This is the way I found to pass parameters.

Git: Create a branch from unstaged/uncommitted changes on master

Try:

git stash
git checkout -b new-branch
git stash apply

Run / Open VSCode from Mac Terminal

I prefer to have symlinks in the home directory, in this case at least. Here's how I have things setup:

: cat ~/.bash_profile | grep PATH
# places ~/bin first in PATH
export PATH=~/bin:$PATH

So I symlinked to the VSCode binary like so:

ln -s /Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin/code ~/bin/code

Now I can issue code . in whichever directory I desire.

Hide div after a few seconds

There's a really simple way to do this.

The problem is that .delay only effects animations, so what you need to do is make .hide() act like an animation by giving it a duration.

$("#whatever").delay().hide(1);

By giving it a nice short duration, it appears to be instant just like the regular .hide function.

Authenticate with GitHub using a token

I'm on Ubuntu 20.04 and I kept getting the message that soon I wouldn't be able to login from console. I was terribly confused. Finally, I got to the URL below which will work. But you need to know how to create a PAT (Personal Access Token) which you are going to have to keep in a file on your computer.

Here's what the final URL will look like:

git push https://[email protected]/user-name/repo.git

long PAT (Personal Access Token) value -- The entire long value between the // and the @ sign in the url is your PAT.

user-name will be your exact username

repo.git will be your exact repo name

You need to generate a PAT following the steps at: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token

That will give you the PAT value that you will place in your URL.

When you create the PAT make sure you choose the following options so it has the ability to allow you to manage your REPOs. PAT settings

Save Your PAT Or Lose It

Once you have your PAT. You're going to need to save it in a file locally so you can use it again. If you don't save it somewhere there is no way to ever see it again and you'll be forced to create a new PAT

Now you're going to need at the very least :

  1. a way to display it in your console so you can see it again.
  2. or, A way to copy it to your clipboard automatically.

For 1, just use :

$ cat ~/files/myPatFile.txt

Where the path is a real path to the location and file where you stored your PAT value.

For 2

$ xclip -selection clipboard < ~/files/myPatFile.txt

That'll copy the contents of the file to the clipboard so you can use your PAT more easily.

FYI - if you don't have xclip do the following:

$ sudo apt-get install xclip

Downloads and installs xclip. If you don't have apt-get, you might need to use another installer (like yum)

How to get the date 7 days earlier date from current date in Java

You can use this to continue using the type Date and a more legible code, if you preffer:

import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);

How to get query string parameter from MVC Razor markup?

If you are using .net core 2.0 this would be:

Context.Request.Query["id"]

Sample usage:

<a href="@Url.Action("Query",new {parm1=Context.Request.Query["queryparm1"]})">GO</a>

How to import a module in Python with importlib.import_module

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

  1. To avoid clash with other methods/libraries in the same window,
  2. Avoid Global scope, make it local scope,
  3. To make debugging faster (local scope),
  4. JavaScript has function scope only, so it will help in compilation of codes as well.

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

Python loop for inside lambda

Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

x = lambda x: sys.stdout.write("\n".join(x) + "\n")

How to install PostgreSQL's pg gem on Ubuntu?

If you have libpq-dev installed and are still having this problem it is likely due to conflicting versions of OpenSSL's libssl and friends - the Ubuntu system version in /usr/lib (which libpq is built against) and a second version RVM installed in $HOME/.rvm/usr/lib (or /usr/local/rvm/usr/lib if it's a system install). You can verify this by temporarily renaming $HOME/.rvm/usr/lib and seeing if "gem install pg" works.

To solve the problem have rvm rebuild using the system OpenSSL libraries (you may need to manually remove libssl.* and libcrypto.* from the rvm/usr/lib dir):

rvm reinstall 1.9.3 --with-openssl-dir=/usr

This finally solved the problem for me on Ubunto 12.04.

Hiding an Excel worksheet with VBA

To hide from the UI, use Format > Sheet > Hide

To hide programatically, use the Visible property of the Worksheet object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.

ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden 
' or xlSheetHidden or xlSheetVisible

You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

Well, I'm not sure that merge would be the way to go. Personally I would build a new data frame by creating an index of the dates and then constructing the columns using list comprehensions. Possibly not the most pythonic way, but it seems to work for me!

import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

# Create an index list from the set of dates in both data frames
Index = list(set(list(df1.index) + list(df2.index)))
Index.sort()

df3 = pd.DataFrame({'df1': [df1.loc[Date, 'c'] if Date in df1.index else np.nan for Date in Index],\
                'df2': [df2.loc[Date, 'c'] if Date in df2.index else np.nan for Date in Index],},\
                index = Index)

df3

Rolling back bad changes with svn in Eclipse

You have two choices to do this.

The Quick and Dirty is selecting your files (using ctrl) in Project Explorer view, right-click them, choose Replace with... and then you choose the best option for you, from Latest from Repository, or some Branch version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision.

A more clean way is choosing Merge at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision.

Both commands have their command-line equivalents: svn revert and svn merge.

Joining Spark dataframes on the key

inner join with scala

val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show

Xcode 'CodeSign error: code signing is required'

Be sure you code sign on the line "any iOS SDK" and not "Debug/Distribution/Release"

Here is exactly what I did :

Code signing identity -> don't code sign
* Debug -> don't code sign
** any iOS SDK -> [my developer profile]
* Distribution -> don't code sign
** any iOS SDK -> [my AppStore profile]
* Release -> don't code sign
** any iOS SDK -> [my AdHoc profile]

When I put my profiles one level above (at Debug/Ditribution/Release), it doesn't work for some reason (bug ?).

Hope it helps some of us !

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

I wasn't using Azure, but I got the same error locally. Using <customErrors mode="Off" /> seemed to have no effect, but checking the Application logs in Event Viewer revealed a warning from ASP.NET which contained all the detail I needed to resolve the issue.

How to use executables from a package installed locally in node_modules?

UPDATE: As Seyeong Jeong points out in their answer below, since npm 5.2.0 you can use npx [command], which is more convenient.

OLD ANSWER for versions before 5.2.0:

The problem with putting

./node_modules/.bin

into your PATH is that it only works when your current working directory is the root of your project directory structure (i.e. the location of node_modules)

Independent of what your working directory is, you can get the path of locally installed binaries with

npm bin

To execute a locally installed coffee binary independent of where you are in the project directory hierarchy you can use this bash construct

PATH=$(npm bin):$PATH coffee

I aliased this to npm-exec

alias npm-exec='PATH=$(npm bin):$PATH'

So, now I can

npm-exec coffee

to run the correct copy of coffee no matter of where I am

$ pwd
/Users/regular/project1

$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd lib/
$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd ~/project2
$ npm-exec which coffee
/Users/regular/project2/node_modules/.bin/coffee

Retrieving Property name from lambda expression

I've found that some of the suggested answers which drill down into the MemberExpression/UnaryExpression don't capture nested/subproperties.

ex) o => o.Thing1.Thing2 returns Thing1 rather than Thing1.Thing2.

This distinction is important if you're trying to work with EntityFramework DbSet.Include(...).

I've found that just parsing the Expression.ToString() seems to work fine, and comparatively quickly. I compared it against the UnaryExpression version, and even getting ToString off of the Member/UnaryExpression to see if that was faster, but the difference was negligible. Please correct me if this is a terrible idea.

The Extension Method

/// <summary>
/// Given an expression, extract the listed property name; similar to reflection but with familiar LINQ+lambdas.  Technique @via https://stackoverflow.com/a/16647343/1037948
/// </summary>
/// <remarks>Cheats and uses the tostring output -- Should consult performance differences</remarks>
/// <typeparam name="TModel">the model type to extract property names</typeparam>
/// <typeparam name="TValue">the value type of the expected property</typeparam>
/// <param name="propertySelector">expression that just selects a model property to be turned into a string</param>
/// <param name="delimiter">Expression toString delimiter to split from lambda param</param>
/// <param name="endTrim">Sometimes the Expression toString contains a method call, something like "Convert(x)", so we need to strip the closing part from the end</param>
/// <returns>indicated property name</returns>
public static string GetPropertyName<TModel, TValue>(this Expression<Func<TModel, TValue>> propertySelector, char delimiter = '.', char endTrim = ')') {

    var asString = propertySelector.ToString(); // gives you: "o => o.Whatever"
    var firstDelim = asString.IndexOf(delimiter); // make sure there is a beginning property indicator; the "." in "o.Whatever" -- this may not be necessary?

    return firstDelim < 0
        ? asString
        : asString.Substring(firstDelim+1).TrimEnd(endTrim);
}//--   fn  GetPropertyNameExtended

(Checking for the delimiter might even be overkill)

Demo (LinqPad)

Demonstration + Comparison code -- https://gist.github.com/zaus/6992590

How can I change the font size of ticks of axes object in matplotlib

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()

the x/yticks has the same properties as matplotlib.text

how to run or install a *.jar file in windows?

Open up a command prompt and type java -jar jbpm-installer-3.2.7.jar

Is it possible to capture the stdout from the sh DSL command in the pipeline

I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {                                 
                            println my_var
                            }
                }

Creating executable files in Linux

I think the problem you're running into is that, even though you can set your own umask values in the system, this does not allow you to explicitly control the default permissions set on a new file by gedit (or whatever editor you use).

I believe this detail is hard-coded into gedit and most other editors. Your options for changing it are (a) hacking up your own mod of gedit or (b) finding a text editor that allows you to set a preference for default permissions on new files. (Sorry, I know of none.)

In light of this, it's really not so bad to have to chmod your files, right?

How to determine an object's class?

You can use getSimpleName().

Let's say we have a object: Dog d = new Dog(),

The we can use below statement to get the class name: Dog. E.g.:

d.getClass().getSimpleName(); // return String 'Dog'.

PS: d.getClass() will give you the full name of your object.

How to make the overflow CSS property work with hidden as value

Actually...

To hide an absolute positioned element, the container position must be anything except for static. It can be relative or fixed in addition to absolute.

How to paginate with Mongoose in Node.js?

You can chain just like that:

var query = Model.find().sort('mykey', 1).skip(2).limit(5)

Execute the query using exec

query.exec(callback);

Chmod 777 to a folder and all contents

This didn't work for me.

sudo chmod -R 777 /path/to/your/file/or/directory

I used -f also.

sudo chmod -R -f 777 /path/to/your/file/or/directory

How to change the decimal separator of DecimalFormat from comma to dot/point?

This worked for me...

    double num = 10025000;
    new DecimalFormat("#,###.##");
    DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
    System.out.println(df.format(num));

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

INNER JOIN ON vs WHERE clause

They have a different human-readable meaning.

However, depending on the query optimizer, they may have the same meaning to the machine.

You should always code to be readable.

That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

SonarQube not picking up Unit Test Coverage

Based on https://github.com/SonarSource/sonar-examples/blob/master/projects/tycho/pom.xml, the following POM works for me:

<properties>
    <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
    <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
</properties>
<build>
    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.7.0.201403182114</version>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <destFile>${sonar.jacoco.reportPath}</destFile>
            </configuration>
        </plugin>
    </plugins>
</build>
  • Setting the destination file to the report path ensures that Sonar reads exactly the file JaCoCo generates.
  • The report path should be outside the projects' directories to take cross-project coverage into account (e.g. in case of Tycho where the convention is to have separate projects for tests).
  • The reuseReports setting prevents the deletion of the JaCoCo report file before it is read! (Since 4.3, this is the default and is deprecated.)

Then I just run

mvn clean install
mvn sonar:sonar

Is there a way to get the XPath in Google Chrome?

Let tell you a simple formula to find xpath of any element:

1- Open site in browser

2- Select element and right click on it

3- Click inspect element option

4- Right click on selected html

5- choose option to copy xpath Use it where ever you need it

This video link will be helpful for you. http://screencast.com/t/afXsaQXru

Note: For advance options of xpath you must know regex or pattern of your html.

Mockito - NullpointerException when stubbing Method

None of the above answers helped me. I was struggling to understand why code works in Java but not in Kotlin.

Then I figured it out from this thread.

You have to make class and member functions open, otherwise NPE was being thrown.

After making function open tests started to pass.

You might as well consider using compiler's "all-open" plugin:

Kotlin has classes and their members final by default, which makes it inconvenient to use frameworks and libraries such as Spring AOP that require classes to be open. The all-open compiler plugin adapts Kotlin to the requirements of those frameworks and makes classes annotated with a specific annotation and their members open without the explicit open keyword.

How do I add a new column to a Spark DataFrame (using PySpark)?

To add new column with some custom value or dynamic value calculation which will be populated based on the existing columns.

e.g.

|ColumnA | ColumnB |
|--------|---------|
| 10     | 15      |
| 10     | 20      |
| 10     | 30      |

and new ColumnC as ColumnA+ColumnB

|ColumnA | ColumnB | ColumnC|
|--------|---------|--------|
| 10     | 15      | 25     |
| 10     | 20      | 30     |
| 10     | 30      | 40     |

using

#to add new column
def customColumnVal(row):
rd=row.asDict()
rd["ColumnC"]=row["ColumnA"] + row["ColumnB"]

new_row=Row(**rd)
return new_row
----------------------------
#convert DF to RDD
df_rdd= input_dataframe.rdd

#apply new fucntion to rdd
output_dataframe=df_rdd.map(customColumnVal).toDF()

input_dataframe is the dataframe which will get modified and customColumnVal function is having code to add new column.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

How to convert an IPv4 address into a integer in C#?

I noticed that System.Net.IPAddress have Address property (System.Int64) and constructor, which also accept Int64 data type. So you can use this to convert IP address to/from numeric (although not Int32, but Int64) format.

error: package com.android.annotations does not exist

Open gradle.properties and use following code:

android.useAndroidX=false
android.enableJetifier=false

or U can use these dependencies too:

implementation 'androidx.appcompat:appcompat:1.0.2'
 implementation 'androidx.annotation:annotation:1.0.2'

How to check if Receiver is registered in Android?

I am not sure the API provides directly an API, if you consider this thread:

I was wondering the same thing.
In my case I have a BroadcastReceiver implementation that calls Context#unregisterReceiver(BroadcastReceiver) passing itself as the argument after handling the Intent that it receives.
There is a small chance that the receiver's onReceive(Context, Intent) method is called more than once, since it is registered with multiple IntentFilters, creating the potential for an IllegalArgumentException being thrown from Context#unregisterReceiver(BroadcastReceiver).

In my case, I can store a private synchronized member to check before calling Context#unregisterReceiver(BroadcastReceiver), but it would be much cleaner if the API provided a check method.

Writelines writes lines without newline, Just fills the file

writelines() does not add line separators. You can alter the list of strings by using map() to add a new \n (line break) at the end of each string.

items = ['abc', '123', '!@#']
items = map(lambda x: x + '\n', items)
w.writelines(items)

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

Instead of using javascript, you can simply put this line of code after your mysql_connect sentence:

mysql_set_charset('utf8',$connection);

Cheers.

Using Tempdata in ASP.NET MVC - Best practice

TempData is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.

To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.

Hope this helps.

Have a reloadData for a UITableView animate when changing

In my case, I wanted to add 10 more rows into the tableview (for a "show more results" type of functionality) and I did the following:

  NSInteger tempNumber = self.numberOfRows;
  self.numberOfRows += 10;
  NSMutableArray *arrayOfIndexPaths = [[NSMutableArray alloc] init];
  for (NSInteger i = tempNumber; i < self.numberOfRows; i++) {
    [arrayOfIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
  }
  [self.tableView beginUpdates];
  [self.tableView insertRowsAtIndexPaths:arrayOfIndexPaths withRowAnimation:UITableViewRowAnimationTop];
  [self.tableView endUpdates];

In most cases, instead of "self.numberOfRows", you would usually use the count of the array of objects for the tableview. So to make sure this solution works well for you, "arrayOfIndexPaths" needs to be an accurate array of the index paths of the rows being inserted. If the row exists for any of this index paths, the code might crash, so you should use the method "reloadRowsAtIndexPaths:withRowAnimation:" for those index pathds to avoid crashing

How do I display images from Google Drive on a website?

<img src="https://drive.google.com/uc?export=view&id=Your_Image_ID" alt="">

I use on my wordpress site as storing image files on local host takes up to much space and slows down my site

I use textmate as it is easy to edit multiple URLs at same time using the 'alt/option' button

Select element by exact match of its content

An one-liner that works with alternative libraries to jQuery:

$('p').filter((i, p) => $(p).text().trim() === "hello").css('font-weight', 'bold');

And this is the equivalent to a jQuery's a:contains("pattern") selector:

var res = $('a').filter((i, a) => $(a).text().match(/pattern/));

How to sort in mongoose?

Post.find().sort({updatedAt: 1});

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Using the AWS Management Console

  • Go to "Volumes" and create a Snapshot of your instance's volume.
  • Go to "Snapshots" and select "Create Image from Snapshot".
  • Go to "AMIs" and select "Launch Instance" and choose your "Instance Type" etc.

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

How to get only the last part of a path in Python?

During my current projects, I'm often passing rear parts of a path to a function and therefore use the Path module. To get the n-th part in reverse order, I'm using:

from typing import Union
from pathlib import Path

def get_single_subpath_part(base_dir: Union[Path, str], n:int) -> str:
    if n ==0:
        return Path(base_dir).name
    for _ in range(n):
        base_dir = Path(base_dir).parent
    return getattr(base_dir, "name")

path= "/folderA/folderB/folderC/folderD/"

# for getting the last part:
print(get_single_subpath_part(path, 0))
# yields "folderD"

# for the second last
print(get_single_subpath_part(path, 1))
#yields "folderC"

Furthermore, to pass the n-th part in reverse order of a path containing the remaining path, I use:

from typing import Union
from pathlib import Path

def get_n_last_subparts_path(base_dir: Union[Path, str], n:int) -> Path:
    return Path(*Path(base_dir).parts[-n-1:])

path= "/folderA/folderB/folderC/folderD/"

# for getting the last part:
print(get_n_last_subparts_path(path, 0))
# yields a `Path` object of "folderD"

# for second last and last part together 
print(get_n_last_subparts_path(path, 1))
# yields a `Path` object of "folderc/folderD"

Note that this function returns a Pathobject which can easily be converted to a string (e.g. str(path))

Spring cron expression for every day 1:01:am

You can use annotate your method with @Scheduled(cron ="0 1 1 * * ?").

0 - is for seconds

1- 1 minute

1 - hour of the day.

Strangest language feature

This is nothing strange or surprising, but it is something that made me always say WTF:

Case sensitivity in syntax, or in identifier names.

Most languages that have it just seem to have it because C has it. There is no good reason for it.

How to set image to fit width of the page using jsPDF?

I discovered this while experimenting with html2canvas this morning. While this doesn't include provisions for printing multiple pages it does scale the image to page width and reframes the height in ratio to the adjusted width:

html2canvas(document.getElementById('testdiv')).then(function(canvas){
        var wid: number
        var hgt: number
        var img = canvas.toDataURL("image/png", wid = canvas.width, hgt = canvas.height);
        var hratio = hgt/wid
        var doc = new jsPDF('p','pt','a4');
        var width = doc.internal.pageSize.width;    
        var height = width * hratio
        doc.addImage(img,'JPEG',20,20, width, height);
        doc.save('Test.pdf');
    });

android start activity from service

I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:

 Intent dialogIntent = new Intent(this, myActivity.class);
 dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 this.startActivity(dialogIntent);

and in one my subclasses, stored in a separate file I had to:

public static Service myService;

myService = this;

new SubService(myService);

Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);

All the other answers gave me a nullpointerexception.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:

First

  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)

Second

  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)

References:

Example:

<location path="upl">
   <system.web>
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering>          
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />
       </requestFiltering>
     </security>
   </system.webServer>
 </location>

How to make an anchor tag refer to nothing?

If you don't want to have it point to anything, you probably shouldn't be using the <a> (anchor) tag.

If you want something to look like a link but not act like a link, it's best to use the appropriate element (such as <span>) and then style it using CSS:

<span class="fake-link" id="fake-link-1">Am I a link?</span>

.fake-link {
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}

Also, given that you tagged this question "jQuery", I am assuming that you want to attach a click event hander. If so, just do the same thing as above and then use something like the following JavaScript:

$('#fake-link-1').click(function() {
    /* put your code here */
});

Leaflet - How to find existing markers, and delete markers?

(1) add layer group and array to hold layers and reference to layers as global variables:

var search_group = new L.LayerGroup(); var clickArr = new Array();

(2) add map

(3) Add group layer to map

map.addLayer(search_group);

(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.

 map.on('click', function(e) {
        var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
        clickArr.push(clickPositionMarker);
        mapLat = e.latlng.lat;
        mapLon = e.latlng.lng;
        clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
                .openPopup();   

                /*   clickPositionMarker.on('click', function(e) {
                  markerDelAgain(); 
                }); */


});

(5) The remove function, compare the marker lat long to the id fired in the remove:

$(document).on("click","a[name='removeClickM']", function (e) {

      // Stop form from submitting normally
    e.preventDefault();

    for(i=0;i<clickArr.length;i++) {

    if(search_group.hasLayer(clickArr[i]))
    {
        if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
            {
                hideLayer(search_group,clickArr[i]);
                clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
            }

    }

    }  

Passing arguments to angularjs filters

Actually there is another (maybe better solution) where you can use the angular's native 'filter' filter and still pass arguments to your custom filter.

Consider the following code:

<div ng-repeat="group in groups">
    <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
        <span>{{friend.name}}</span>
    <li>
</div>

To make this work you just define your filter as the following:

$scope.weDontLike = function(name) {
    return function(friend) {
        return friend.name != name;
    }
}

As you can see here, weDontLike actually returns another function which has your parameter in its scope as well as the original item coming from the filter.

It took me 2 days to realise you can do this, haven't seen this solution anywhere yet.

Checkout Reverse polarity of an angular.js filter to see how you can use this for other useful operations with filter.

C convert floating point to int

If you want to round it to lower, just cast it.

float my_float = 42.8f;
int my_int;
my_int = (int)my_float;          // => my_int=42

For other purpose, if you want to round it to nearest, you can make a little function or a define like this:

#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))

float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43

Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.

UnsatisfiedDependencyException: Error creating bean with name

If you describe a field as criteria in method definition ("findBy"), You must pass that parameter to the method, otherwise you will get "Unsatisfied dependency expressed through method parameter" exception.

public interface ClientRepository extends JpaRepository<Client, Integer> {
       Client findByClientId();                ////WRONG !!!!
       Client findByClientId(int clientId);    /// CORRECT 
}

*I assume that your Client entity has clientId attribute.

In Java, how to find if first character in a string is upper case without regex

Don't forget to check whether the string is empty or null. If we forget checking null or empty then we would get NullPointerException or StringIndexOutOfBoundException if a given String is null or empty.

public class StartWithUpperCase{

        public static void main(String[] args){

            String str1 = ""; //StringIndexOfBoundException if 
                              //empty checking not handled
            String str2 = null; //NullPointerException if 
                                //null checking is not handled.
            String str3 = "Starts with upper case";
            String str4 = "starts with lower case";

            System.out.println(startWithUpperCase(str1)); //false
            System.out.println(startWithUpperCase(str2)); //false
            System.out.println(startWithUpperCase(str3)); //true
            System.out.println(startWithUpperCase(str4)); //false



        }

        public static boolean startWithUpperCase(String givenString){

            if(null == givenString || givenString.isEmpty() ) return false;
            else return (Character.isUpperCase( givenString.codePointAt(0) ) );
        }

    }

How to beautify JSON in Python?

First install pygments

then

echo '<some json>' | python -m json.tool | pygmentize -l json

Removing elements from an array in C

Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.

    int remove_element(int*from, int total, int index) {
            if((total - index - 1) > 0) {
                      memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
            }
            return total-1; // return the new array size
    }

Note that memcpy will not work in this case because of the overlapping memory.

One of the efficient way (better than memory move) to remove one random element is swapping with the last element.

    int remove_element(int*from, int total, int index) {
            if(index != (total-1))
                    from[index] = from[total-1];
            return total; // **DO NOT DECREASE** the total here
    }

But the order is changed after the removal.

Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.

    int remove_element(int*from, int total, int*is_valid, int index) {
            is_valid[index] = 0;
            return total-1; // return the number of elements
    }

It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.

    int sparse_to_compact(int*arr, int total, int*is_valid) {
            int i = 0;
            int last = total - 1;
            // trim the last invalid elements
            for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last

            // now we keep swapping the invalid with last valid element
            for(i=0; i < last; i++) {
                    if(is_valid[i])
                            continue;
                    arr[i] = arr[last]; // swap invalid with the last valid
                    last--;
                    for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
            }
            return last+1; // return the compact length of the array
    }

How to change the default message of the required field in the popover of form-control in bootstrap?

$("input[required]").attr("oninvalid", "this.setCustomValidity('Say Somthing!')");

this work if you move to previous or next field by mouse, but by enter key, this is not work !!!

IE and Edge fix for object-fit: cover;

Here is the only CSS solution to fix this. Use the below css.

.row-fluid {
  display: table;
}

.row-fluid .span6 {
  display: table-cell;
  vertical-align: top;
}

.vc_single_image-wrapper {
  position: relative;
}

.vc_single_image-wrapper .image-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
}

HTML from the OP:

<div class="vc_single_image-wrapper   vc_box_border_grey">
  <div class="image-wrapper" style="background-image: url(http://i0.wp.com/www.homedecor.nl/wp-content/uploads/2016/03/Gordijnen-Home-Decor-2.jpg?fit=952%2C480;"></div>
</div>

try this, it should work. also remove float from .row-fluid .span6

How to create own dynamic type or dynamic object in C#?

dynamic MyDynamic = new ExpandoObject();

Unsuccessful append to an empty NumPy array

Here's the result of running your code in Ipython. Note that result is a (2,0) array, 2 rows, 0 columns, 0 elements. The append produces a (2,) array. result[0] is (0,) array. Your error message has to do with trying to assign that 2 item array into a size 0 slot. Since result is dtype=float64, only scalars can be assigned to its elements.

In [65]: result=np.asarray([np.asarray([]),np.asarray([])])

In [66]: result
Out[66]: array([], shape=(2, 0), dtype=float64)

In [67]: result[0]
Out[67]: array([], dtype=float64)

In [68]: np.append(result[0],[1,2])
Out[68]: array([ 1.,  2.])

np.array is not a Python list. All elements of an array are the same type (as specified by the dtype). Notice also that result is not an array of arrays.

Result could also have been built as

ll = [[],[]]
result = np.array(ll)

while

ll[0] = [1,2]
# ll = [[1,2],[]]

the same is not true for result.

np.zeros((2,0)) also produces your result.

Actually there's another quirk to result.

result[0] = 1

does not change the values of result. It accepts the assignment, but since it has 0 columns, there is no place to put the 1. This assignment would work in result was created as np.zeros((2,1)). But that still can't accept a list.

But if result has 2 columns, then you can assign a 2 element list to one of its rows.

result = np.zeros((2,2))
result[0] # == [0,0]
result[0] = [1,2]

What exactly do you want result to look like after the append operation?

How to edit an Android app?

First you have to download file x-plore and installed it.. After that open it and find the thoes you want to edit.. After that just rename the file Xyz.apk to xyz.zip After that open that file and you can see some folders.. then just go and edit the app..

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

Open a folder using Process.Start

Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?

The following code should open a new explorer instance

class sample{

static void Main()
{
  System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");
}
}

Error handling in Bash

Use a trap!

tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  exit "${code}"
}
trap 'error ${LINENO}' ERR

...then, whenever you create a temporary file:

temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )

and $temp_foo will be deleted on exit, and the current line number will be printed. (set -e will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability).

You can either let the trap call error for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:

error ${LINENO} "the foobar failed" 2

will exit with status 2, and give an explicit message.

Xcode Debugger: view value of variable

I agree with other posters that Xcode as a developing environment should include an easy way to debug variables. Well, good news, there IS one!

After searching and not finding a simple answer/tutorial on how to debug variables in Xcode I went to explore with Xcode itself and found this (at least for me) very useful discovery.

How to easily debug your variables in Xcode 4.6.3

In the main screen of Xcode make sure to see the bottom Debug Area by clicking the upper-right corner button showed in the screenshot.

Debug Area button

Debug Area in Xcode 4.6.3

Now set a Breakpoint – the line in your code where you want your program to pause, by clicking the border of your Code Area.

Breakpoint

Now in the Debug Area look for this buttons and click the one in the middle. You will notice your area is now divided in two.

Split Debug Area

Should look like this

Now run your application.

When the first Breakpoint is reached during the execution of your program you will see on the left side all your variables available at that breakpoint.

Search Field

You can expand the left arrows on the variable for a greater detail. And even use the search field to isolate that variable you want and see it change on real time as you "Step into" the scope of the Breakpoint.

Step Into

On the right side of your Debug Area you can send to print the variables as you desire using the mouse's right-button click over the desired variable.

Contextual Menu

As you can see, that contextual menu is full of very interesting debugging options. Such as Watch that has been already suggested with typed commands or even Edit Value… that changes the runtime value of your variable!

jQuery DatePicker with today as maxDate

http://api.jqueryui.com/datepicker/#option-maxDate

$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Use the axis argument:

>> numpy.sum(a, axis=0)
  array([18, 22, 26])

How to check if a file exists in a shell script

If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:

time timeout 3 test -f 
/nfs/my_nfs_is_currently_down
real    0m3.004s <<== timeout is taken into account
user    0m0.001s
sys     0m0.004s
echo $?
124   <= 124 means the timeout has been reached

A "[ -e my_file ]" construct will freeze until the NFS is functional again:

if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi

<no answer from the system, my session is "frozen">

Get value (String) of ArrayList<ArrayList<String>>(); in Java

The right way to iterate on a list inside list is:

//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
    ArrayList<String> currentList = collection.get(i);
    //now iterate on the current list
    for (int j = 0; j < currentList.size(); j++) {
        String s = currentList.get(1);
    }
}

Synchronizing a local Git repository with a remote one

You want to do

git fetch --prune origin
git reset --hard origin/master
git clean -f -d

This makes your local repo exactly like your remote repo.

Remember to replace origin and master with the remote and branch that you want to synchronize with.

How to delete multiple files at once in Bash on Linux?

If you want to delete all files whose names match a particular form, a wildcard (glob pattern) is the most straightforward solution. Some examples:

$ rm -f abc.log.*             # Remove them all
$ rm -f abc.log.2012*         # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]*  # Remove all files from the first quarter of 2012

Regular expressions are more powerful than wildcards; you can feed the output of grep to rm -f. For example, if some of the file names start with "abc.log" and some with "ABC.log", grep lets you do a case-insensitive match:

$ rm -f $(ls | grep -i '^abc\.log\.')

This will cause problems if any of the file names contain funny characters, including spaces. Be careful.

When I do this, I run the ls | grep ... command first and check that it produces the output I want -- especially if I'm using rm -f:

$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)

where !! expands to the previous command. Or I can type up-arrow or Ctrl-P and edit the previous line to add the rm -f command.

This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the $(...) syntax. You can use the equivalent backtick syntax:

$ rm -f `ls | grep -i '^abc\.log\.'`

The $(...) syntax is easier to read, and if you're really ambitious it can be nested.

Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:

$ ls > list
$ vi list   # Use your favorite text editor

I can then edit the list file manually, leaving only the files I want to remove, and then:

$ rm -f $(<list)

or

$ rm -f `cat list`

(Again, this assumes none of the file names contain funny characters, particularly spaces.)

Or, when editing the list file, I can add rm -f to the beginning of each line and then:

$ . ./list

or

$ source ./list

Editing the file is also an opportunity to add quotes where necessary, for example changing rm -f foo bar to rm -f 'foo bar' .

Easy way to turn JavaScript array into comma-separated list?

As of Chrome 72, it's possible to use Intl.ListFormat:

_x000D_
_x000D_
const vehicles = ['Motorcycle', 'Bus', 'Car'];_x000D_
_x000D_
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });_x000D_
console.log(formatter.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus, and Car"_x000D_
_x000D_
const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });_x000D_
console.log(formatter2.format(vehicles));_x000D_
// expected output: "Motorcycle, Bus oder Car"_x000D_
_x000D_
const formatter3 = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });_x000D_
console.log(formatter3.format(vehicles));_x000D_
// expected output: "Motorcycle Bus Car"
_x000D_
_x000D_
_x000D_

Please note that this way is in its very earlier stage, so as of the date of posting this answer, expect incompatibility with older versions of Chrome and other browsers.

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

Python: create dictionary using dict() with integer keys?

Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

How do I use valgrind to find memory leaks?

Try this:

valgrind --leak-check=full -v ./your_program

As long as valgrind is installed it will go through your program and tell you what's wrong. It can give you pointers and approximate places where your leaks may be found. If you're segfault'ing, try running it through gdb.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

How to configure robots.txt to allow everything?

It means you allow every (*) user-agent/crawler to access the root (/) of your site. You're okay.

how to sort pandas dataframe from one column

Just adding some more operations on data. Suppose we have a dataframe df, we can do several operations to get desired outputs

ID         cost      tax    label
1       216590      1600    test      
2       523213      1800    test 
3          250      1500    experiment

(df['label'].value_counts().to_frame().reset_index()).sort_values('label', ascending=False)

will give sorted output of labels as a dataframe

    index   label
0   test        2
1   experiment  1

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

Is there a difference between x++ and ++x in java?

Yes, the value returned is the value after and before the incrementation, respectively.

class Foo {
    public static void main(String args[]) {
        int x = 1;
        int a = x++;
        System.out.println("a is now " + a);
        x = 1;
        a = ++x;
        System.out.println("a is now " + a);
    }
}

$ java Foo
a is now 1
a is now 2

MVC Form not able to post List of objects

Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId, planCompareViewModel[1].PlanId to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model) use for loop and render names with indexes.

When to use std::size_t?

size_t is an unsigned integral type, that can represent the largest integer on you system. Only use it if you need very large arrays,matrices etc.

Some functions return an size_t and your compiler will warn you if you try to do comparisons.

Avoid that by using a the appropriate signed/unsigned datatype or simply typecast for a fast hack.

How to push local changes to a remote git repository on bitbucket

This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.

To push all local branches to the remote repository, use --all:

git push REMOTENAME --all
git push --all

or specify all branches you want to push:

git push REMOTENAME master exp-branch-a anotherbranch bugfix

In addition, it's useful to add -u to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.

SQL changing a value to upper or lower case

You can do:

SELECT lower(FIRST NAME) ABC
FROM PERSON

NOTE: ABC is used if you want to change the name of the column

What are the main performance differences between varchar and nvarchar SQL Server data types?

If you are using NVARCHAR just because a system stored procedure requires it, the most frequent occurrence being inexplicably sp_executesql, and your dynamic SQL is very long, you would be better off from performance perspective doing all string manipulations (concatenation, replacement etc.) in VARCHAR then converting the end result to NVARCHAR and feeding it into the proc parameter. So no, do not always use NVARCHAR!

If WorkSheet("wsName") Exists

Slightly changed to David Murdoch's code for generic library

Function HasByName(cSheetName As String, _ 
                   Optional oWorkBook As Excel.Workbook) As Boolean

    HasByName = False
    Dim wb

    If oWorkBook Is Nothing Then
        Set oWorkBook = ThisWorkbook
    End If

    For Each wb In oWorkBook.Worksheets
        If wb.Name = cSheetName Then
            HasByName = True
            Exit Function
        End If
    Next wb
End Function

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

String was not recognized as a valid DateTime " format dd/MM/yyyy"

private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Is it possible to print a variable's type in standard C++?

Copying from this answer: https://stackoverflow.com/a/56766138/11502722

I was able to get this somewhat working for C++ static_assert(). The wrinkle here is that static_assert() only accepts string literals; constexpr string_view will not work. You will need to accept extra text around the typename, but it works:

template<typename T>
constexpr void assertIfTestFailed()
{
#ifdef __clang__
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(__GNUC__)
    static_assert(testFn<T>(), "Test failed on this used type: " __PRETTY_FUNCTION__);
#elif defined(_MSC_VER)
    static_assert(testFn<T>(), "Test failed on this used type: " __FUNCSIG__);
#else
    static_assert(testFn<T>(), "Test failed on this used type (see surrounding logged error for details).");
#endif
    }
}

MSVC Output:

error C2338: Test failed on this used type: void __cdecl assertIfTestFailed<class BadType>(void)
... continued trace of where the erroring code came from ...

How can I read command line parameters from an R script?

I just put together a nice data structure and chain of processing to generate this switching behaviour, no libraries needed. I'm sure it will have been implemented numerous times over, and came across this thread looking for examples - thought I'd chip in.

I didn't even particularly need flags (the only flag here is a debug mode, creating a variable which I check for as a condition of starting a downstream function if (!exists(debug.mode)) {...} else {print(variables)}). The flag checking lapply statements below produce the same as:

if ("--debug" %in% args) debug.mode <- T
if ("-h" %in% args || "--help" %in% args) 

where args is the variable read in from command line arguments (a character vector, equivalent to c('--debug','--help') when you supply these on for instance)

It's reusable for any other flag and you avoid all the repetition, and no libraries so no dependencies:

args <- commandArgs(TRUE)

flag.details <- list(
"debug" = list(
  def = "Print variables rather than executing function XYZ...",
  flag = "--debug",
  output = "debug.mode <- T"),
"help" = list(
  def = "Display flag definitions",
  flag = c("-h","--help"),
  output = "cat(help.prompt)") )

flag.conditions <- lapply(flag.details, function(x) {
  paste0(paste0('"',x$flag,'"'), sep = " %in% args", collapse = " || ")
})
flag.truth.table <- unlist(lapply(flag.conditions, function(x) {
  if (eval(parse(text = x))) {
    return(T)
  } else return(F)
}))

help.prompts <- lapply(names(flag.truth.table), function(x){
# joins 2-space-separatated flags with a tab-space to the flag description
  paste0(c(paste0(flag.details[x][[1]][['flag']], collapse="  "),
  flag.details[x][[1]][['def']]), collapse="\t")
} )

help.prompt <- paste(c(unlist(help.prompts),''),collapse="\n\n")

# The following lines handle the flags, running the corresponding 'output' entry in flag.details for any supplied
flag.output <- unlist(lapply(names(flag.truth.table), function(x){
  if (flag.truth.table[x]) return(flag.details[x][[1]][['output']])
}))
eval(parse(text = flag.output))

Note that in flag.details here the commands are stored as strings, then evaluated with eval(parse(text = '...')). Optparse is obviously desirable for any serious script, but minimal-functionality code is good too sometimes.

Sample output:

$ Rscript check_mail.Rscript --help
--debug Print  variables rather than executing function XYZ...

-h  --help  Display flag definitions

Remove all items from a FormArray in Angular

Warning!

The Angular v6.1.7 FormArray documentation says:

To change the controls in the array, use the push, insert, or removeAt methods in FormArray itself. These methods ensure the controls are properly tracked in the form's hierarchy. Do not modify the array of AbstractControls used to instantiate the FormArray directly, as that result in strange and unexpected behavior such as broken change detection.

Keep this in mind if you are using the splice function directly on the controls array as one of the answer suggested.

Use the removeAt function.

  while (formArray.length !== 0) {
    formArray.removeAt(0)
  }

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I faced the same problem when after installing Viber. It had all required qt libraries in /opt/viber/plugins/. I checked dependencies of /opt/viber/plugins/platforms/libqxcb.so and found missing dependencies. They were libxcb-render.so.0, libxcb-image.so.0, libxcb-icccm.so.4, libxcb-xkb.so.1 So I resolved my issue by installing missing packages with this libraries:

apt-get install libxcb-xkb1 libxcb-icccm4 libxcb-image0 libxcb-render-util0

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

How to order by with union in SQL?

Just write

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name

the order by is applied to the complete resultset

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

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:

<script type="text/javascript">
function recp(id) {
  $('#myStyle').load('data.php?id=' + id);
}
</script>

<a href="#" onClick="recp('1')" > One   </a>
<a href="#" onClick="recp('2')" > Two   </a>
<a href="#" onClick="recp('3')" > Three </a>

<div id='myStyle'>
</div>

Then you put your PHP code into a separate file: (I've called it data.php in the above example)

<?php
  require ('myConnect.php');     
  $id = $_GET['id'];
  $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");   
  if( mysql_num_rows($results) > 0 )
  {
   $row = mysql_fetch_array( $results );
   echo $row['para'];
  }
?>

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

Access-Control-Allow-Origin and Angular.js $http

@Swapnil Niwane

I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.

$.ajax({
          method: 'GET',
          url: url,
          defaultHeaders: {
              'Content-Type': 'application/json',
              "Access-Control-Allow-Origin": "*",
              'Accept': 'application/json'
           },

          dataType: 'jsonp',

          success: function (response) {
            console.log("success ");
            console.log(response);
          },
          error: function (xhr) {
            console.log("error ");
            console.log(xhr);
          }
});

How to use DISTINCT and ORDER BY in same SELECT statement?

Try next, but it's not useful for huge data...

SELECT DISTINCT Cat FROM (
  SELECT Category as Cat FROM MonitoringJob ORDER BY CreationDate DESC
);

Toggle Class in React

Toggle function in react

At first you should create constructor like this

constructor(props) {
        super(props);
        this.state = {
            close: true,
        };
    }

Then create a function like this

yourFunction = () => {
        this.setState({
            close: !this.state.close,
        });
    };

then use this like

render() {
        const {close} = this.state;
        return (

            <Fragment>

                 <div onClick={() => this.yourFunction()}></div>

                 <div className={close ? "isYourDefaultClass" : "isYourOnChangeClass"}></div>

            </Fragment>
        )
    }
}

Please give better solutions

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

remove item from array using its name / value

you can use delete operator to delete property by it's name

delete objectExpression.property

or iterate through the object and find the value you need and delete it:

for(prop in Obj){
   if(Obj.hasOwnProperty(prop)){
      if(Obj[prop] === 'myValue'){
        delete Obj[prop];
      }
   }
}

Node JS Promise.all and forEach

It's pretty straightforward with some simple rules:

  • Whenever you create a promise in a then, return it - any promise you don't return will not be waited for outside.
  • Whenever you create multiple promises, .all them - that way it waits for all the promises and no error from any of them are silenced.
  • Whenever you nest thens, you can typically return in the middle - then chains are usually at most 1 level deep.
  • Whenever you perform IO, it should be with a promise - either it should be in a promise or it should use a promise to signal its completion.

And some tips:

  • Mapping is better done with .map than with for/push - if you're mapping values with a function, map lets you concisely express the notion of applying actions one by one and aggregating the results.
  • Concurrency is better than sequential execution if it's free - it's better to execute things concurrently and wait for them Promise.all than to execute things one after the other - each waiting before the next.

Ok, so let's get started:

var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
    return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns

var actions = items.map(fn); // run the function over all items

// we now have a promises array and we want to wait for it

var results = Promise.all(actions); // pass array of promises

results.then(data => // or just .then(console.log)
    console.log(data) // [2, 4, 6, 8, 10]
);

// we can nest this of course, as I said, `then` chains:

var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
    data => Promise.all(data.map(fn))
).then(function(data){
    // the next `then` is executed after the promise has returned from the previous
    // `then` fulfilled, in this case it's an aggregate promise because of 
    // the `.all` 
    return Promise.all(data.map(fn));
}).then(function(data){
    // just for good measure
    return Promise.all(data.map(fn));
});

// now to get the results:

res2.then(function(data){
    console.log(data); // [16, 32, 48, 64, 80]
});

How do I center a Bootstrap div with a 'spanX' class?

Twitter's bootstrap .span classes are floated to the left so they won't center by usual means. So, if you want it to center your span simply add float:none to your #main rule.

CSS

#main {
 margin:0 auto;
 float:none;
}

What Does This Mean in PHP -> or =>

=> is used in associative array key value assignment. Take a look at:

http://php.net/manual/en/language.types.array.php.

-> is used to access an object method or property. Example: $obj->method().

How can I generate a 6 digit unique number?

<?php
$file = 'count.txt';

//get the number from the file
$uniq = file_get_contents($file);

//add +1
$id = $uniq + 1 ;

// add that new value to text file again for next use
file_put_contents($file, $id);

// your unique id ready
echo $id;
?>

i hope this will work fine. i use the same technique in my website.

ie8 var w= window.open() - "Message: Invalid argument."

When you call window.open in IE, the second argument (window name) has to be either one of the predefined target strings or a string, which has a form of a valid identifier in JavaScript.

So what works in Firefox: "Job Directory 9463460", does not work in Internet Exploder, and has to be replaced by: "Job_Directory_9463460" for example (no spaces, no minus signs, no dots, it has to be a valid identifier).

Removing nan values from an array

If you're using numpy for your arrays, you can also use

x = x[numpy.logical_not(numpy.isnan(x))]

Equivalently

x = x[~numpy.isnan(x)]

[Thanks to chbrown for the added shorthand]

Explanation

The inner function, numpy.isnan returns a boolean/logical array which has the value True everywhere that x is not-a-number. As we want the opposite, we use the logical-not operator, ~ to get an array with Trues everywhere that x is a valid number.

Lastly we use this logical array to index into the original array x, to retrieve just the non-NaN values.

Where do I call the BatchNormalization function in Keras?

It's almost become a trend now to have a Conv2D followed by a ReLu followed by a BatchNormalization layer. So I made up a small function to call all of them at once. Makes the model definition look a whole lot cleaner and easier to read.

def Conv2DReluBatchNorm(n_filter, w_filter, h_filter, inputs):
    return BatchNormalization()(Activation(activation='relu')(Convolution2D(n_filter, w_filter, h_filter, border_mode='same')(inputs)))

Why am I getting the message, "fatal: This operation must be run in a work tree?"

The direct reason for the error is that yes, it's impossible to use git-add with a bare repository. A bare repository, by definition, has no work tree. git-add takes files from the work tree and adds them to the index, in preparation for committing.

You may need to put a bit of thought into your setup here, though. GIT_DIR is the repository directory used for all git commands. Are you really trying to create a single repository for everything you track, maybe things all over your system? A git repository by nature tracks the contents of a single directory. You'll need to set GIT_WORK_TREE to a path containing everything you want to track, and then you'll need a .gitignore to block out everything you're not interested in tracking.

Maybe you're trying to create a repository which will track just c:\www? Then you should put it in c:\www (don't set GIT_DIR). This is the normal usage of git, with the repository in the .git directory of the top-level directory of your "module".

Unless you have a really good reason, I'd recommend sticking with the way git likes to work. If you have several things to track, you probably want several repositories!

Ant: How to execute a command for each file in directory?

An approach without ant-contrib is suggested by Tassilo Horn (the original target is here)

Basicly, as there is no extension of <java> (yet?) in the same way that <apply> extends <exec>, he suggests to use <apply> (which can of course also run a java programm in a command line)

Here some examples:

  <apply executable="java"> 
    <arg value="-cp"/> 
    <arg pathref="classpath"/> 
    <arg value="-f"/> 
    <srcfile/> 
    <arg line="-o ${output.dir}"/> 

    <fileset dir="${input.dir}" includes="*.txt"/> 
  </apply> 

Is it possible to program Android to act as physical USB keyboard?

I believe that you can do it if you have a rooted device with a recent Android. For example, the Asus Eee Pad Transformer running Android 4 has the libraries /system/lib/libusb.so and /system/lib/libusbhost.so, so you can write a Java application that calls them using JNI to emulate a USB keyboard. This means that you must write some glue C code that emulates the way a USB keyboard is communicating with a PC (=you must study the way the USB protocol works).

I say "rooted", because some permissions are usually needed to use these libraries.

Edit: The above is true when programming an Android device to act as a USB host, in your case you need to be a "gadget". I don't know how much of the Linux gadget functionality is contained in the kernel of your Android device. See this for a similar question.

Align DIV's to bottom or baseline

Use the CSS display values of table and table-cell:

HTML

<html>
<body>

  <div class="valign bottom">
    <div>

      <div>my bottom aligned div 1</div>
      <div>my bottom aligned div 2</div>
      <div>my bottom aligned div 3</div>

    </div>
  </div>

</body>
</html>

CSS

html,body {
    width: 100%;
    height: 100%;
}
.valign {
    display: table;
    width: 100%;
    height: 100%;
}
.valign > div {
    display: table-cell;
    width: 100%;
    height: 100%;
}
.valign.bottom > div {
    vertical-align: bottom;
}

I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit

The demo also has an example how to vertically center align using the same technique.

Get hostname of current request in node.js Express

First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.

Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.

The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse method for more info. But then, again, note that an IP might have multiple names associated with it.

How do I use cx_freeze?

You can change the setup.py code to this:

    from cx_freeze import setup, Executable
    setup( name = "foo",
           version = "1.1",
           description = "Description of the app here.",
           executables = [Executable("foo.py")]
         )

I am sure it will work. I have tried it on both windows 7 as well as ubuntu 12.04

possibly undefined macro: AC_MSG_ERROR

I had the same problem with the Macports port "openocd" (locally modified the Portfile to use the git repository) on a freshly installed machine.

The permanent fix is easy, define a dependency to pkgconfig in the Portfile: depends_lib-append port:pkgconfig

PHP cURL HTTP PUT

In a POST method, you can put an array. However, in a PUT method, you should use http_build_query to build the params like this:

curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );

Byte Array to Image object

According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).

jQuery - simple input validation - "empty" and "not empty"

Actually there is a simpler way to do this, just:

if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}

src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

if var == False

Use not

var = False
if not var:
    print 'learnt stuff'

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?

The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

TypeError: method() takes 1 positional argument but 2 were given

It occurs when you don't specify the no of parameters the __init__() or any other method looking for.

For example:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme, it gives you an error like that:

TypeError: __init__() takes 1 positional argument but 6 were given

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

How do I merge changes to a single file, rather than merging commits?

I found this approach simple and useful: How to "merge" specific files from another branch

As it turns out, we’re trying too hard. Our good friend git checkout is the right tool for the job.

git checkout source_branch <paths>...

We can simply give git checkout the name of the feature branch A and the paths to the specific files that we want to add to our master branch.

Please read the whole article for more understanding

Singleton in Android

EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

How to make a edittext box in a dialog

Simplified version

final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Add a new task")
        .setMessage("What do you want to do next?")
        .setView(taskEditText)
        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String task = String.valueOf(taskEditText.getText());
                SQLiteDatabase db = mHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
                db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
                        null,
                        values,
                        SQLiteDatabase.CONFLICT_REPLACE);
                db.close();
                updateUI();
            }
        })
        .setNegativeButton("Cancel", null)
        .create();
dialog.show();
return true;

Find a private field with Reflection?

Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).

The binding flag you will need is: System.Reflection.BindingFlags.NonPublic

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

How to use target in location.href

If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.

// Code by @qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)

Maybe someone could post a comment to his post, because I cannot.

What's the difference between align-content and align-items?

Having read some of the answers, they identify correctly that align-content takes no affect if the flex content is not wrapped. However what they don't understand is align-items still plays an important role when there is wrapped content:

In the following two examples, align-items is used to center the items within each row, then we change align-content to see it's effect.

Example 1:

align-content: flex-start;

enter image description here

Example 2:

    align-content: flex-end;

enter image description here

Here's the code:

<div class="container">
    <div class="child" style="height: 30px;">1</div>
    <div class="child" style="height: 50px;">2</div>
    <div class="child" style="height: 60px;">3</div>
    <div class="child" style="height: 40px;">4</div>
    <div class="child" style="height: 50px;">5</div>
    <div class="child" style="height: 20px;">6</div>
    <div class="child" style="height: 90px;">7</div>
    <div class="child" style="height: 50px;">8</div>
    <div class="child" style="height: 30px;">9</div>
    <div class="child" style="height: 40px;">10</div>
    <div class="child" style="height: 30px;">11</div>
    <div class="child" style="height: 60px;">12</div>
</div>

<style>
.container {
    display: flex;
    width: 300px;
    flex-flow: row wrap;
    justify-content: space-between;
    align-items: center;
    align-content: flex-end;
    background: lightgray;
    height: 400px;
}
.child {
    padding: 12px;
    background: red;
    border: solid 1px black;
}
</style>

Convert audio files to mp3 using ffmpeg

For batch processing files in folder:

for i in *.wav; do ffmpeg -i "$i" -f mp3 "${i%}.mp3"; done

This script converts all "wav" files in folder to mp3 files and adds mp3 extension

ffmpeg have to be installed. (See other answers)

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

This worked for me. may help some one. Turn off firewall. on RHEL 7

systemctl stop  firewalld

Entity Framework is Too Slow. What are my options?

If you're purely fetching data, it's a big help to performance when you tell EF to not keep track of the entities it fetches. Do this by using MergeOption.NoTracking. EF will just generate the query, execute it and deserialize the results to objects, but will not attempt to keep track of entity changes or anything of that nature. If a query is simple (doesn't spend much time waiting on the database to return), I've found that setting it to NoTracking can double query performance.

See this MSDN article on the MergeOption enum:

Identity Resolution, State Management, and Change Tracking

This seems to be a good article on EF performance:

Performance and the Entity Framework

Insert multiple rows with one query MySQL

Here are a few ways to do it

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip' 
from SOMETABLEWITHTONSOFROWS LIMIT 3;

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')

How exactly does __attribute__((constructor)) work?

  1. It runs when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

Formatting a double to two decimal places

Since you are working in currency why not simply do this:

Console.Writeline("Earnings this week: {0:c}", answer);

This will format answer as currency, so on my machine (UK) it will come out as:

Earnings this week: £209.00

Changing Placeholder Text Color with Swift

    extension UITextField{
            @IBInspectable var placeHolderColor: UIColor? {
                get {
                    return self.placeHolderColor
                }
                set {
                    self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ?
        self.placeholder! : "",
        attributes:[NSAttributedString.Key.foregroundColor : newValue!])
                }
            } 
}

Total memory used by Python process?

Below is my function decorator which allows to track how much memory this process consumed before the function call, how much memory it uses after the function call, and how long the function is executed.

import time
import os
import psutil


def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))


def get_process_memory():
    process = psutil.Process(os.getpid())
    return process.memory_info().rss


def track(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

So, when you have some function decorated with it

from utils import track

@track
def list_create(n):
    print("inside list create")
    return [1] * n

You will be able to see this output:

inside list create
list_create: memory before: 45,928,448, after: 46,211,072, consumed: 282,624; exec time: 00:00:00

Read/Parse text file line by line in VBA

For completeness; working with the data loaded into memory;

dim hf As integer: hf = freefile
dim lines() as string, i as long

open "c:\bla\bla.bla" for input as #hf
    lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf

for i = 0 to ubound(lines)
    debug.? "Line"; i; "="; lines(i)
next

How to loop over a Class attributes in Java?

There is no linguistic support to do what you're asking for.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

See also

Related questions


Example

Here's a simple example to show only some of what reflection is capable of doing.

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

Aligning label and textbox on same line (left and right)

you can use style

   <td  colspan="2">
     <div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>

    <div style="float: right; width:100px">    
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    </div>

     <div style="clear:both"></div>

    </td>

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

Where is the php.ini file on a Linux/CentOS PC?

php -i |grep 'Configuration File'

Using :before CSS pseudo element to add image to modal

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

.Modal:before{
  content: '';
  background:url('blackCarrot.png');
  width: /* width of the image */;
  height: /* height of the image */;
  display: block;
}

Start/Stop and Restart Jenkins service on Windows

Step 01: You need to add jenkins for environment variables, Then you can use jenkins commands

Step 02: Go to "C:\Program Files (x86)\Jenkins" with admin prompt

Step 03: Choose your option: jenkins.exe stop / jenkins.exe start / jenkins.exe restart

Configuring Log4j Loggers Programmatically

It sounds like you're trying to use log4j from "both ends" (the consumer end and the configuration end).

If you want to code against the slf4j api but determine ahead of time (and programmatically) the configuration of the log4j Loggers that the classpath will return, you absolutely have to have some sort of logging adaptation which makes use of lazy construction.

public class YourLoggingWrapper {
    private static boolean loggingIsInitialized = false;

    public YourLoggingWrapper() {
        // ...blah
    }

    public static void debug(String debugMsg) {
        log(LogLevel.Debug, debugMsg);
    }

    // Same for all other log levels your want to handle.
    // You mentioned TRACE and ERROR.

    private static void log(LogLevel level, String logMsg) {
        if(!loggingIsInitialized)
            initLogging();

        org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");

        switch(level) {
        case: Debug:
            logger.debug(logMsg);
            break;
        default:
            // whatever
        }
    }

    // log4j logging is lazily constructed; it gets initialized
    // the first time the invoking app calls a log method
    private static void initLogging() {
        loggingIsInitialized = true;

        org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");

        // Now all the same configuration code that @oers suggested applies...
        // configure the logger, configure and add its appenders, etc.
        debugLogger.addAppender(someConfiguredFileAppender);
    }

With this approach, you don't need to worry about where/when your log4j loggers get configured. The first time the classpath asks for them, they get lazily constructed, passed back and made available via slf4j. Hope this helped!

Close window automatically after printing dialog closes

An entirely different approach using native things only

First, add the following in the page that is to be printed

<head>
<title>printing please wait</title>
<META http-equiv=Refresh content=2;url="close.html">
</head>
<body onLoad="window.print()">

Then make close.html with following content

<body onLoad="window.close()"></body>

Now when the print dialogue is displayed, the page will remain open. As soon as the print or cancel task is done, the page will close like a breeze.

how to take user input in Array using java?

import java.util.Scanner;

class Example{

//Checks to see if a string is consider an integer.

public static boolean isInteger(String s){

    if(s.isEmpty())return false;

    for (int i = 0; i <s.length();++i){

        char c = s.charAt(i);

        if(!Character.isDigit(c) && c !='-')

            return false;
    }

    return true;
}

//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.

public static int getInteger(String prompt){
    Scanner input = new Scanner(System.in);
    String in = "";
    System.out.println(prompt);
    in = input.nextLine();
    while(!isInteger(in)){
        System.out.println(prompt);
        in = input.nextLine();
    }
    input.close();
    return Integer.parseInt(in);
}

public static void main(String[] args){
    int [] a = new int[6];
    for (int i = 0; i < a.length;++i){
        int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
        a[i] = tmp;
    }

}

}

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

At first you should check major version of compiled problematic .class file, in your case map/CareMonths. See this answer how to do it.

WAS7 uses Java 6 (as said Jacek), and Java 6 uses major version 50, so you have to compile your project with Java 6. How to set proper version of Java compiler depends on your IDE (e.g. Eclipse, IntelliJ) or build tool (e.g. Maven, Ant).

Pass Multiple Parameters to jQuery ajax call

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',      
    data: "jewellerId=" + filter+ "&locale=" +  locale,  
    success: AjaxSucceeded,
    error: AjaxFailed
});

How to easily get network path to the file you are working on?

Right click on the ribbon and choose Customize the ribbon. From the Choose commands from: drop down, select Commands not in the ribbon.

That is where I found the Document location command.

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url. For that just access this http://host/ReportServer/ and from there you can go to the report pages. There append your parmaters like this &<parameter>=<value>

For more detailed information:

http://dobrzanski.net/2008/08/11/reporting-services-problem-with-passing-parameters-directly-in-the-url/

https://www.mssqltips.com/sqlservertip/1336/pass-parameters-and-options-with-a-url-in-sql-reporting-services/

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

querySelector can be a complete CSS(3)-Selector with IDs and Classes and Pseudo-Classes together like this:

'#id.class:pseudo'

// or

'tag #id .class .class.class'

with getElementsByClassName you can just define a class

'class'

with getElementById you can just define an id

'id'

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

gdb fails with "Unable to find Mach task port for process-id" error

This link had the clearest and most detailed step-by-step to make this error disappear for me.

In my case I had to have the key as a "System" key otherwise it did not work (which not every url mentions).

Also killing taskgated is a viable (and quicker) alternative to having to restart.

I also uninstalled MacPorts before I started this process and uninstalled the current gdb using brew uninstall gdb.

Execute JavaScript code stored as a string

For users that are using node and that are concerned with the context implications of eval() nodejs offers vm. It creates a V8 virtual machine that can sandbox the execution of your code in a separate context.

Taking things a step further is vm2 which hardens vm allowing the vm to run untrusted code.

const vm = require('vm');

const x = 1;

const sandbox = { x: 2 };
vm.createContext(sandbox); // Contextify the sandbox.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the sandboxed environment.
// Initially, x has the value 2 because that is the value of sandbox.x.
vm.runInContext(code, sandbox);

console.log(sandbox.x); // 42
console.log(sandbox.y); // 17

console.log(x); // 1; y is not defined.

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

Running a CMD or BAT in silent mode

I'm created RunApp to do such a job and also using it in my production env, hope it's helps.

The config like below:

file: config.arg

:style:hidden

MyBatchFile.bat
arg1
arg2

And launch runapp.exe instead.

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

In my opinion the easiest and fastest way to get a Google Drive file ID is from Google Drive on the web. Right-click the file name and select Get shareable link. The last part of the link is the file ID. Then you can cancel the sharing.

How to remove leading and trailing white spaces from a given html string?

var str = "  my awesome string   "
str.trim();    

for old browsers, use regex

str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string" 

Android: Creating a Circular TextView?

You can try this in round_tv.xml in drawable folder:

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

    <stroke android:color="#22ff55" android:width="3dip"/>

    <corners
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />

    <size
        android:height="60dp"
        android:width="60dp" />

</shape>

Apply that drawable in your textviews as:

<TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/round_tv"
    android:gravity="center_vertical|center_horizontal"
    android:text="ddd"
    android:textColor="#000"
    android:textSize="20sp" />

Output:

enter image description here

Hope this helps.

Edit: If your text is too long, Oval shape is more preferred.

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

    <stroke android:color="#55ff55" android:width="3dip"/>

    <corners
        android:bottomLeftRadius="30dp"
        android:bottomRightRadius="30dp"
        android:topLeftRadius="30dp"
        android:topRightRadius="30dp" />

    <size
        android:height="60dp"
        android:width="60dp" />

</shape>

Output:

enter image description here

If you still need it a proper circle, then I guess you will need to set its height dynamically after setting text in it, new height should be as much as its new width so as to make a proper circle.

Compare integer in bash, unary operator expected

Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?

A common mistake is also not to leave a space after and before the square brackets.

What does java:comp/env/ do?

Quoting https://web.archive.org/web/20140227201242/http://v1.dione.zcu.cz/java/docs/jndi-1.2/tutorial/beyond/misc/policy.html

At the root context of the namespace is a binding with the name "comp", which is bound to a subtree reserved for component-related bindings. The name "comp" is short for component. There are no other bindings at the root context. However, the root context is reserved for the future expansion of the policy, specifically for naming resources that are tied not to the component itself but to other types of entities such as users or departments. For example, future policies might allow you to name users and organizations/departments by using names such as "java:user/alice" and "java:org/engineering".

In the "comp" context, there are two bindings: "env" and "UserTransaction". The name "env" is bound to a subtree that is reserved for the component's environment-related bindings, as defined by its deployment descriptor. "env" is short for environment. The J2EE recommends (but does not require) the following structure for the "env" namespace.

So the binding you did from spring or, for example, from a tomcat context descriptor go by default under java:comp/env/

For example, if your configuration is:

<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="foo"/>
</bean>

Then you can access it directly using:

Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/foo");

or you could make an intermediate step so you don't have to specify "java:comp/env" for every resource you retrieve:

Context ctx = new InitialContext();
Context envCtx = (Context)ctx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("foo");

ORA-01438: value larger than specified precision allows for this column

The error seems not to be one of a character field, but more of a numeric one. (If it were a string problem like WW mentioned, you'd get a 'value too big' or something similar.) Probably you are using more digits than are allowed, e.g. 1,000000001 in a column defined as number (10,2).

Look at the source code as WW mentioned to figure out what column may be causing the problem. Then check the data if possible that is being used there.

Datetime format Issue: String was not recognized as a valid DateTime

This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.

So first split it by slash

var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2] 


var properFormat = month + "/" +day +"/" + year;

Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

As mentioned here, you need to remove the unused references and the warnings will go.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

I think i understand what the reason of your error. First you click auto AUTO INCREMENT field then select it as a primary key.

The Right way is First You have to select it as a primary key then you have to click auto AUTO INCREMENT field.

Very easy. Thanks

How to declare a local variable in Razor?

You can also use:

@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}

No need for a variable in the code

Hex transparency in colors

Here's a correct table of percentages to hex values. E.g. for 50% white you'd use #80FFFFFF.

  • 100% — FF
  • 95% — F2
  • 90% — E6
  • 85% — D9
  • 80% — CC
  • 75% — BF
  • 70% — B3
  • 65% — A6
  • 60% — 99
  • 55% — 8C
  • 50% — 80
  • 45% — 73
  • 40% — 66
  • 35% — 59
  • 30% — 4D
  • 25% — 40
  • 20% — 33
  • 15% — 26
  • 10% — 1A
  • 5% — 0D
  • 0% — 00

(source)

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I got the following error:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)

I fixed this by changing my hibernate properties file

hibernate.current_session_context_class=thread

My code and configuration file as follows

session =  getHibernateTemplate().getSessionFactory().getCurrentSession();

session.beginTransaction();

session.createQuery(Qry).executeUpdate();

session.getTransaction().commit();

on properties file

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.query_factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory

hibernate.current_session_context_class=thread

on cofiguration file

<properties>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>         
<prop key="hibernate.query.factory_class">${hibernate.query_factory_class}</prop>       
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
</props>
</property>
</properties>

Thanks,
Ashok

SQL Query to fetch data from the last 30 days?

Try this : Using this you can select data from last 30 days

SELECT
    *
FROM
    product
WHERE
    purchase_date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH)