Programs & Examples On #Path finding

Pathfinding generally refers to the problem of finding the shortest route between two points, subject to any obstacles. Pathfinding has application in a wide range of areas including robotics and game development. Algorithms for pathfinding tend to be closely related to graph and tree search algorithms.

What algorithms compute directions from point A to point B on a map?

I see what's up with the maps in the OP:

Look at the route with the intermediate point specified: The route goes slightly backwards due to that road that isn't straight.

If their algorithm won't backtrack it won't see the shorter route.

Android TextView Text not getting wrapped

I finally managed to add some pixels to the height of the TextView to solve this issue.

First you need to actually get the height of the TextView. It's not straightforward because it's 0 before it's already painted.

Add this code to onCreate:

mReceiveInfoTextView = (TextView) findViewById(R.id.receive_info_txt);
if (mReceiveInfoTextView != null) { 
    final ViewTreeObserver observer = mReceiveInfoTextView.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int height = mReceiveInfoTextView.getHeight();
            int addHeight = getResources().getDimensionPixelSize(R.dimen.view_add_height);
            mReceiveInfoTextView.setHeight(height + addHeight);

            // Remove the listener if possible
            ViewTreeObserver viewTreeObserver = mReceiveInfoTextView.getViewTreeObserver();
            if (viewTreeObserver.isAlive()) {
                viewTreeObserver.removeOnGlobalLayoutListener(this);
            }
        }
    });
}

You need to add this line to dimens.xml

<dimen name="view_add_height">10dp</dimen>

Hope it helps.

How to get response status code from jQuery.ajax?

jqxhr is a json object:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

see: jQuery ajax

so you would do:

jqxhr.status to get the status

Sending emails in Node.js?

You definitely want to use https://github.com/niftylettuce/node-email-templates since it supports nodemailer/postmarkapp and has beautiful async email template support built-in.

How do I change the language of moment.js?

First Call , p5.js and moment-with-locales.js and then do code like below and you will get your result.

In this result I have showed Month Name in different language :)

Check code please :

_x000D_
_x000D_
     var monthNameEnglish = moment().locale('en-gb').format('MMMM');
    document.getElementById('monthNameEnglish').innerHTML =  monthNameEnglish;
    
    
         var monthNameGerman = moment().locale('de').format('MMMM');
    document.getElementById('monthNameGerman').innerHTML =  monthNameGerman;
_x000D_
<!DOCTYPE html>
<html>
    <head>
        <title>P5.js and Moment.js</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment-with-locales.js"></script>
    
    <h3>English Version Month Name</h3>
    
    <p id="monthNameEnglish"></p>
    
    <h3> German Version Month Name</h3>
    
    <p id="monthNameGerman"></p>
        
    </head>
    <body>
    </body>
</html>
_x000D_
_x000D_
_x000D_

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

Find indices of elements equal to zero in a NumPy array

numpy.where() is my favorite.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])

How do I check if a string is a number (float)?

The input may be as follows:

a="50" b=50 c=50.1 d="50.1"


1-General input:

The input of this function can be everything!

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed.

is_numeric function

import ast
import numbers              
def is_numeric(obj):
    if isinstance(obj, numbers.Number):
        return True
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            #if used + or - in digit :
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

test:

>>> is_numeric("54")
True
>>> is_numeric("54.545")
True
>>> is_numeric("0x45")
True

is_float function

Finds whether the given variable is float. float strings consist of optional sign, any number of digits, ...

import ast

def is_float(obj):
    if isinstance(obj, float):
        return True
    if isinstance(obj, int):
        return False
    elif isinstance(obj, str):
        nodes = list(ast.walk(ast.parse(obj)))[1:]
        if not isinstance(nodes[0], ast.Expr):
            return False
        if not isinstance(nodes[-1], ast.Num):
            return False
        if not isinstance(nodes[-1].n, float):
            return False
        nodes = nodes[1:-1]
        for i in range(len(nodes)):
            if i % 2 == 0:
                if not isinstance(nodes[i], ast.UnaryOp):
                    return False
            else:
                if not isinstance(nodes[i], (ast.USub, ast.UAdd)):
                    return False
        return True
    else:
        return False

test:

>>> is_float("5.4")
True
>>> is_float("5")
False
>>> is_float(5)
False
>>> is_float("5")
False
>>> is_float("+5.4")
True

what is ast?


2- If you are confident that the variable content is String:

use str.isdigit() method

>>> a=454
>>> a.isdigit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
>>> a="454"
>>> a.isdigit()
True

3-Numerical input:

detect int value:

>>> isinstance("54", int)
False
>>> isinstance(54, int)
True
>>> 

detect float:

>>> isinstance("45.1", float)
False
>>> isinstance(45.1, float)
True

How to select a single field for all documents in a MongoDB collection?

db.student.find({}, {"roll":1, "_id":0})

This is equivalent to -

Select roll from student



db.student.find({}, {"roll":1, "name":1, "_id":0})

This is equivalent to -

Select roll, name from student

Facebook share button and custom text

This is a simple dialog feed that Facebook offer's. Read here for more detail link

How to get the current directory in a C program?

Use getcwd

#include <stdio.h>  /* defines FILENAME_MAX */
//#define WINDOWS  /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

int main(){
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  printf("Current working dir: %s\n", buff);
  return 1;
}

OR

#include<stdio.h>
#include<unistd.h> 
#include<stdlib.h>

main() {
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("\n %s \n",buf);
}

MySQL Update Inner Join tables query

The SET clause should come after the table specification.

UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

Python "expected an indented block"

This one is wrong at least:

            for x in range(x, 1, 1):
        elif option == 0:

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

install using adb with command ./adb install -r abc.apk will solve the problem (it will overwrite even when the device has higher app version)

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

It worked for me you can try your: Add this to VM options in Tomcat

-DdevBaseDir="C:\Your_Project_Dir_Path"

TCPDF ERROR: Some data has already been output, can't send PDF file

I had the same error but finally I solved it by suppressing PHP errors Just put this code error_reporting(0); at the top of your print page

    <?php 
    error_reporting(0); //hide php errors
    if( ! defined('BASEPATH')) exit('No direct script access allowed');
    require_once dirname(__FILE__) . '/tohtml/tcpdf/tcpdf.php';
    .... //continue

Casting variables in Java

The right way is this:

Integer i = Integer.class.cast(obj);

The method cast() is a much safer alternative to compile-time casting.

Convert array of strings into a string in Java

String array[]={"one","two"};
String s="";

for(int i=0;i<array.length;i++)
{
  s=s+array[i];
}

System.out.print(s);

Launching an application (.EXE) from C#?

Additionally you will want to use the Environment Variables for your paths if at all possible: http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows

E.G.

  • %WINDIR% = Windows Directory
  • %APPDATA% = Application Data - Varies alot between Vista and XP.

There are many more check out the link for a longer list.

Android: adb pull file on desktop

Judging by the desktop folder location you are using Windows. The command in Windows would be:

adb pull /sdcard/log.txt %USERPROFILE%\Desktop\

ORDER BY the IN value list

Slight improvement over the version that uses a sequence I think:

CREATE OR REPLACE FUNCTION in_sort(anyarray, out id anyelement, out ordinal int)
LANGUAGE SQL AS
$$
    SELECT $1[i], i FROM generate_series(array_lower($1,1),array_upper($1,1)) i;
$$;

SELECT 
    * 
FROM 
    comments c
    INNER JOIN (SELECT * FROM in_sort(ARRAY[1,3,2,4])) AS in_sort
        USING (id)
ORDER BY in_sort.ordinal;

Convert spark DataFrame column to python list

I ran a benchmarking analysis and list(mvv_count_df.select('mvv').toPandas()['mvv']) is the fastest method. I'm very surprised.

I ran the different approaches on 100 thousand / 100 million row datasets using a 5 node i3.xlarge cluster (each node has 30.5 GBs of RAM and 4 cores) with Spark 2.4.5. Data was evenly distributed on 20 snappy compressed Parquet files with a single column.

Here's the benchmarking results (runtimes in seconds):

+-------------------------------------------------------------+---------+-------------+
|                          Code                               | 100,000 | 100,000,000 |
+-------------------------------------------------------------+---------+-------------+
| df.select("col_name").rdd.flatMap(lambda x: x).collect()    |     0.4 | 55.3        |
| list(df.select('col_name').toPandas()['col_name'])          |     0.4 | 17.5        |
| df.select('col_name').rdd.map(lambda row : row[0]).collect()|     0.9 | 69          |
| [row[0] for row in df.select('col_name').collect()]         |     1.0 | OOM         |
| [r[0] for r in mid_df.select('col_name').toLocalIterator()] |     1.2 | *           |
+-------------------------------------------------------------+---------+-------------+

* cancelled after 800 seconds

Golden rules to follow when collecting data on the driver node:

  • Try to solve the problem with other approaches. Collecting data to the driver node is expensive, doesn't harness the power of the Spark cluster, and should be avoided whenever possible.
  • Collect as few rows as possible. Aggregate, deduplicate, filter, and prune columns before collecting the data. Send as little data to the driver node as you can.

toPandas was significantly improved in Spark 2.3. It's probably not the best approach if you're using a Spark version earlier than 2.3.

See here for more details / benchmarking results.

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

lodash: mapping array to object

Yep it is here, using _.reduce

var params = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }
];

_.reduce(params , function(obj,param) {
 obj[param.name] = param.input
 return obj;
}, {});

How many files can I put in a directory?

The biggest issue I've run into is on a 32-bit system. Once you pass a certain number, tools like 'ls' stop working.

Trying to do anything with that directory once you pass that barrier becomes a huge problem.

Disable browser 'Save Password' functionality

if autocomplete="off" is not working...remove the form tag and use a div tag instead, then pass the form values using jquery to the server. This worked for me.

How to list all files in a directory and its subdirectories in hadoop hdfs

Now, one can use Spark to do the same and its way faster than other approaches (such as Hadoop MR). Here is the code snippet.

def traverseDirectory(filePath:String,recursiveTraverse:Boolean,filePaths:ListBuffer[String]) {
    val files = FileSystem.get( sparkContext.hadoopConfiguration ).listStatus(new Path(filePath))
            files.foreach { fileStatus => {
                if(!fileStatus.isDirectory() && fileStatus.getPath().getName().endsWith(".xml")) {                
                    filePaths+=fileStatus.getPath().toString()      
                }
                else if(fileStatus.isDirectory()) {
                    traverseDirectory(fileStatus.getPath().toString(), recursiveTraverse, filePaths)
                }
            }
    }   
}

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

A non-blocking read on a subprocess.PIPE in Python

The select module helps you determine where the next useful input is.

However, you're almost always happier with separate threads. One does a blocking read the stdin, another does wherever it is you don't want blocked.

Add element to a JSON file?

One possible issue I see is you set your JSON unconventionally within an array/list object. I would recommend using JSON in its most accepted form, i.e.:

test_json = { "a": 1, "b": 2}

Once you do this, adding a json element only involves the following line:

test_json["c"] = 3

This will result in:

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

Afterwards, you can add that json back into an array or a list of that is desired.

Passing variables in remote ssh command

(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)

You can feed data right through the standard input of the ssh command and read that from the remote location.

In the following example,

  1. an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
  2. For each of those variables, we give to ssh a null-terminated line giving the name and value of the variable.
  3. In the shh command itself, we loop through these lines to initialise the required variables.
# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb

# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
    FOO
    BAR
)

for name in "${VAR_NAMES[@]}"
do
    printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
    while read -rd '"''"' name value
    do
        export "$name"="$value"
    done

    # Check
    printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'

Output:

FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]

If you don’t need to export those, you should be able to use declare instead of export.

A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:

$ ssh [email protected] 'read foo' <<< "$foo"

MySQL: Grant **all** privileges on database

Hello I used this code to have the super user in mysql

GRANT EXECUTE, PROCESS, SELECT, SHOW DATABASES, SHOW VIEW, ALTER, ALTER ROUTINE,
    CREATE, CREATE ROUTINE, CREATE TEMPORARY TABLES, CREATE VIEW, DELETE, DROP,
    EVENT, INDEX, INSERT, REFERENCES, TRIGGER, UPDATE, CREATE USER, FILE,
    LOCK TABLES, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHUTDOWN,
    SUPER
        ON *.* TO mysql@'%'
    WITH GRANT OPTION;

and then

FLUSH PRIVILEGES;

Reset MySQL root password using ALTER USER statement after install on Mac

remember versions 5.7.23 and up - the user table doesn't has column password instead authentication string so below works while resetting password for a user.

update user set authentication_string=password('root') where user='root';

why is plotting with Matplotlib so slow?

This may not apply to many of you, but I'm usually operating my computers under Linux, so by default I save my matplotlib plots as PNG and SVG. This works fine under Linux but is unbearably slow on my Windows 7 installations [MiKTeX under Python(x,y) or Anaconda], so I've taken to adding this code, and things work fine over there again:

import platform     # Don't save as SVG if running under Windows.
#
# Plot code goes here.
#
fig.savefig('figure_name.png', dpi = 200)
if platform.system() != 'Windows':
    # In my installations of Windows 7, it takes an inordinate amount of time to save
    # graphs as .svg files, so on that platform I've disabled the call that does so.
    # The first run of a script is still a little slow while everything is loaded in,
    # but execution times of subsequent runs are improved immensely.
    fig.savefig('figure_name.svg')

Gulp command not found after install

I had this problem with getting "command not found" after install but I was installed into /usr/local as described in the solution above.

My problem seemed to be caused by me running the install with sudo. I did the following.

  1. Removing gulp again with sudo
  2. Changing the owner of /usr/local/lib/node_modules to my user
  3. Installing gulp again without sudo. "npm install gulp -g"

Field 'id' doesn't have a default value?

make sure that you do not have defined setter for the for your primary key in model class.

public class User{
@Id
@GeneratedValues
private int user_Id;
private String userName;

public int getUser_Id{
return user_Id;
}

public String getUserName{
return userName;
}

public void setUserName{
this.userName=userName;
}
}

Change default icon

If your designated icon shows when you run the EXE but not when you run it from Visual Studio, then, for a WPF project add the following at the top of your XAML: Icon="Images\MyIcon.ico". Put this just where you have the Title, and xmlns definitions. (Assuming you have an Images folder in your project, and that you added MyIcon.ico there).

Measuring text height to be drawn on Canvas ( Android )

If anyone still has problem, this is my code.

I have a custom view which is square (width = height) and I want to assign a character to it. onDraw() shows how to get height of character, although I'm not using it. Character will be displayed in the middle of view.

public class SideBarPointer extends View {

    private static final String TAG = "SideBarPointer";

    private Context context;
    private String label = "";
    private int width;
    private int height;

    public SideBarPointer(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public SideBarPointer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    private void init() {
//        setBackgroundColor(0x64FF0000);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        height = this.getMeasuredHeight();
        width = this.getMeasuredWidth();

        setMeasuredDimension(width, width);
    }

    protected void onDraw(Canvas canvas) {
        float mDensity = context.getResources().getDisplayMetrics().density;
        float mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;

        Paint previewPaint = new Paint();
        previewPaint.setColor(0x0C2727);
        previewPaint.setAlpha(200);
        previewPaint.setAntiAlias(true);

        Paint previewTextPaint = new Paint();
        previewTextPaint.setColor(Color.WHITE);
        previewTextPaint.setAntiAlias(true);
        previewTextPaint.setTextSize(90 * mScaledDensity);
        previewTextPaint.setShadowLayer(5, 1, 2, Color.argb(255, 87, 87, 87));

        float previewTextWidth = previewTextPaint.measureText(label);
//        float previewTextHeight = previewTextPaint.descent() - previewTextPaint.ascent();
        RectF previewRect = new RectF(0, 0, width, width);

        canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
        canvas.drawText(label, (width - previewTextWidth)/2, previewRect.top - previewTextPaint.ascent(), previewTextPaint);

        super.onDraw(canvas);
    }

    public void setLabel(String label) {
        this.label = label;
        Log.e(TAG, "Label: " + label);

        this.invalidate();
    }
}

How to check whether mod_rewrite is enable on server?

If you are using a virtual hosts configuration file, make sure the virtual host in question has the directive AllowOverride All somewhere like this:

<VirtualHost *:80>
        ...
    <Directory "directory/of/your/.htaccess">
        AllowOverride All
    </Directory>
</VirtualHost>

Basically, this states to allow processing of all .htaccess directives.

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

Try this..Add this in your page

<style>
textarea
{
width:100%;
}
</style>

How can I use mySQL replace() to replace strings in multiple records?

you can write a stored procedure like this:

CREATE PROCEDURE sanitize_TABLE()

BEGIN

#replace space with underscore

UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;

#delete dot

UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;

#delete (

UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;

#delete )

UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;

#raplace or delete any char you want

#..........................

END

In this way you have modularized control over table.

You can also generalize stored procedure making it, parametric with table to sanitoze input parameter

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

Had the same issue on Ubuntu 14.10 with java-8-oracle installed.

Solved installing ca-certificates-java package:

sudo apt-get install ca-certificates-java

How do I create a Bash alias?

To create a permanent alias shortcut, put it in .bash_profile file and point .bashrc file to .bash_profile file. Follow these steps (I am creating an alias command called bnode to run babel transpiler on ES6 code):

  1. Go to terminal command prompt and type “cd” (this will take you to the home directory. Note: even though your programming files may be located on your “D: drive”, your “.bash” files may be located on your “C: drive” )
  2. To see the location of the home directory, type “pwd” (this will show you the home directory path and where the .bash files are probably located)
  3. To see all dot "." files in the home directory, type “ls -la” (this will show ALL files including hidden dot "." files)
  4. You will see 2 files: “.bash_profile” and “.bashrc”
  5. Open .bashrc file in VS Code Editor or your IDE and enter “source ~/.bash_profile” in first line (to point .bashrc file to .bash_profile)
  6. Open .bash_profile file in VS Code Editor and enter “alias bnode='./node_modules/.bin/babel-node'” (to create permanent bnode shortcut to execute as bash command)
  7. Save and close both files
  8. Now open the file you want to execute (index.js) and open in terminal command prompt and run file by using command “bnode index.js”
  9. Now your index.js file will execute but before creating bnode alias in .bash_profile file you would get the error "bash: bnode command not found" and it would not recognize and give errors on some ES6 code.
  10. Helpful link to learn about dotfiles: https://dotfiles.github.io/

I hope this helps! Good luck!

How to increase Bootstrap Modal Width?

In Bootstrap 3 you need to change the modal-dialog. So, in this case, you can add the class modal-admin in the place where modal-dialog stands.

@media (min-width: 768px) {
  .modal-dialog {
    width: 600;
    margin: 30px auto;
  }
  .modal-content {
    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
            box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
  }
  .modal-sm {
    width: 300px;
  }
}

Skip to next iteration in loop vba

Just do nothing once the criteria is met, otherwise do the processing you require and the For loop will go to the next item.

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return = 0 And Level = 0 Then
        'Do nothing
    Else
        'Do something
    End If
Next i

Or change the clause so it only processes if the conditions are met:

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return <> 0 Or Level <> 0 Then
        'Do something
    End If
Next i

What is the "Temporary ASP.NET Files" folder for?

These are what's known as Shadow Copy Folders.

Simplistically....and I really mean it:

When ASP.NET runs your app for the first time, it copies any assemblies found in the /bin folder, copies any source code files (found for example in the App_Code folder) and parses your aspx, ascx files to c# source files. ASP.NET then builds/compiles all this code into a runnable application.

One advantage of doing this is that it prevents the possibility of .NET assembly DLL's #(in the /bin folder) becoming locked by the ASP.NET worker process and thus not updatable.

ASP.NET watches for file changes in your website and will if necessary begin the whole process all over again.

Theoretically the folder shouldn't need any maintenance, but from time to time, and only very rarely you may need to delete contents. That said, I work for a hosting company, we run up to 1200 sites per shared server and I haven't had to touch this folder on any of the 250 or so machines for years.

This is outlined in the MSDN article Understanding ASP.NET Dynamic Compilation

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

Detect Safari browser

Simplest answer:

function isSafari() {
 if (navigator.vendor.match(/[Aa]+pple/g).length > 0 ) 
   return true; 
 return false;
}

How to detect lowercase letters in Python?

There are many methods to this, here are some of them:

  1. Using the predefined str method islower():

    >>> c = 'a'
    >>> c.islower()
    True
    
  2. Using the ord() function to check whether the ASCII code of the letter is in the range of the ASCII codes of the lowercase characters:

    >>> c = 'a'
    >>> ord(c) in range(97, 123)
    True
    
  3. Checking if the letter is equal to it's lowercase form:

    >>> c = 'a'
    >>> c.lower() == c
    True
    
  4. Checking if the letter is in the list ascii_lowercase of the string module:

    >>> from string import ascii_lowercase
    >>> c = 'a'
    >>> c in ascii_lowercase
    True
    

But that may not be all, you can find your own ways if you don't like these ones: D.

Finally, let's start detecting:

d = str(input('enter a string : '))
lowers = [c for c in d if c.islower()]

# here i used islower() because it's the shortest and most-reliable
# one (being a predefined function), using this list comprehension
# is (probably) the most efficient way of doing this

How to make an app's background image repeat

Ok, here's what I've got in my app. It includes a hack to prevent ListViews from going black while scrolling.

drawable/app_background.xml:

<?xml version="1.0" encoding="utf-8"?>
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/actual_pattern_image"
        android:tileMode="repeat" />

values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <style name="app_theme" parent="android:Theme">
    <item name="android:windowBackground">@drawable/app_background</item>
    <item name="android:listViewStyle">@style/TransparentListView</item>
    <item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
  </style>

  <style name="TransparentListView" parent="@android:style/Widget.ListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

  <style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

</resources>

AndroidManifest.xml:

//
<application android:theme="@style/app_theme">
//

How to find an available port?

If your server starts up, then that socket was not used.

EDIT

Something like:

ServerSocket s = null ;

try { 
    s = new ServerSocket( 0 ); 
} catch( IOException ioe ){
   for( int i = START; i < END ; i++ ) try {
        s = new ServerSocket( i );
    } catch( IOException ioe ){}
}
// At this point if s is null we are helpless
if( s == null ) {
    throw new IOException(
       Strings.format("Unable to open server in port range(%d-%d)",START,END));
}

How can I select rows with most recent timestamp for each key value?

This can de done in a relatively elegant way using SELECT DISTINCT, as follows:

SELECT DISTINCT ON (sensorID)
sensorID, timestamp, sensorField1, sensorField2 
FROM sensorTable
ORDER BY sensorID, timestamp DESC;

The above works for PostgreSQL (some more info here) but I think also other engines. In case it's not obvious, what this does is sort the table by sensor ID and timestamp (newest to oldest), and then returns the first row (i.e. latest timestamp) for each unique sensor ID.

In my use case I have ~10M readings from ~1K sensors, so trying to join the table with itself on a timestamp-based filter is very resource-intensive; the above takes a couple of seconds.

Modifying location.hash without page scrolling

This solution creates a div at the actual scrollTop and removes it after changing hash:

$('#menu a').on('click',function(){
    //your anchor event here
    var href = $(this).attr('href');
    window.location.hash = href;
    if(window.location.hash == href)return false;           
    var $jumpTo = $('body').find(href);
    $('body').append(
        $('<div>')
            .attr('id',$jumpTo.attr('id'))
            .addClass('fakeDivForHash')
            .data('realElementForHash',$jumpTo.removeAttr('id'))
            .css({'position':'absolute','top':$(window).scrollTop()})
    );
    window.location.hash = href;    
});
$(window).on('hashchange', function(){
    var $fakeDiv = $('.fakeDivForHash');
    if(!$fakeDiv.length)return true;
    $fakeDiv.data('realElementForHash').attr('id',$fakeDiv.attr('id'));
    $fakeDiv.remove();
});

optional, triggering anchor event at page load:

$('#menu a[href='+window.location.hash+']').click();

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

Interpreting "condition has length > 1" warning from `if` function

Here's an easy way without ifelse:

(a/sum(a))^(a>0)

An example:

a <- c(0, 1, 0, 0, 1, 1, 0, 1)

(a/sum(a))^(a>0)

[1] 1.00 0.25 1.00 1.00 0.25 0.25 1.00 0.25

jQuery - determine if input element is textbox or select list

If you just want to check the type, you can use jQuery's .is() function,

Like in my case I used below,

if($("#id").is("select")) {
 alert('Select'); 
else if($("#id").is("input")) {
 alert("input");
}

Updating user data - ASP.NET Identity

Based on your question and also noted in comment.

Can someone guide me on how to update User info in the database?

Yes, the code is correct for updating any ApplicationUser to the database.

IdentityResult result = await UserManager.UpdateAsync(user);

  • Check for constrains of all field's required values
  • Check for UserManager is created using ApplicationUser.

UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

Python MySQLdb TypeError: not all arguments converted during string formatting

I encountered this error while executing SELECT * FROM table; I traced the error to cursor.py line 195.

if args is not None:
        if isinstance(args, dict):
            nargs = {}
            for key, item in args.items():
                if isinstance(key, unicode):
                    key = key.encode(db.encoding)
                nargs[key] = db.literal(item)
            args = nargs
        else:
            args = tuple(map(db.literal, args))
        try:
            query = query % args
        except TypeError as m:
            raise ProgrammingError(str(m))

Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.

Docker error : no space left on device

  1. Clean dangled images docker rmi $(docker images -f "dangling=true" -q)
  2. Remove unwanted volumes
  3. Remove unused images
  4. Remove unused containers

"git checkout <commit id>" is changing branch to "no branch"

If you checkout a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.

If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:

git checkout <branch>

If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:

# Checkout a new branch at current detached head state:
git checkout -b newBranch

You can read more about detached head state at the official Linux Kernel Git docs for checkout.

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.

Despite the checked answer being correct:

Mike M wrote-

"The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table."

What is missing from this answer is simply;

You must build the table containing the Primary Key first.

Another way to say it is;

You must Insert Data into the parent table, containing the Primary Key, before attempting to insert data into the child table containing the Foreign Key.

In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.

If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.

javax.servlet.ServletException cannot be resolved to a type in spring web app

import javax.servlet

STEP 1

Go to properties of your project ( with Alt+Enter or righ-click )

STEP 2

check on Apache Tomcat v7.0 under Targeted Runtime and it works.

source: https://stackoverflow.com/a/9287149

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

How to downgrade python from 3.7 to 3.6

I just now downgraded my Python 3.9 to 3.6 because I wanted to use the librosa package but it does not support Python 3.9 still now.

Steps -

  • Go to python official website
  • Download the Python version which you want
  • Install in your machine normally

Run python3 --version in the terminal and it will show this version of Python.

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

How to get Android crash logs?

Use acra crash reporter for android app..Acra lib

make image( not background img) in div repeat?

It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.

<div id="rightflower">
<div id="divImg"></div> 
</div>

And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.

Maven: Command to update repository after adding dependency to POM

Pay attention to your dependency scope I was having the issue where when I invoke clean compile via Intellij, the pom would get downloaded, but the jar would not. There was a xxx.jar.lastUpdated file created. Then realized that the dependency scope was test, but I was triggering the compile. I deleted the repos, and triggered the mvn test, and issue was resolved.

How to monitor network calls made from iOS Simulator

FLEX is a great tool to monitor network traffic from your iOS app.

FLEX iOS Screenshot 1

On clicking on any of the requests listed in the above screenshot, I will be redirected to another screen where I can see more details about that request. FLEX iOS Screenshot 2

However, I had a use case where the app which I was working on would redirect the user to Safari. I wanted to monitor the network traffic in Safari as well, but FLEX could only monitor the traffic from your iOS app, not from any other app ( at the time of writing this answer ).

Then I switched to Proxyman to monitor network traffic from the iOS simulator.

  • It has a clear set of instructions on how to set it up with both iOS simulators and Android emulators.
  • It has a simple, intuitive UI, which makes it easy to work with.

enter image description here

How to set entire application in portrait mode only?

Use:

android:screenOrientation="portrait" 

Just write this line in your application's manifest file in each activity which you want to show in portrait mode only.

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!

This started happening after I've updated android studio to latest version.

Laravel Request::all() Should Not Be Called Statically

i make it work with a scope definition

public function pagar(\Illuminate\Http\Request $request) { //

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

We can try by using latest jQuery library. I got the same issue. I used jQuery-1.4.2.min before and getting the error. After that I used version 1.9.1 and it works. Thanks

Compare object instances for equality by their attributes

You should implement the method __eq__:

class MyClass:
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def __eq__(self, other): 
        if not isinstance(other, MyClass):
            # don't attempt to compare against unrelated types
            return NotImplemented

        return self.foo == other.foo and self.bar == other.bar

Now it outputs:

>>> x == y
True

Note that implementing __eq__ will automatically make instances of your class unhashable, which means they can't be stored in sets and dicts. If you're not modelling an immutable type (i.e. if the attributes foo and bar may change value within the lifetime of your object), then it's recommend to just leave your instances as unhashable.

If you are modelling an immutable type, you should also implement the datamodel hook __hash__:

class MyClass:
    ...

    def __hash__(self):
        # necessary for instances to behave sanely in dicts and sets.
        return hash((self.foo, self.bar))

A general solution, like the idea of looping through __dict__ and comparing values, is not advisable - it can never be truly general because the __dict__ may have uncomparable or unhashable types contained within.

N.B.: be aware that before Python 3, you may need to use __cmp__ instead of __eq__. Python 2 users may also want to implement __ne__, since a sensible default behaviour for inequality (i.e. inverting the equality result) will not be automatically created in Python 2.

AngularJS format JSON string output

You can use an optional parameter of JSON.stringify()

JSON.stringify(value[, replacer [, space]])

Parameters

  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

"{
    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4
    }
}"

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

Old question, but here's another explanation of the problem. You'll get this error even if you have strongly typed views and aren't using ViewData to create your dropdown list. The reason for the error can becomes clear when you look at the MVC source:

// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
    selectList = htmlHelper.GetSelectData(name);
    usedViewData = true;
}

So if you have something like:

@Html.DropDownList("MyList", Model.DropDownData, "")

And Model.DropDownData is null, MVC looks through your ViewData for something named MyList and throws an error if there's no object in ViewData with that name.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

ValueError: setting an array element with a sequence

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

smtp configuration for php mail

Note that PHP mail settings come from your php.ini file. The default looks more or less like this:

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = On

; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log =

By editing your php.ini file you should be able to fix the problem without changing your PHP scripts. Also, you can test a connection with the telnet tool and the HELO, MAIL FROM, RCPT TO, DATA, QUIT commands if you directly connect to an SMTP server. With sendmail, you don't even need that, sendmail should know what it's doing (although in your case it probably wasn't and the sendmail settings probably needed a little help.)

Update: in most cases, telnet is not installed anymore because it's considered dangerous (i.e. it gives you a clear text connection which is generally fine on your local network, but not so much to remote computers). Instead, we have nc which is very similar for testing things such as SMTP but doesn't really allow for remote shell connections. That being said, more and more SMTP is going to use encryption as well so the best tool to test is still sendmail.

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

How to create file object from URL object (image)

In order to create a File from a HTTP URL you need to download the contents from that URL:

URL url = new URL("http://www.google.ro/logos/2011/twain11-hp-bg.jpg");
URLConnection connection = url.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("downloaded.jpg"));
byte[] buf = new byte[512];
while (true) {
    int len = in.read(buf);
    if (len == -1) {
        break;
    }
    fos.write(buf, 0, len);
}
in.close();
fos.flush();
fos.close();

The downloaded file will be found at the root of your project: {project}/downloaded.jpg

how do I initialize a float to its max/min value?

You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).

#include <limits>

//...

std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();

As noted in the comments, min() returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.

There is of course the std::max_element and min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.

Handlebars.js Else If

The spirit of handlebars is that it is "logicless". Sometimes this makes us feel like we are fighting with it, and sometimes we end up with ugly nested if/else logic. You could write a helper; many people augment handlebars with a "better" conditional operator or believe that it should be part of the core. I think, though, that instead of this,

{{#if FriendStatus.IsFriend}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
  {{#if FriendStatus.FriendRequested}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
  {{else}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
  {{/if}}
{{/if}}

you might want to arrange things in your model so that you can have this,

{{#if is_friend }}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{/if}}

{{#if is_not_friend_yet }}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{/if}}

{{#if will_never_be_my_friend }}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}

Just make sure that only one of these flags is ever true. Chances are, if you are using this if/elsif/else in your view, you are probably using it somewhere else too, so these variables might not end up being superfluous.

Keep it lean.

Differences between action and actionListener

ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.

If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.

Here is a link that describes the relationship:

http://www.java-samples.com/showtutorial.php?tutorialid=605

how to create insert new nodes in JsonNode?

These methods are in ObjectNode: the division is such that most read operations are included in JsonNode, but mutations in ObjectNode and ArrayNode.

Note that you can just change first line to be:

ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type

or

ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

Does Eclipse have line-wrap

Try AhtiK Eclipse WordWrap, it works for me: http://www.ahtik.com/eclipse-update/

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

Difference between "querySelector" and "querySelectorAll"

_x000D_
_x000D_
//querySelector returns single element_x000D_
let listsingle = document.querySelector('li');_x000D_
console.log(listsingle);_x000D_
_x000D_
_x000D_
//querySelectorAll returns lit/array of elements_x000D_
let list = document.querySelectorAll('li');_x000D_
console.log(list);_x000D_
_x000D_
_x000D_
//Note : output will be visible in Console
_x000D_
<ul>_x000D_
<li class="test">ffff</li>_x000D_
<li class="test">vvvv</li>_x000D_
<li>dddd</li>_x000D_
<li class="test">ddff</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How Does Modulus Divison Work

Maybe the example with an clock could help you understand the modulo.

A familiar use of modular arithmetic is its use in the 12-hour clock, in which the day is divided into two 12 hour periods.

Lets say we have currently this time: 15:00
But you could also say it is 3 pm

This is exactly what modulo does:

15 / 12 = 1, remainder 3

You find this example better explained on wikipedia: Wikipedia Modulo Article

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Trying to solve this problem myself, I discovered that there is no HeadBucket permission. It looks like there is, because that's what the error message tells you, but actually the HEAD operation requires the ListBucket permission. I also discovered that my IAM policy and my bucket policy were conflicting. Make sure you check both.

Initializing C dynamic arrays

p = {1,2,3} is wrong.

You can never use this:

int * p;
p = {1,2,3};

loop is right

int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
    p[i] = i;

Transparent background on winforms?

My solution was extremely close to Joel's (Not Etherton, just plain Joel):

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;
        this.TransparencyKey = Color.Transparent; // I had to add this to get it to work.

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

How to use UIPanGestureRecognizer to move object? iPhone/iPad

UIPanGestureRecognizer * pan1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(moveObject:)];
pan1.minimumNumberOfTouches = 1;
[image1 addGestureRecognizer:pan1];

-(void)moveObject:(UIPanGestureRecognizer *)pan;
{
 image1.center = [pan locationInView:image1.superview];
}

Working with huge files in VIM

I wrote a little script based on Florian's answer that uses nano (my favorite editor):

#!/bin/sh

if [ "$#" -ne 3 ]; then
  echo "Usage: $0 hugeFilePath startLine endLine" >&2
  exit 1
fi

sed -n -e $2','$3'p' -e $3'q' $1 > hfnano_temporary_file
nano hfnano_temporary_file
(head -n `expr $2 - 1` $1; cat hfnano_temporary_file; sed -e '1,'$3'd' $1) > hfnano_temporary_file2
cat hfnano_temporary_file2 > $1
rm hfnano_temporary_file hfnano_temporary_file2

Use it like this:

sh hfnano yourHugeFile 3 8

In that example, nano will open up lines 3 through 8, you can edit them, and when you save and quit, those lines in the hugefile will automatically be overwritten with your saved lines.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

The documentation states several ways to do this.

If you want to replace the default ObjectMapper completely, define a @Bean of that type and mark it as @Primary.

Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).

WPF User Control Parent

I've found that the parent of a UserControl is always null in the constructor, but in any event handlers the parent is set correctly. I guess it must have something to do with the way the control tree is loaded. So to get around this you can just get the parent in the controls Loaded event.

For an example checkout this question WPF User Control's DataContext is Null

How to select a dropdown value in Selenium WebDriver using Java

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I was having the same problem with the fetch command. A quick look at the docs from here tells us this:

If the server you are requesting from doesn't support CORS, you should get an error in the console indicating that the cross-origin request is blocked due to the CORS Access-Control-Allow-Origin header being missing.

You can use no-cors mode to request opaque resources.

fetch('https://bar.com/data.json', {
  mode: 'no-cors' // 'cors' by default
})
.then(function(response) {
  // Do something with response
});

How to pass a callback as a parameter into another function

Yes of course, function are objects and can be passed, but of course you must declare it:

function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).

How to convert UTC timestamp to device local time in android

Java:

int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
long now = System.currentTimeMillis() - offset;

Kotlin:

Int offset = TimeZone.getDefault()rawOffset + TimeZone.getDefault().dstSavings
Long now = System.currentTimeMillis() - offset

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I have had this issue before. I usually just hit enter to add a line and then wait for the plus/minus to show on the html page and the designer should add what you need. I have also had to close the project and reopen it to get it to work.

How to emulate GPS location in the Android Emulator?

No one here mentioned the built in solution of the emulator itself, so for future visitors, I'd like to share it with visuals.

First, run your Android Emulator and click on the menu button (3 dots) shown below:

emulator with menu button

Then from the left pane, select Location and change the coordinates according to your needs. After pressing Send button, changes will immediately take effect (I recommend you to open up Google Maps for better understanding).

enter image description here

Android Studio Version: 2.3.3

In addition, to make your different locations coming to your application in real time, you can use GPX file. It's very easy to create this file from Google Map direction link:

  1. Go to google map, choose a location, then press "Directions" and enter the second location.
  2. After route is created, copy a link from the browser
  3. Go to this website: https://mapstogpx.com and paste the link to "Let's Go" box
  4. Press the "Let's Go" button and GPX file will be downloaded

Use "Load GPS/KML" button to load the created file to your emulator, choose speed, and press green play button on the bottom. Locations will be sent in real time as shown on the picture below.

enter image description here

How to convert a string to number in TypeScript?

Easiest way is to use +strVal or Number(strVal)

Examples:

let strVal1 = "123.5"
let strVal2 = "One"
let val1a = +strVal1
let val1b = Number(strVal1)
let val1c = parseFloat(strVal1)
let val1d = parseInt(strVal1)
let val1e = +strVal1 - parseInt(strVal1)
let val2a = +strVal2

console.log("val1a->", val1a) // 123.5
console.log("val1b->", val1b) // 123.5
console.log("val1c->", val1c) // 123.5
console.log("val1d->", val1d) // 123
console.log("val1e->", val1e) // 0.5
console.log("val2a->", val2a) // NaN

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

Can you Run Xcode in Linux?

The low-level toolchain for Xcode (the gcc compiler family, the gdb debugger, etc.) is all open source and common to Unix and Linux platforms. But the IDE--the editor, project management, indexing, navigation, build system, graphical debugger, visual data modeling, SCM system, refactoring, project snapshots, etc.--is a Mac OS X Cocoa application, and is not portable.

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

Convert `List<string>` to comma-separated string

In .NET 4 you don't need the ToArray() call - string.Join is overloaded to accept IEnumerable<T> or just IEnumerable<string>.

There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?

You could iterate over the list, work out the final size, allocate a StringBuilder of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.

Use JavaScript to place cursor at end of text in text input element

Though I'm answering too late, but for future query, it will be helpful. And it also work in contenteditable div.

From where you need to set focus at end; write this code-

var el = document.getElementById("your_element_id");
placeCaretAtEnd(el);

And the function is -

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

Iterator invalidation rules

Since this question draws so many votes and kind of becomes an FAQ, I guess it would be better to write a separate answer to mention one significant difference between C++03 and C++11 regarding the impact of std::vector's insertion operation on the validity of iterators and references with respect to reserve() and capacity(), which the most upvoted answer failed to notice.

C++ 03:

Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().

C++11:

Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

So in C++03, it is not "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)" as mentioned in the other answer, instead, it should be "greater than the size specified in the most recent call to reserve()". This is one thing that C++03 differs from C++11. In C++03, once an insert() causes the size of the vector to reach the value specified in the previous reserve() call (which could well be smaller than the current capacity() since a reserve() could result a bigger capacity() than asked for), any subsequent insert() could cause reallocation and invalidate all the iterators and references. In C++11, this won't happen and you can always trust capacity() to know with certainty that the next reallocation won't take place before the size overpasses capacity().

In conclusion, if you are working with a C++03 vector and you want to make sure a reallocation won't happen when you perform insertion, it's the value of the argument you previously passed to reserve() that you should check the size against, not the return value of a call to capacity(), otherwise you may get yourself surprised at a "premature" reallocation.

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

Auto-redirect to another HTML page

If you're using Apache and can use a .htaccess file you should use the following type of redirect. Add the following to an .htaccess file in the root of your website.

RewriteEngine On
RewriteRule ^/oldfile_path/file_name\.html$ /oldfile_path/file_name.html [R=301,L]

This has the advantage of being a very fast and immediate redirect. It also depends on your reason for the redirect. This is a more permanent method because it sends the HTTP 301 status code signifying that the file has moved permanently and causes many browsers to cache that request. You can change the code to something else like a 302 for temporary redirects.

Otherwise you can do a simple redirect using an HTML <meta> tag as suggested by others:

<meta http-equiv="refresh" content="5; url=http://example.com/">

By default the content="5" makes that redirect after 5 seconds. This will be slower and not all browsers support it. A redirect can also be done in the server language of your choice PHP, Node.js, etc.

How to change the locale in chrome browser

Based from this thread, you need to bookmark chrome://settings/languages and then Drag and Drop the language to make it default. You have to click on the Display Google Chrome in this Language button and completely restart Chrome.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

How can I convert an RGB image into grayscale in Python?

You can also use scikit-image, which provides some functions to convert an image in ndarray, like rgb2gray.

from skimage import color
from skimage import io

img = color.rgb2gray(io.imread('image.png'))

Notes: The weights used in this conversion are calibrated for contemporary CRT phosphors: Y = 0.2125 R + 0.7154 G + 0.0721 B

Alternatively, you can read image in grayscale by:

from skimage import io
img = io.imread('image.png', as_gray=True)

PreparedStatement setNull(..)

but watch out for this....

Long nullLong = null;

preparedStatement.setLong( nullLong );

-thows null pointer exception-

because the protype is

setLong( long )   

NOT

setLong( Long )

nice one to catch you out eh.

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

Babel 6 regeneratorRuntime is not defined

This error is caused when async/await functions are used without the proper Babel plugins. As of March 2020, the following should be all you need to do. (@babel/polyfill and a lot of the accepted solutions have been deprecated in Babel. Read more in the Babel docs.)

In the command line, type:

npm install --save-dev @babel/plugin-transform-runtime

In your babel.config.js file, add this plugin @babel/plugin-transform-runtime. Note: The below example includes the other presets and plugins I have for a small React/Node/Express project I worked on recently:

module.exports = {
  presets: ['@babel/preset-react', '@babel/preset-env'],
  plugins: ['@babel/plugin-proposal-class-properties', 
  '@babel/plugin-transform-runtime'],
};

How to pass the password to su/sudo/ssh without overriding the TTY?

I've got:

ssh user@host bash -c "echo mypass | sudo -S mycommand"

Works for me.

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

$ is not a function - jQuery error

In Wordpress jQuery.noConflict() is called on the jQuery file it includes (scroll to the bottom of the file it's including for jQuery to see this), which means $ doesn't work, but jQuery does, so your code should look like this:

<script type="text/javascript">
  jQuery(function($) {
    for(var i=0; i <= 20; i++) 
      $("ol li:nth-child(" + i + ")").addClass('olli' + i);
  });
</script>

How to find the unclosed div tag

Div tags are easy to spot for me. Just download the file, scan it or so with netbeans, then continue debugging it. Or you can use the Google chrome developer kit, and view the page source. I'm a bit of a weird developer, I don't always use the "best" stuff. But it works for me.

I'll link you with some developer stuff I use

http://www.coffeecup.com/free-editor/

http://www.netbeans.org

Those are just a few of the good ones out there. I'm open to more suggestions to this list :D

Happy programming

-skycoder

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Free XML Formatting tool

You can open the XML file in any Visual Studio Express product and the press Ctrl+A, Ctrl+K, Ctrl+F to get it nicely formatted.

Hey, it's free and it's a tool, so it fits the question. :-)

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Here is a handy comparison table that shows the conversions that happen and the differences between == and ===.

As the conclusion states:

"Use three equals unless you fully understand the conversions that take place for two-equals."

http://dorey.github.io/JavaScript-Equality-Table/

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

try this

provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);

Bye.

mean() warning: argument is not numeric or logical: returning NA

From R 3.0.0 onwards mean(<data.frame>) is defunct (and passing a data.frame to mean will give the error you state)

A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".

In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following

lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)

Add CSS or JavaScript files to layout head from views or partial views

I tried to solve this issue.

My answer is here.

"DynamicHeader" - http://dynamicheader.codeplex.com/, https://nuget.org/packages/DynamicHeader

For example, _Layout.cshtml is:

<head>
@Html.DynamicHeader()
</head>
...

And, you can register .js and .css files to "DynamicHeader" anywhere you want.

For example, the code block in AnotherPartial.cshtml is:

@{
  DynamicHeader.AddSyleSheet("~/Content/themes/base/AnotherPartial.css");
  DynamicHeader.AddScript("~/some/myscript.js");
}

Result HTML output for this sample is:

<html>
  <link href="/myapp/Content/themes/base/AnotherPartial.css" .../>
  <script src="/myapp/some/myscript.js" ...></script>
</html>
...

excel formula to subtract number of days from a date

Say the 1st date is in A1 cell & the 2nd date is in B1 cell

Make sure that the cell type of both A1 & B1 is DATE.
Then simply put the following formula in C1:

=A1-B1

The result of this formula may look funny to you. Then Change the Cell type of C1 to GENERAL.

It will give you the difference in Days.

You can also use this formula to get the remaining days of year or change the formula as you need:

=365-(A1-B1)

Word-wrap in an HTML table

As mentioned, putting the text within div almost works. You just have to specify the width of the div, which is fortunate for layouts which are static.

This works on FF 3.6, IE 8, Chrome.

<td>
  <div style="width: 442px; word-wrap: break-word">
    <!-- Long Content Here-->
  </div>
</td>

How do I get the IP address into a batch-file variable?

This work even if you have a virtual network adapters or VPN connections:

FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
echo Your IP Address is: %localIp%

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

Manifest Merger failed with multiple errors in Android Studio

In my case it was showing an error because there was a redundancy in <uses-permission> element. So, please check in your AndroidManifest.xml file for the same.

Android Studio version is 3.0.1

Operating System is Windows 7

Here is the screenshot for reference.

Screen-shot which shows redundancy in manifest file.

What are the special dollar sign shell variables?

To help understand what do $#, $0 and $1, ..., $n do, I use this script:

#!/bin/bash

for ((i=0; i<=$#; i++)); do
  echo "parameter $i --> ${!i}"
done

Running it returns a representative output:

$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine

Any reason not to use '+' to concatenate two strings?

The assumption that one should never, ever use + for string concatenation, but instead always use ''.join may be a myth. It is true that using + creates unnecessary temporary copies of immutable string object but the other not oft quoted fact is that calling join in a loop would generally add the overhead of function call. Lets take your example.

Create two lists, one from the linked SO question and another a bigger fabricated

>>> myl1 = ['A','B','C','D','E','F']
>>> myl2=[chr(random.randint(65,90)) for i in range(0,10000)]

Lets create two functions, UseJoin and UsePlus to use the respective join and + functionality.

>>> def UsePlus():
    return [myl[i] + myl[i + 1] for i in range(0,len(myl), 2)]

>>> def UseJoin():
    [''.join((myl[i],myl[i + 1])) for i in range(0,len(myl), 2)]

Lets run timeit with the first list

>>> myl=myl1
>>> t1=timeit.Timer("UsePlus()","from __main__ import UsePlus")
>>> t2=timeit.Timer("UseJoin()","from __main__ import UseJoin")
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
2.48 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.61 usec/pass
>>> 

They have almost the same runtime.

Lets use cProfile

>>> myl=myl2
>>> cProfile.run("UsePlus()")
         5 function calls in 0.001 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 <pyshell#1376>:1(UsePlus)
        1    0.000    0.000    0.001    0.001 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {range}


>>> cProfile.run("UseJoin()")
         5005 function calls in 0.029 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.015    0.015    0.029    0.029 <pyshell#1388>:1(UseJoin)
        1    0.000    0.000    0.029    0.029 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
     5000    0.014    0.000    0.014    0.000 {method 'join' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {range}

And it looks that using Join, results in unnecessary function calls which could add to the overhead.

Now coming back to the question. Should one discourage the use of + over join in all cases?

I believe no, things should be taken into consideration

  1. Length of the String in Question
  2. No of Concatenation Operation.

And off-course in a development pre-mature optimization is evil.

Waiting for Target Device to Come Online

Go to the Sdk manager--> SDKtools --> instal the emulator 25.3.1

TSQL - Cast string to integer or return default value

Regards.

I wrote a useful scalar function to simulate the TRY_CAST function of SQL SERVER 2012 in SQL Server 2008.

You can see it in the next link below and we help each other to improve it. TRY_CAST Function for SQL Server 2008 https://gist.github.com/jotapardo/800881eba8c5072eb8d99ce6eb74c8bb

The two main differences are that you must pass 3 parameters and you must additionally perform an explicit CONVERT or CAST to the field. However, it is still very useful because it allows you to return a default value if CAST is not performed correctly.

dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)

Example:

SELECT   CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL   
                        THEN 'Cast failed'  
                        ELSE 'Cast succeeded'  
                    END AS Result; 

For now only supports the data types INT, DATE, NUMERIC, BIT and FLOAT

I hope you find it useful.

CODE:

DECLARE @strSQL NVARCHAR(1000)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TRY_CAST]'))
    BEGIN
        SET @strSQL = 'CREATE FUNCTION [dbo].[TRY_CAST] () RETURNS INT AS BEGIN RETURN 0 END'
        EXEC sys.sp_executesql @strSQL
    END

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
------------------------------------------------------------------------------------------------------------------------
    Description:    
                    Syntax 
                    ---------------
                    dbo.TRY_CAST(Expression, Data_Type, ReturnValueIfErrorCast)

                    +---------------------------+-----------------------+
                    |   Expression              |   VARCHAR(8000)       |
                    +---------------------------+-----------------------+
                    |   Data_Type               |   VARCHAR(8000)       |
                    +---------------------------+-----------------------+
                    |   ReturnValueIfErrorCast  |   SQL_VARIANT = NULL  |
                    +---------------------------+-----------------------+


                    Arguments
                    ---------------
                    expression
                    The value to be cast. Any valid expression.

                    Data_Type
                    The data type into which to cast expression.

                    ReturnValueIfErrorCast
                    Value returned if cast fails or is not supported. Required. Set the DEFAULT value by default.


                    Return Type
                    ----------------
                    Returns value cast to SQL_VARIANT type if the cast succeeds; otherwise, returns null if the parameter @pReturnValueIfErrorCast is set to DEFAULT, 
                    or that the user indicates.


                    Remarks
                    ----------------
                    dbo.TRY_CAST function simulates the TRY_CAST function reserved of SQL SERVER 2012 for using in SQL SERVER 2008. 
                    dbo.TRY_CAST function takes the value passed to it and tries to convert it to the specified Data_Type. 
                    If the cast succeeds, dbo.TRY_CAST returns the value as SQL_VARIANT type; if the cast doesn´t succees, null is returned if the parameter @pReturnValueIfErrorCast is set to DEFAULT. 
                    If the Data_Type is unsupported will return @pReturnValueIfErrorCast.
                    dbo.TRY_CAST function requires user make an explicit CAST or CONVERT in ANY statements.
                    This version of dbo.TRY_CAST only supports CAST for INT, DATE, NUMERIC and BIT types.


                    Examples
                    ====================================================================================================

                    --A. Test TRY_CAST function returns null

                        SELECT   
                            CASE WHEN dbo.TRY_CAST('6666666166666212', 'INT', DEFAULT) IS NULL   
                            THEN 'Cast failed'  
                            ELSE 'Cast succeeded'  
                        END AS Result; 

                    GO

                    --B. Error Cast With User Value

                        SELECT   
                            dbo.TRY_CAST('2147483648', 'INT', DEFAULT) AS [Error Cast With DEFAULT],
                            dbo.TRY_CAST('2147483648', 'INT', -1) AS [Error Cast With User Value],
                            dbo.TRY_CAST('2147483648', 'INT', NULL) AS [Error Cast With User NULL Value]; 

                        GO 

                    --C. Additional CAST or CONVERT required in any assignment statement

                        DECLARE @IntegerVariable AS INT

                        SET @IntegerVariable = CAST(dbo.TRY_CAST(123, 'INT', DEFAULT) AS INT)

                        SELECT @IntegerVariable

                        GO 

                        IF OBJECT_ID('tempdb..#temp') IS NOT NULL
                            DROP TABLE #temp

                        CREATE TABLE #temp (
                            Id INT IDENTITY
                            , FieldNumeric NUMERIC(3, 1)
                            )

                        INSERT INTO dbo.#temp (FieldNumeric)
                        SELECT CAST(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', 0) AS NUMERIC(3, 1));--Need explicit CAST on INSERT statements

                        SELECT *
                        FROM #temp

                        DROP TABLE #temp

                        GO 

                    --D. Supports CAST for INT, DATE, NUMERIC and BIT types.

                        SELECT dbo.TRY_CAST(2147483648, 'INT', 0) AS [Cast failed]
                            , dbo.TRY_CAST(2147483647, 'INT', 0) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST(212, 'INT', 0), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST('AAAA0101', 'DATE', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST('20160101', 'DATE', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST('2016-01-01', 'DATE', DEFAULT), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST(1.23, 'NUMERIC(3,1)', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST(12.3, 'NUMERIC(3,1)', DEFAULT), 'BaseType') AS [BaseType];

                        SELECT dbo.TRY_CAST('A', 'BIT', DEFAULT) AS [Cast failed]
                            , dbo.TRY_CAST(1, 'BIT', DEFAULT) AS [Cast succeeded]
                            , SQL_VARIANT_PROPERTY(dbo.TRY_CAST('123', 'BIT', DEFAULT), 'BaseType') AS [BaseType];

                        GO 

                    --E. B. TRY_CAST return NULL on unsupported data_types

                        SELECT dbo.TRY_CAST(4, 'xml', DEFAULT) AS [unsupported];  

                        GO  

                    ====================================================================================================

------------------------------------------------------------------------------------------------------------------------
    Responsible:    Javier Pardo 
    Date:           diciembre 29/2016
    WB tests:       Javier Pardo 
------------------------------------------------------------------------------------------------------------------------
    Update by:      Javier Eduardo Pardo Moreno 
    Date:           febrero 16/2017
    Id update:      JEPM20170216
    Description:    Fix  ISNUMERIC function makes it unreliable. SELECT dbo.TRY_CAST('+', 'INT', 0) will yield Msg 8114, 
                    Level 16, State 5, Line 16 Error converting data type varchar to float.
                    ISNUMERIC() function treats few more characters as numeric, like: – (minus), + (plus), $ (dollar), \ (back slash), (.)dot and (,)comma
                    Collaborator aperiooculus (http://stackoverflow.com/users/3083382/aperiooculus )

                    Fix dbo.TRY_CAST('2013/09/20', 'datetime', DEFAULT) for supporting DATETIME format

    WB tests:       Javier Pardo 

------------------------------------------------------------------------------------------------------------------------
*/

ALTER FUNCTION dbo.TRY_CAST
(
    @pExpression AS VARCHAR(8000),
    @pData_Type AS VARCHAR(8000),
    @pReturnValueIfErrorCast AS SQL_VARIANT = NULL
)
RETURNS SQL_VARIANT
AS
BEGIN
    --------------------------------------------------------------------------------
    --  INT 
    --------------------------------------------------------------------------------

    IF @pData_Type = 'INT'
    BEGIN
        IF ISNUMERIC(@pExpression) = 1 AND @pExpression NOT IN ('-','+','$','.',',','\')    --JEPM20170216
        BEGIN
            DECLARE @pExpressionINT AS FLOAT = CAST(@pExpression AS FLOAT)

            IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
            BEGIN
                RETURN CAST(@pExpressionINT as INT)
            END
            ELSE
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END --FIN IF @pExpressionINT BETWEEN - 2147483648.0 AND 2147483647.0
        END
        ELSE
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END -- FIN IF ISNUMERIC(@pExpression) = 1
    END -- FIN IF @pData_Type = 'INT'

    --------------------------------------------------------------------------------
    --  DATE    
    --------------------------------------------------------------------------------

    IF @pData_Type IN ('DATE','DATETIME')
    BEGIN
        IF ISDATE(@pExpression) = 1
        BEGIN

            DECLARE @pExpressionDATE AS DATETIME = cast(@pExpression AS DATETIME)

            IF @pData_Type = 'DATE'
            BEGIN
                RETURN cast(@pExpressionDATE as DATE)
            END

            IF @pData_Type = 'DATETIME'
            BEGIN
                RETURN cast(@pExpressionDATE as DATETIME)
            END

        END
        ELSE 
        BEGIN

            DECLARE @pExpressionDATEReplaced AS VARCHAR(50) = REPLACE(REPLACE(REPLACE(@pExpression,'\',''),'/',''),'-','')

            IF ISDATE(@pExpressionDATEReplaced) = 1
            BEGIN
                IF @pData_Type = 'DATE'
                BEGIN
                    RETURN cast(@pExpressionDATEReplaced as DATE)
                END

                IF @pData_Type = 'DATETIME'
                BEGIN
                    RETURN cast(@pExpressionDATEReplaced as DATETIME)
                END

            END
            ELSE
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END
        END --FIN IF ISDATE(@pExpression) = 1
    END --FIN IF @pData_Type = 'DATE'

    --------------------------------------------------------------------------------
    --  NUMERIC 
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'NUMERIC%'
    BEGIN

        IF ISNUMERIC(@pExpression) = 1
        BEGIN

            DECLARE @TotalDigitsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX('(',@pData_Type)+1,  CHARINDEX(',',@pData_Type) - CHARINDEX('(',@pData_Type) - 1)
                , @TotalDecimalsOfType AS INT = SUBSTRING(@pData_Type,CHARINDEX(',',@pData_Type)+1,  CHARINDEX(')',@pData_Type) - CHARINDEX(',',@pData_Type) - 1)
                , @TotalDigitsOfValue AS INT 
                , @TotalDecimalsOfValue AS INT 
                , @TotalWholeDigitsOfType AS INT 
                , @TotalWholeDigitsOfValue AS INT 

            SET @pExpression = REPLACE(@pExpression, ',','.')

            SET @TotalDigitsOfValue = LEN(REPLACE(@pExpression, '.',''))
            SET @TotalDecimalsOfValue = CASE Charindex('.', @pExpression)
                                        WHEN 0
                                            THEN 0
                                        ELSE Len(Cast(Cast(Reverse(CONVERT(VARCHAR(50), @pExpression, 128)) AS FLOAT) AS BIGINT))
                                        END 
            SET @TotalWholeDigitsOfType = @TotalDigitsOfType - @TotalDecimalsOfType
            SET @TotalWholeDigitsOfValue = @TotalDigitsOfValue - @TotalDecimalsOfValue

            -- The total digits can not be greater than the p part of NUMERIC (p, s)
            -- The total of decimals can not be greater than the part s of NUMERIC (p, s)
            -- The total digits of the whole part can not be greater than the subtraction between p and s
            IF (@TotalDigitsOfValue <= @TotalDigitsOfType) AND (@TotalDecimalsOfValue <= @TotalDecimalsOfType) AND (@TotalWholeDigitsOfValue <= @TotalWholeDigitsOfType)
            BEGIN
                DECLARE @pExpressionNUMERIC AS FLOAT
                SET @pExpressionNUMERIC = CAST (ROUND(@pExpression, @TotalDecimalsOfValue) AS FLOAT) 

                RETURN @pExpressionNUMERIC --Returns type FLOAT
            END 
            else
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END-- FIN IF (@TotalDigitisOfValue <= @TotalDigits) AND (@TotalDecimalsOfValue <= @TotalDecimals) 

        END
        ELSE 
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'NUMERIC%'

    --------------------------------------------------------------------------------
    --  BIT 
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'BIT'
    BEGIN
        IF ISNUMERIC(@pExpression) = 1
        BEGIN
            RETURN CAST(@pExpression AS BIT) 
        END
        ELSE 
        BEGIN
            RETURN @pReturnValueIfErrorCast
        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'BIT'


    --------------------------------------------------------------------------------
    --  FLOAT   
    --------------------------------------------------------------------------------

    IF @pData_Type LIKE 'FLOAT'
    BEGIN
        IF ISNUMERIC(REPLACE(REPLACE(@pExpression, CHAR(13), ''), CHAR(10), '')) = 1
        BEGIN

            RETURN CAST(@pExpression AS FLOAT) 
        END
        ELSE 
        BEGIN

            IF REPLACE(@pExpression, CHAR(13), '') = '' --Only white spaces are replaced, not new lines
            BEGIN
                RETURN 0
            END
            ELSE 
            BEGIN
                RETURN @pReturnValueIfErrorCast
            END --IF REPLACE(@pExpression, CHAR(13), '') = '' 

        END --FIN IF ISNUMERIC(@pExpression) = 1
    END --IF @pData_Type LIKE 'FLOAT'

    --------------------------------------------------------------------------------
    --  Any other unsupported data type will return NULL or the value assigned by the user to @pReturnValueIfErrorCast  
    --------------------------------------------------------------------------------

    RETURN @pReturnValueIfErrorCast



END

Reading in a JSON File Using Swift

I'm providing another answer because none of the ones here are geared toward loading the resource from the test bundle. If you are consuming a remote service that puts out JSON and want to unit test parsing the results without hitting the actual service, you take one or more responses and put them into files in the Tests folder in your project.

func testCanReadTestJSONFile() {
    let path = NSBundle(forClass: ForecastIOAdapterTests.self).pathForResource("ForecastIOSample", ofType: "json")
    if let jsonData = NSData(contentsOfFile:path!) {
        let json = JSON(data: jsonData)
        if let currentTemperature = json["currently"]["temperature"].double {
            println("json: \(json)")
            XCTAssertGreaterThan(currentTemperature, 0)
        }
    }
}

This also uses SwiftyJSON but the core logic of getting the test bundle and loading the file is the answer to the question.

MySQL parameterized queries

Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect (with security issues)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct (with escaping)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

You can try usage:

# echo "/usr/lib/oracle/12.2/client64/lib" > /etc/ld.so.conf.d/oracle.conf
# ldconfig

This problem are because oracleinstant client not configure shared library.

How to disable RecyclerView scrolling?

recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            // Stop only scrolling.
            return rv.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING;
        }
    });

JQuery Find #ID, RemoveClass and AddClass

corrected Code:

jQuery('#testID2').addClass('test3').removeClass('test2');

Accept server's self-signed ssl certificate in Java client

I chased down this problem to a certificate provider that is not part of the default JVM trusted hosts as of JDK 8u74. The provider is www.identrust.com, but that was not the domain I was trying to connect to. That domain had gotten its certificate from this provider. See Will the cross root cover trust by the default list in the JDK/JRE? -- read down a couple entries. Also see Which browsers and operating systems support Let’s Encrypt.

So, in order to connect to the domain I was interested in, which had a certificate issued from identrust.com I did the following steps. Basically, I had to get the identrust.com (DST Root CA X3) certificate to be trusted by the JVM. I was able to do that using Apache HttpComponents 4.5 like so:

1: Obtain the certificate from indettrust at Certificate Chain Download Instructions. Click on the DST Root CA X3 link.

2: Save the string to a file named "DST Root CA X3.pem". Be sure to add the lines "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" in the file at the beginning and the end.

3: Create a java keystore file, cacerts.jks with the following command:

keytool -import -v -trustcacerts -alias IdenTrust -keypass yourpassword -file dst_root_ca_x3.pem -keystore cacerts.jks -storepass yourpassword

4: Copy the resulting cacerts.jks keystore into the resources directory of your java/(maven) application.

5: Use the following code to load this file and attach it to the Apache 4.5 HttpClient. This will solve the problem for all domains that have certificates issued from indetrust.com util oracle includes the certificate into the JRE default keystore.

SSLContext sslcontext = SSLContexts.custom()
        .loadTrustMaterial(new File(CalRestClient.class.getResource("/cacerts.jks").getFile()), "yourpasword".toCharArray(),
                new TrustSelfSignedStrategy())
        .build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
        .setSSLSocketFactory(sslsf)
        .build();

When the project builds then the cacerts.jks will be copied into the classpath and loaded from there. I didn't, at this point in time, test against other ssl sites, but if the above code "chains" in this certificate then they will work too, but again, I don't know.

Reference: Custom SSL context and How do I accept a self-signed certificate with a Java HttpsURLConnection?

How can I color Python logging output?

Install the colorlog package, you can use colors in your log messages immediately:

  • Obtain a logger instance, exactly as you would normally do.
  • Set the logging level. You can also use the constants like DEBUG and INFO from the logging module directly.
  • Set the message formatter to be the ColoredFormatter provided by the colorlog library.
import colorlog

logger = colorlog.getLogger()
logger.setLevel(colorlog.colorlog.logging.DEBUG)

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter())
logger.addHandler(handler)

logger.debug("Debug message")
logger.info("Information message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")

output: enter image description here


UPDATE: extra info

Just update ColoredFormatter:

handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))

output: enter image description here


Package:

pip install colorlog

output:

Collecting colorlog
  Downloading colorlog-4.6.2-py2.py3-none-any.whl (10.0 kB)
Installing collected packages: colorlog
Successfully installed colorlog-4.6.2

How do I center this form in css?

i dont know if the full resolution has been made for this yet. i know that from doing a 2 column page with fixed left side bar, to get a contact us form centered on my page i put the following:

    form {
 width: 100%;
 margin-left: auto;
 margin-right: auto;
 display: inline-block;
 }

this worked for me so thought id throw in my resolution to the same problem

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

Delete file from internal storage

String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete(); 
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);

The code File dir = getFilesDir(); doesn't work because this is a request for a File object. You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.

div background color, to change onhover

Set

display: block;

on a and give some height

Cannot find java. Please use the --jdkhome switch

In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.

When I see a directory structure with bin and jre subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.

Java command not found on Linux

I had these choices:

-----------------------------------------------
*  1           /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
 + 2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   3           /home/ec2-user/local/java/jre1.7.0_25/bin/java

When I chose 3, it didn't work. When I chose 2, it did work.

how do I get a new line, after using float:left?

You need to "clear" the float after every 6 images. So with your current code, change the styles for containerdivNewLine to:

.containerdivNewLine { clear: both; float: left; display: block; position: relative; } 

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

Order by descending date - month, day and year

try ORDER BY MONTH(Date),DAY(DATE)

Try this:

ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC

Worked perfectly on a JET DB.

How to do vlookup and fill down (like in Excel) in R?

Starting with:

houses <- read.table(text="Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3",col.names=c("HouseType","HouseTypeNo"))

... you can use

as.numeric(factor(houses$HouseType))

... to give a unique number for each house type. You can see the result here:

> houses2 <- data.frame(houses,as.numeric(factor(houses$HouseType)))
> houses2
  HouseType HouseTypeNo as.numeric.factor.houses.HouseType..
1      Semi           1                                    3
2    Single           2                                    4
3       Row           3                                    2
4    Single           2                                    4
5 Apartment           4                                    1
6 Apartment           4                                    1
7       Row           3                                    2

... so you end up with different numbers on the rows (because the factors are ordered alphabetically) but the same pattern.

(EDIT: the remaining text in this answer is actually redundant. It occurred to me to check and it turned out that read.table() had already made houses$HouseType into a factor when it was read into the dataframe in the first place).

However, you may well be better just to convert HouseType to a factor, which would give you all the same benefits as HouseTypeNo, but would be easier to interpret because the house types are named rather than numbered, e.g.:

> houses3 <- houses
> houses3$HouseType <- factor(houses3$HouseType)
> houses3
  HouseType HouseTypeNo
1      Semi           1
2    Single           2
3       Row           3
4    Single           2
5 Apartment           4
6 Apartment           4
7       Row           3
> levels(houses3$HouseType)
[1] "Apartment" "Row"       "Semi"      "Single"  

Change working directory in my current shell context when running Node script

Short answer: no (easy?) way, but you can do something that serves your purpose.

I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:

spawn('bash', ['-i'], {
  cwd: new_cwd,
  env: new_env,
  stdio: 'inherit'
});

After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:

  • There is an additional process, so...
  • you have to write 'exit' to come back, and then...
  • after existing, all changes are undone.

However, for me, that differences are desirable.

HTML5 record audio to file

Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.

Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...

Code Source


Currently, there are three ways to do it:

  1. as wav[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.
  2. as mp3[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.
  3. as ogg [ client+ server(node.js) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.

    ogg recording example( only firefox):

    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();  // to start recording.    
    ...
    mediaRecorder.stop();   // to stop recording.
    mediaRecorder.ondataavailable = function(e) {
        // do something with the data.
    }
    

    Fiddle Demo for ogg recording.

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

No you can't; datetime will be stored in default format only while creating table and then you can change the display format in you select query the way you want using the Mysql Date Time Functions

How to remove all CSS classes using jQuery/JavaScript?

I had similar issue. In my case on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jquery to remove this class on every element/control I wont and everything works and looks great now.

This is my code for removing aspNetDisabled class:

$(document).ready(function () {

    $("span").removeClass("aspNetDisabled");
    $("select").removeClass("aspNetDisabled");
    $("input").removeClass("aspNetDisabled");

}); 

How to delete directory content in Java?

You can't delete on an array ! This should work better :

for (File f : files) f.delete();

But it won't work if the folders are not empty. For this cases, you will need to recursively descend into the folder hierarchy and delete everything. Yes it's a shame Java can't do that by default...

Multiplying Two Columns in SQL Server

This code is used to multiply the values of one column

select exp(sum(log(column))) from table

How to create a MySQL hierarchical recursive query?

I have made a query for you. This will give you Recursive Category with a Single Query:

SELECT id,NAME,'' AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 WHERE prent is NULL
UNION 
SELECT b.id,a.name,b.name AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id WHERE a.prent is NULL AND b.name IS NOT NULL 
UNION 
SELECT c.id,a.name,b.name AS subName,c.name AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id WHERE a.prent is NULL AND c.name IS NOT NULL 
UNION 
SELECT d.id,a.name,b.name AS subName,c.name AS subsubName,d.name AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id LEFT JOIN Table1 AS d ON d.prent=c.id WHERE a.prent is NULL AND d.name IS NOT NULL 
ORDER BY NAME,subName,subsubName,subsubsubName

Here is a fiddle.

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

CSS/HTML: Create a glowing border around an Input Field

You better use Twitter Bootstrap which contains all of this nice stuff inside. Particularly here is exactly what you want.

In addition, you can use different themes built for Twitter Bootstrap from this website

Remove white space below image

Give the height of the div .youtube-thumb the height of the image. That should set the problem in Firefox browser.

.youtube-thumb{ height: 106px }

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Check if a given key already exists in a dictionary and increment it

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

Delete cookie by name?

//if passed exMins=0 it will delete as soon as it creates it.

function setCookie(cname, cvalue, exMins) {
    var d = new Date();
    d.setTime(d.getTime() + (exMins*60*1000));
    var expires = "expires="+d.toUTCString();  
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

setCookie('cookieNameToDelete','',0) // this will delete the cookie.

SELECT max(x) is returning null; how can I make it return 0?

You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:

SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1

How to get an input text value in JavaScript

The reason that this doesn't work is because the variable doesn't change with the textbox. When it initially runs the code it gets the value of the textbox, but afterwards it isn't ever called again. However, when you define the variable in the function, every time that you call the function the variable updates. Then it alerts the variable which is now equal to the textbox's input.

How do I resize a Google Map with JavaScript after it has loaded?

This is best it will do the Job done. It will re-size your Map. No need to inspect element anymore to re-size your Map. What it does it will automatically trigger re-size event .

    google.maps.event.addListener(map, "idle", function()
        {
            google.maps.event.trigger(map, 'resize');
        });

        map_array[Next].setZoom( map.getZoom() - 1 );
    map_array[Next].setZoom( map.getZoom() + 1 );

Proxies with Python 'Requests' module

I have found that urllib has some really good code to pick up the system's proxy settings and they happen to be in the correct form to use directly. You can use this like:

import urllib

...
r = requests.get('http://example.org', proxies=urllib.request.getproxies())

It works really well and urllib knows about getting Mac OS X and Windows settings as well.

How to kill a process running on particular port in Linux?

Get the PID of the task and kill it.

lsof -ti:8080 | xargs kill

How to check if a directory containing a file exist?

EDIT: as of Java8 you'd better use Files class:

Path resultingPath = Files.createDirectories('A/B');

I don't know if this ultimately fixes your problem but class File has method mkdirs() which fully creates the path specified by the file.

File f = new File("/A/B/");
f.mkdirs();

SQL Server : Arithmetic overflow error converting expression to data type int

On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.

Python: Find in list

 lstr=[1, 2, 3]
 lstr=map(str,lstr)
 r=re.compile('^(3){1}')
 results=list(filter(r.match,lstr))
 print(results)

Get all validation errors from Angular 2 FormGroup

Try This , it will call validation for all control in form :

validateAllFormControl(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
    const control = formGroup.get(field);             
    if (control instanceof FormControl) {             
      control.markAsTouched({ onlySelf: true });
    } else if (control instanceof FormGroup) {        
      this.validateAllFormControl(control);            
    }
  });
}

Installing Google Protocol Buffers on mac

FWIW., the latest version of brew is at protobuf 3.0, and doesn't include any formulae for the older versions. This is somewhat "inconvenient".

While protobuf may be compatible at the wire level, it is absolutely not compatible at the level of generated java classes: you can't use .class files generated with protoc 2.4 with the protobuf-2.5 JAR, etc. etc. This is why updating protobuf versions is such a sensitive topic in the Hadoop stack: it invariably requires coordination across different projects, and is traumatic enough that nobody likes to do it.

Greater than and less than in one statement

Nowadays you can use lodash:

var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

push multiple elements to array

If you want to add multiple items, you have to use the spread operator

a = [1,2]
b = [3,4,5,6]
a.push(...b)

The output will be

a = [1,2,3,4,5,6]

Create Table from View

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
œ

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

    SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';

Hope This Might Help

How to add button tint programmatically

Have you tried something like this?

button.setBackgroundTintList(getResources().getColorStateList(R.id.blue_100));

note that getResources() will only work in an activity. But it can be called on every context too.

Peak-finding algorithm for Python/SciPy

I do not think that what you are looking for is provided by SciPy. I would write the code myself, in this situation.

The spline interpolation and smoothing from scipy.interpolate are quite nice and might be quite helpful in fitting peaks and then finding the location of their maximum.

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

How to use SortedMap interface in Java?

TreeMap sorts by the key natural ordering. The keys should implement Comparable or be compatible with a Comparator (if you passed one instance to constructor). In you case, Float already implements Comparable so you don't have to do anything special.

You can call keySet to retrieve all the keys in ascending order.

Python list sort in descending order

In one line, using a lambda:

timestamps.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

Passing a function to list.sort:

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamps.sort(key=foo, reverse=True)

How to reset Django admin password?

I think,The better way At the command line

python manage.py createsuperuser

Disable XML validation in Eclipse

The other answers may work for you, but they did not cover my case. I wanted some XML to be validated, and others not. This image shows how to exclude certain folders (or files) for XML validation.

Begin by right clicking the root of your Eclipse project. Select the last item: Properties...

enter image description here

(If your browser scales this image very small, right click and open in a new window or tab.)

  • Eclipse appears to be very sensitive if you click the **Browse File...* or **Browser Folder...* button. This dialog needs some work!
  • This was done using Eclipse 4.3 (Kepler).

Python Image Library fails with message "decoder JPEG not available" - PIL

This question was posted quite a while ago and most of the answers are quite old too. So when I spent hours trying to figure this out, nothing worked, and I tried all suggestions in this post.

I was still getting the standard JPEG errors when trying to upload a JPG in my Django avatar form:

raise IOError("decoder %s not available" % decoder_name)
OSError: decoder jpeg not available

Then I checked the repository for Ubuntu 12.04 and noticed some extra packages for libjpeg. I installed these and my problem was solved:

sudo apt-get install libjpeg62 libjpeg62-dev

Installing these removed libjpeg-dev, libjpeg-turbo8-dev, and libjpeg8-dev.

Hope this helps someone in the year 2015 and beyond!

Cheers

Failed to connect to camera service

since this question was asked 4 years back..and i didn't realised that unless mentioned by the Questioner..when there were no Run time permissions support.

but hoping it useful for the users who still caught in this situation.. Have a look at Run Time Permissions ,for me it solved the problem when i added Run time permissions to grant camera access. Alternatively you can grant permissions to the app manually by going to your mobile settings=>Apps=>(select your app)=>Permissions section in the appeared window and enable/disable desired permissions. hope this will work.

How to search for a string in an arraylist

Since your list doesn't appear to be sorted, you have to iterate over its elements. Apply startsWith() or contains() to each element, and store matches in an auxiliary list. Return the auxiliary list when done.

if block inside echo statement?

You can always use the ( <condition> ? <value if true> : <value if false> ) syntax (it's called the ternary operator - thanks to Mark for remining me :) ).

If <condition> is true, the statement would be evaluated as <value if true>. If not, it would be evaluated as <value if false>

For instance:

$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";

This is the same as:

$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
  echo "Fourteen is more than twelve";
}else{
  echo "Fourteen is not more than twelve";
}