Programs & Examples On #Pylint

Python source code analyzer looking for bugs and signs of poor quality.

How do I disable a Pylint warning?

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.

Pylint "unresolved import" error in Visual Studio Code

I was facing the same problem while importing the project-related(non standard) modules. Detailed explanation of the problem

Directory structure:

Project_dir:
    .vscode/settings.json
    dir_1
        > a
        > b
        > c
    dir_2
        > x
        > y
        > z

What we want:

Project_dir
    dir_3
        import a
        import y

Here "import a" and "import y" fails with following error:

Import "dir_1.a" could not be resolvedPylancereportMissingImports
Import "dir_2.y" could not be resolvedPylancereportMissingImports

What worked for me:

Appending the top directory which contains the modules to be imported.

In above example add the follwoing "Code to append" in ".vscode/settings.json"

Filename:

.vscode/settings.json

Code to append:

"python.analysis.extraPaths": [dir_1, dir_2]

Python: avoiding pylint warnings about too many arguments

Python has some nice functional programming tools that are likely to fit your needs well. Check out lambda functions and map. Also, you're using dicts when it seems like you'd be much better served with lists. For the simple example you provided, try this idiom. Note that map would be better and faster but may not fit your needs:

def mysum(d):
   s = 0  
   for x in d:
        s += x
   return s

def mybigfunction():
   d = (x1, x2, x3, x4, x5, x6, x7, x8, x9)
   return mysum(d)

You mentioned having a lot of local variables, but frankly if you're dealing with lists (or tuples), you should use lists and factor out all those local variables in the long run.

Is it possible to ignore one single specific line with Pylint?

I believe you're looking for...

import config.logging_settings  # @UnusedImport

Note the double space before the comment to avoid hitting other formatting warnings.

Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport).

How do I disable "missing docstring" warnings at a file-level in Pylint?

No. Pylint doesn't currently let you discriminate between doc-string warnings.

However, you can use Flake8 for all Python code checking along with the doc-string extension to ignore this warning.

Install the doc-string extension with pip (internally, it uses pydocstyle).

pip install flake8_docstrings

You can then just use the --ignore D100 switch. For example, flake8 file.py --ignore D100

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Error message "Linter pylint is not installed"

  1. Open a terminal (ctrl+~)
  2. Run the command pip install pylint

If that doesn't work: On the off chance you've configured a non-default Python path for your editor, you'll need to match that Python's install location with the pip executable you're calling from the terminal.

This is an issue because the Python extension's settings enable Pylint by default. If you'd rather turn off linting, you can instead change this setting from true to false in your user or workspace settings:

"python.linting.pylintEnabled": false

PyLint "Unable to import" error - how to set PYTHONPATH?

The solution to alter path in init-hook is good, but I dislike the fact that I had to add absolute path there, as result I can not share this pylintrc file among the developers of the project. This solution using relative path to pylintrc file works better for me:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

Note that pylint.config.PYLINTRC also exists and has the same value as find_pylintrc().

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)


Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

Java - How to create new Entry (key, value)

org.apache.commons.lang3.tuple.Pair implements java.util.Map.Entry and can also be used standalone.

Also as others mentioned Guava's com.google.common.collect.Maps.immutableEntry(K, V) does the trick.

I prefer Pair for its fluent Pair.of(L, R) syntax.

Type definition in object literal in TypeScript

I'm surprised that no-one's mentioned this but you could just create an interface called ObjectLiteral, that accepts key: value pairs of type string: any:

interface ObjectLiteral {
  [key: string]: any;
}

Then you'd use it, like this:

let data: ObjectLiteral = {
  hello: "world",
  goodbye: 1,
  // ...
};

An added bonus is that you can re-use this interface many times as you need, on as many objects you'd like.

Good luck.

C# LINQ select from list

        var eventids = GetEventIdsByEventDate(DateTime.Now);
        var result = eventsdb.Where(e => eventids.Contains(e));

If you are returnning List<EventFeed> inside the method, you should change the method return type from IEnumerable<EventFeed> to List<EventFeed>.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Add Json NamingStrategy property to your class definition.

_x000D_
_x000D_
[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
_x000D_
_x000D_
_x000D_

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

Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size. Let’s see two different methods of checking if string is empty or not: Method #1 : Using Len() Using Len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as an empty string even its non-zero.

Method #2 : Using not

Not operator can also perform the task similar to Len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.

Good Luck!

fileReader.readAsBinaryString to upload files

Use fileReader.readAsDataURL( fileObject ), this will encode it to base64, which you can safely upload to your server.

How do I connect to a MySQL Database in Python?

Just a modification in above answer. Simply run this command to install mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember! It is case sensitive.

What are the various "Build action" settings in Visual Studio project properties and what do they do?

From the documentation:

The BuildAction property indicates what Visual Studio does with a file when a build is executed. BuildAction can have one of several values:

None - The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.

Compile - The file is compiled into the build output. This setting is used for code files.

Content - The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file.

Embedded Resource - This file is embedded in the main project build output as a DLL or executable. It is typically used for resource files.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Start the server in debug mode and It will track changes inside methods. Other changes It will ask to restart the module.

Java - Check if input is a positive integer, negative integer, natural number and so on.

For integers you can use Integer.signum()

Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)

How can two strings be concatenated?

For the first non-paste() answer, we can look at stringr::str_c() (and then toString() below). It hasn't been around as long as this question, so I think it's useful to mention that it also exists.

Very simple to use, as you can see.

tmp <- cbind("GAD", "AB")
library(stringr)
str_c(tmp, collapse = ",")
# [1] "GAD,AB"

From its documentation file description, it fits this problem nicely.

To understand how str_c works, you need to imagine that you are building up a matrix of strings. Each input argument forms a column, and is expanded to the length of the longest argument, using the usual recyling rules. The sep string is inserted between each column. If collapse is NULL each row is collapsed into a single string. If non-NULL that string is inserted at the end of each row, and the entire matrix collapsed to a single string.

Added 4/13/2016: It's not exactly the same as your desired output (extra space), but no one has mentioned it either. toString() is basically a version of paste() with collapse = ", " hard-coded, so you can do

toString(tmp)
# [1] "GAD, AB"

Swift: declare an empty dictionary

Swift:

var myDictionary = Dictionary<String, AnyObject>()

How can I convert a date into an integer?

var dates = dates_as_int.map(function(dateStr) {
    return new Date(dateStr).getTime();
});

=>

[1468959781804, 1469029434776, 1469199218634, 1469457574527]

Update: ES6 version:

const dates = dates_as_int.map(date => new Date(date).getTime())

How should I escape commas and speech marks in CSV files so they work in Excel?

We eventually found the answer to this.

Excel will only respect the escaping of commas and speech marks if the column value is NOT preceded by a space. So generating the file without spaces like this...

Reference,Title,Description
1,"My little title","My description, which may contain ""speech marks"" and commas."
2,"My other little title","My other description, which may also contain ""speech marks"" and commas."

... fixed the problem. Hope this helps someone!

C/C++ maximum stack size of program

Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.

Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.

You should specify which OS and development environment you're using for more targeted assistance.

For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack option of ld to do that.

Button Center CSS

The problem is with the following CSS line on .nav_button:

margin: 0 auto;

That would only work if you had one button, that's why they're off-centered when there are more than one nav_button divs.

If you want all your buttons centered nest the nav_buttons in another div:

<div class="nav">
    <div class="centerButtons">
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Home</div>
            <div class="b_right"></div>
        </div>
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Contact Us</div>
            <div class="b_right"></div>
        </div>
    </div>
</div>

And style it this way:

.nav{
    margin-top:167px;
    width:1024px;
    height:34px;
}

/* Centers the div that nests the nav_buttons */
.centerButtons {
    margin: 0 auto;
    float: left;
} 

.nav_button{
    height:34px;
    margin-right:10px;
    float: left;
}

Create line after text with css

There's no need for extra wrappers or span elements anymore. Flexbox and Grid can handle this easily.

_x000D_
_x000D_
h2 {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
h2::after {_x000D_
  content: '';_x000D_
  flex: 1;_x000D_
  margin-left: 1rem;_x000D_
  height: 1px;_x000D_
  background-color: #000;_x000D_
}
_x000D_
<h2>Heading</h2>
_x000D_
_x000D_
_x000D_

How do I delete rows in a data frame?

Create id column in your data frame or use any column name to identify the row. Using index is not fair to delete.

Use subset function to create new frame.

updated_myData <- subset(myData, id!= 6)
print (updated_myData)

updated_myData <- subset(myData, id %in% c(1, 3, 5, 7))
print (updated_myData)

Converting Varchar Value to Integer/Decimal Value in SQL Server

The reason could be that the summation exceeded the required number of digits - 4. If you increase the size of the decimal to decimal(10,2), it should work

 SELECT SUM(convert(decimal(10,2), Stuff)) as result FROM table

OR

 SELECT SUM(CAST(Stuff AS decimal(6,2))) as result FROM table

How to check if JSON return is empty with jquery

Just test if the array is empty.

$.getJSON(url,function(json){
    if ( json.length == 0 ) {
        console.log("NO DATA!")
    }
});

How to print a groupby object

Thanks to Surya for good insights. I'd clean up his solution and simply do:

for key, value in df.groupby('A'):
    print(key, value)

How can I convert a char to int in Java?

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

How to set max width of an image in CSS

Given your container width 600px.

If you want only bigger images than that to fit inside, add: CSS:

#ImageContainer img {
    max-width: 600px;
}

If you want ALL images to take the avaiable (600px) space:

#ImageContainer img {
    width: 600px;
}

Rails and PostgreSQL: Role postgres does not exist

The installation procedure creates a user account called postgres that is associated with the default Postgres role. In order to use Postgres, you can log into that account. But if not explicitly specified the rails app looks for a different role, more particularly the role having your unix username which might not be created in the postgres roles.

To overcome that, you can create a new role, first by switching over to the default role postgres which was created during installation

sudo -i -u postgres

After you are logged in to the postgres account, you can create a new user by the command:

createuser --interactive

This will prompt you with some choices and, based on your responses, execute the correct Postgres commands to create a user.

Pass over a role name and some permissions and the role is created, you can then migrate your db

Clone only one branch

You could create a new repo with

git init 

and then use

git fetch url-to-repo branchname:refs/remotes/origin/branchname

to fetch just that one branch into a local remote-tracking branch.

CSS "and" and "or"

The :not pseudo-class is not supported by IE. I'd got for something like this instead:

.registration_form_right input[type="text"],
.registration_form_right input[type="password"],
.registration_form_right input[type="submit"],
.registration_form_right input[type="button"] {
  ...
}

Some duplication there, but it's a small price to pay for higher compatibility.

Making a cURL call in C#

Late response but this is what I ended up doing. If you want to run your curl commands very similarly as you run them on linux and you have windows 10 or latter do this:

    public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
    {
        if (string.IsNullOrEmpty(curlCommand))
            return "";

        curlCommand = curlCommand.Trim();

        // remove the curl keworkd
        if (curlCommand.StartsWith("curl"))
        {
            curlCommand = curlCommand.Substring("curl".Length).Trim();
        }

        // this code only works on windows 10 or higher
        {

            curlCommand = curlCommand.Replace("--compressed", "");

            // windows 10 should contain this file
            var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

            if (System.IO.File.Exists(fullPath) == false)
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Windows 10 or higher is required to run this application");
            }

            // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
            List<string> parameters = new List<string>();


            // separate parameters to escape quotes
            try
            {
                Queue<char> q = new Queue<char>();

                foreach (var c in curlCommand.ToCharArray())
                {
                    q.Enqueue(c);
                }

                StringBuilder currentParameter = new StringBuilder();

                void insertParameter()
                {
                    var temp = currentParameter.ToString().Trim();
                    if (string.IsNullOrEmpty(temp) == false)
                    {
                        parameters.Add(temp);
                    }

                    currentParameter.Clear();
                }

                while (true)
                {
                    if (q.Count == 0)
                    {
                        insertParameter();
                        break;
                    }

                    char x = q.Dequeue();

                    if (x == '\'')
                    {
                        insertParameter();

                        // add until we find last '
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \' 
                            if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                            {
                                currentParameter.Append('\'');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '\'')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else if (x == '"')
                    {
                        insertParameter();

                        // add until we find last "
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \"
                            if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                            {
                                currentParameter.Append('"');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '"')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else
                    {
                        currentParameter.Append(x);
                    }
                }
            }
            catch
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Invalid curl command");
            }

            StringBuilder finalCommand = new StringBuilder();

            foreach (var p in parameters)
            {
                if (p.StartsWith("-"))
                {
                    finalCommand.Append(p);
                    finalCommand.Append(" ");
                    continue;
                }

                var temp = p;

                if (temp.Contains("\""))
                {
                    temp = temp.Replace("\"", "\\\"");
                }
                if (temp.Contains("'"))
                {
                    temp = temp.Replace("'", "\\'");
                }

                finalCommand.Append($"\"{temp}\"");
                finalCommand.Append(" ");
            }


            using (var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "curl.exe",
                    Arguments = finalCommand.ToString(),
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    WorkingDirectory = Environment.SystemDirectory
                }
            })
            {
                proc.Start();

                proc.WaitForExit(timeoutInSeconds*1000);

                return proc.StandardOutput.ReadToEnd();
            }
        }
    }

The reason why the code is a little bit long is because windows will give you an error if you execute a single quote. In other words, the command curl 'https://google.com' will work on linux and it will not work on windows. Thanks to that method I created you can use single quotes and run your curl commands exactly as you run them on linux. This code also checks for escaping characters such as \' and \".

For example use this code as

var output = ExecuteCurl(@"curl 'https://google.com' -H 'Accept: application/json, text/javascript, */*; q=0.01'");

If you where to run that same string agains C:\Windows\System32\curl.exe it will not work because for some reason windows does not like single quotes.

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

Count number of matches of a regex in Javascript

As mentioned in my earlier answer, you can use RegExp.exec() to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match().

var re = /\s/g,
count = 0;

while (re.exec(text) !== null) {
    ++count;
}

return count;

How to know if an object has an attribute in Python

As Jarret Hardie answered, hasattr will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references:

EAFP vs LBYL (was Re: A little disappointed so far)
EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python

ie:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

... is preferred to:

if hasattr(a, 'property'):
    doStuff(a.property)
else:
    otherStuff()

MySQL WHERE IN ()

You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).

I assume your table looks somewhat like this

TABLE
================================
| group_id | user_ids | name   |
--------------------------------
| 1        | 1,4,6    | group1 |
--------------------------------
| 2        | 4,5,1    | group2 |    

so in your table of user groups, each row represents one group and in user_ids column you have set of user ids assigned to that group.

Normalized version of this table would look like this

GROUP
=====================
| id       | name   |
---------------------
| 1        | group1 |
---------------------
| 2        | group2 |    

GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1        | 1       |
----------------------
| 1        | 4       |
----------------------
| 1        | 6       |
----------------------
| 2        | 4       |
----------------------
| ...      

Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:

/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);

/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);

/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;

/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;

/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;

/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;

This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment, when you want to remove assignment you just delete row in group_user_assignment.

In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.

Here is sqlFiddle to play with.

"React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

  1. <TouchableHighlight> element can have only one child inside
  2. Make sure that you have imported Image

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

What does "request for member '*******' in something not a structure or union" mean?

It may means that you forgot include a header file that define this struct/union. For example:

foo.h file:

typedef union
{
    struct
    {
        uint8_t FIFO_BYTES_AVAILABLE    : 4;
        uint8_t STATE                   : 3;
        uint8_t CHIP_RDY                : 1;
    };
    uint8_t status;
} RF_CHIP_STATUS_t;

RF_CHIP_STATUS_t getStatus();

main.c file:

.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the  #include "foo.h" */
.
.
.

How to count occurrences of a column value efficiently in SQL?

If you're using Oracle, then a feature called analytics will do the trick. It looks like this:

select id, age, count(*) over (partition by age) from students;

If you aren't using Oracle, then you'll need to join back to the counts:

select a.id, a.age, b.age_count
  from students a
  join (select age, count(*) as age_count
          from students
         group by age) b
    on a.age = b.age

How to remove underline from a link in HTML?

<style="text-decoration: none">

The above code will be enough.Just paste this into the link you want to remove underline from.

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

How to remove item from array by value?

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]

How to convert string to XML using C#

// using System.Xml;

String rawXml =
      @"<root>
          <person firstname=""Riley"" lastname=""Scott"" />
          <person firstname=""Thomas"" lastname=""Scott"" />
      </root>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);

I think this should work.

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Deep cloning objects

In general, you implement the ICloneable interface and implement Clone yourself. C# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.

For a deep copy, there is no way it can know how to automatically do it.

How to format DateTime in Flutter , How to get current time in flutter?

Add intl package to your pubspec.yaml file.

import 'package:intl/intl.dart';

DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");

Converting DateTime object to String

String string = dateFormat.format(DateTime.now());

Converting String to DateTime object

DateTime dateTime = dateFormat.parse("2019-07-19 8:40:23");

Python String and Integer concatenation

string = 'string%d' % (i,)

String length in bytes in JavaScript

I compared some of the methods suggested here in Firefox for speed.

The string I used contained the following characters: œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=

All results are averages of 3 runs each. Times are in milliseconds. Note that all URIEncoding methods behaved similarly and had extreme results, so I only included one.

While there are some fluctuations based on the size of the string, the charCode methods (lovasoa and fuweichin) both perform similarly and the fastest overall, with fuweichin's charCode method the fastest. The Blob and TextEncoder methods performed similarly to each other. Generally the charCode methods were about 75% faster than the Blob and TextEncoder methods. The URIEncoding method was basically unacceptable.

Here are the results I got:

Size 6.4 * 10^6 bytes:

Lauri Oherd – URIEncoding:     6400000    et: 796
lovasoa – charCode:            6400000    et: 15
fuweichin – charCode2:         6400000    et: 16
simap – Blob:                  6400000    et: 26
Riccardo Galli – TextEncoder:  6400000    et: 23

Size 19.2 * 10^6 bytes: Blob does kind of a weird thing here.

Lauri Oherd – URIEncoding:     19200000    et: 2322
lovasoa – charCode:            19200000    et: 42
fuweichin – charCode2:         19200000    et: 45
simap – Blob:                  19200000    et: 169
Riccardo Galli – TextEncoder:  19200000    et: 70

Size 64 * 10^6 bytes:

Lauri Oherd – URIEncoding:     64000000    et: 12565
lovasoa – charCode:            64000000    et: 138
fuweichin – charCode2:         64000000    et: 133
simap – Blob:                  64000000    et: 231
Riccardo Galli – TextEncoder:  64000000    et: 211

Size 192 * 10^6 bytes: URIEncoding methods freezes browser at this point.

lovasoa – charCode:            192000000    et: 754
fuweichin – charCode2:         192000000    et: 480
simap – Blob:                  192000000    et: 701
Riccardo Galli – TextEncoder:  192000000    et: 654

Size 640 * 10^6 bytes:

lovasoa – charCode:            640000000    et: 2417
fuweichin – charCode2:         640000000    et: 1602
simap – Blob:                  640000000    et: 2492
Riccardo Galli – TextEncoder:  640000000    et: 2338

Size 1280 * 10^6 bytes: Blob & TextEncoder methods are starting to hit the wall here.

lovasoa – charCode:            1280000000    et: 4780
fuweichin – charCode2:         1280000000    et: 3177
simap – Blob:                  1280000000    et: 6588
Riccardo Galli – TextEncoder:  1280000000    et: 5074

Size 1920 * 10^6 bytes:

lovasoa – charCode:            1920000000    et: 7465
fuweichin – charCode2:         1920000000    et: 4968
JavaScript error: file:///Users/xxx/Desktop/test.html, line 74: NS_ERROR_OUT_OF_MEMORY:

Here is the code:

function byteLengthURIEncoding(str) {
  return encodeURI(str).split(/%..|./).length - 1;
}

function byteLengthCharCode(str) {
  // returns the byte length of an utf8 string
  var s = str.length;
  for (var i=str.length-1; i>=0; i--) {
    var code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s+=2;
    if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
  }
  return s;
}

function byteLengthCharCode2(s){
  //assuming the String is UCS-2(aka UTF-16) encoded
  var n=0;
  for(var i=0,l=s.length; i<l; i++){
    var hi=s.charCodeAt(i);
    if(hi<0x0080){ //[0x0000, 0x007F]
      n+=1;
    }else if(hi<0x0800){ //[0x0080, 0x07FF]
      n+=2;
    }else if(hi<0xD800){ //[0x0800, 0xD7FF]
      n+=3;
    }else if(hi<0xDC00){ //[0xD800, 0xDBFF]
      var lo=s.charCodeAt(++i);
      if(i<l&&lo>=0xDC00&&lo<=0xDFFF){ //followed by [0xDC00, 0xDFFF]
        n+=4;
      }else{
        throw new Error("UCS-2 String malformed");
      }
    }else if(hi<0xE000){ //[0xDC00, 0xDFFF]
      throw new Error("UCS-2 String malformed");
    }else{ //[0xE000, 0xFFFF]
      n+=3;
    }
  }
  return n;
}

function byteLengthBlob(str) {
  return new Blob([str]).size;
}

function byteLengthTE(str) {
  return (new TextEncoder().encode(str)).length;
}

var sample = "œ´®†¥¨ˆøp¬°??©ƒ?ßåO˜çv?˜µ=i";
var string = "";

// Adjust multiplier to change length of string.
let mult = 1000000;

for (var i = 0; i < mult; i++) {
  string += sample;
}

let t0;

try {
  t0 = Date.now();
  console.log("Lauri Oherd – URIEncoding:   " + byteLengthURIEncoding(string) + "    et: " + (Date.now() - t0));
} catch(e) {}

t0 = Date.now();
console.log("lovasoa – charCode:            " + byteLengthCharCode(string) + "    et: " + (Date.now() - t0));

t0 = Date.now();
console.log("fuweichin – charCode2:         " + byteLengthCharCode2(string) + "    et: " + (Date.now() - t0));

t0 = Date.now();
console.log("simap – Blob:                  " + byteLengthBlob(string) + "    et: " + (Date.now() - t0));

t0 = Date.now();
console.log("Riccardo Galli – TextEncoder:  " + byteLengthTE(string) + "    et: " + (Date.now() - t0));

Unique constraint violation during insert: why? (Oracle)

Presumably, since you're not providing a value for the DB_ID column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.

Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID that is currently in the table leading to the error.

You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a

SELECT <<sequence name>>.nextval
  FROM dual

and comparing that to

SELECT MAX(db_id)
  FROM cmdb_db

If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT to something very large, get the nextval once, and set the INCREMENT back to 1.

Bootstrap modal z-index

I fell into this this with using the JQLayout plugin, especially when using nested layouts and modals with Bootstrap 4.

An overriding css needs to be added to correct the behaviour,

.pane-center{
    z-index:inherit !important;
}

jQuery .ready in a dynamically inserted iframe

I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.


var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
    url: url,
    cache: true,
    mimeType: 'application/pdf',
    success: function () {
        // display cached data
        $(scroller).append('<embed type="application/pdf" src="' + url + '" />');
        // hide spinner
        $.mobile.hidePageLoadingMsg();
    }
});

You have to set your http headers correctly as well.


HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";

Play/pause HTML 5 video using JQuery

By JQuery using selectors

$("video_selector").trigger('play');  
$("video_selector").trigger('pause');
$("div.video:first").trigger('play');$("div.video:first").trigger('pause');
$("#video_ID").trigger('play');$("#video_ID").trigger('pause');

By Javascript using ID

video_ID.play();  video_ID.pause();

OR

document.getElementById('video_ID').play();  document.getElementById('video_ID').pause();

How to simulate browsing from various locations?

Sometimes a website doesn't work on my PC and I want to know if it's the website or a problem local to me(e.g. my ISP, my router, etc).

The simplest way to check a website and avoid using your local network resources(and thus avoid any problems caused by them) is using a web proxy such as Proxy.org.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You need the change those double quotation marks into singles. ie. if (answer == 'y') returns true;

Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

Perform Segue programmatically and pass parameters to the destination view

Old question but here's the code on how to do what you are asking. In this case I am passing data from a selected cell in a table view to another view controller.

in the .h file of the trget view:

@property(weak, nonatomic)  NSObject* dataModel;

in the .m file:

@synthesize dataModel;

dataModel can be string, int, or like in this case it's a model that contains many items

- (void)someMethod {
     [self performSegueWithIdentifier:@"loginMainSegue" sender:self];
 }

OR...

- (void)someMethod {
    UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
    [self.navigationController pushViewController: myController animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"storyDetailsSegway"]) {
        UITableViewCell *cell = (UITableViewCell *) sender;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        NSDictionary *storiesDict =[topStories objectAtIndex:[indexPath row]];
        StoryModel *storyModel = [[StoryModel alloc] init];
        storyModel = storiesDict;
        StoryDetails *controller = (StoryDetails *)segue.destinationViewController;
        controller.dataModel= storyModel;
    }
}

How to get the first word in the string

Use this regex

^\w+

\w+ matches 1 to many characters.

\w is similar to [a-zA-Z0-9_]

^ depicts the start of a string


About Your Regex

Your regex (.*)?[ ] should be ^(.*?)[ ] or ^(.*?)(?=[ ]) if you don't want the space

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

How do I convert a javascript object array to a string array of the object attribute I want?

Use the map() function native on JavaScript arrays:

var yourArray = [ {
    'id':1,
    'name':'john'
},{
    'id':2,
    'name':'jane'
}........,{
    'id':2000,
    'name':'zack'
}];

var newArray = yourArray.map( function( el ){ 
                                return el.name; 
                               });

Google maps API V3 - multiple markers on exact same spot

I like simple solutions so here's mine. Instead of modifying the lib, which would make it harder to mantain. you can simply watch the event like this

google.maps.event.addListener(mc, "clusterclick", onClusterClick);

then you can manage it on

function onClusterClick(cluster){
    var ms = cluster.getMarkers();

i, ie, used bootstrap to show a panel with a list. which i find much more confortable and usable than spiderfying on "crowded" places. (if you are using a clusterer chances are you will end up with collisions once you spiderfy). you can check the zoom there too.

btw. i just found leaflet and it seems to work much better, the cluster AND spiderfy works very fluidly http://leaflet.github.io/Leaflet.markercluster/example/marker-clustering-realworld.10000.html and it's open-source.

How do I check if a string contains another string in Objective-C?

An improved version of P i's solution, a category on NSString, that not only will tell, if a string is found within another string, but also takes a range by reference, is:

@interface NSString (Contains)
-(BOOL)containsString: (NSString*)substring
              atRange:(NSRange*)range;

-(BOOL)containsString:(NSString *)substring;
@end

@implementation NSString (Contains)

-(BOOL)containsString:(NSString *)substring
              atRange:(NSRange *)range{

    NSRange r = [self rangeOfString : substring];
    BOOL found = ( r.location != NSNotFound );
    if (range != NULL) *range = r;
    return found;
}

-(BOOL)containsString:(NSString *)substring
{
    return [self containsString:substring
                        atRange:NULL];
}

@end

Use it like:

NSString *string = @"Hello, World!";

//If you only want to ensure a string contains a certain substring
if ([string containsString:@"ello" atRange:NULL]) {
    NSLog(@"YES");
}

// Or simply
if ([string containsString:@"ello"]) {
    NSLog(@"YES");
}

//If you also want to know substring's range
NSRange range;
if ([string containsString:@"ello" atRange:&range]) {
    NSLog(@"%@", NSStringFromRange(range));
}

Converting a column within pandas dataframe from int to string

Just for an additional reference.

All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.

def add_zero_in_prefix(df):
    if(df['Hour']<10):
        return '0' + str(df['Hour'])

data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)

How can I create an Asynchronous function in Javascript?

Next to the great answer by @pimvdb, and just in case you where wondering, async.js does not offer truly asynchronous functions either. Here is a (very) stripped down version of the library's main method:

function asyncify(func) { // signature: func(array)
    return function (array, callback) {
        var result;
        try {
            result = func.apply(this, array);
        } catch (e) {
            return callback(e);
        }
        /* code ommited in case func returns a promise */
        callback(null, result);
    };
}

So the function protects from errors and gracefully hands it to the callback to handle, but the code is as synchronous as any other JS function.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Tensorflow installation error: not a supported wheel on this platform

For Windows 10 64bit:

I have tried all the suggestions here, but finally got it running as follows:

  1. Uninstall all current versions of Python
  2. Remove all Python references in the PATH system and user Environment variables
  3. Download the latest 64bit version of Python 3.8: Python 3.8.7 currently, NOT the latest 3.9.x version which is the one I was using, and NOT 32bit.
  4. Install with all options selected, including pip, and including PATH Environment variable
  5. pip install tensorflow (in Admin CMD prompt)
  6. Upgrade pip if prompted (optional)

How do I work with dynamic multi-dimensional arrays in C?

Basics

Arrays in c are declared and accessed using the [] operator. So that

int ary1[5];

declares an array of 5 integers. Elements are numbered from zero so ary1[0] is the first element, and ary1[4] is the last element. Note1: There is no default initialization, so the memory occupied by the array may initially contain anything. Note2: ary1[5] accesses memory in an undefined state (which may not even be accessible to you), so don't do it!

Multi-dimensional arrays are implemented as an array of arrays (of arrays (of ... ) ). So

float ary2[3][5];

declares an array of 3 one-dimensional arrays of 5 floating point numbers each. Now ary2[0][0] is the first element of the first array, ary2[0][4] is the last element of the first array, and ary2[2][4] is the last element of the last array. The '89 standard requires this data to be contiguous (sec. A8.6.2 on page 216 of my K&R 2nd. ed.) but seems to be agnostic on padding.

Trying to go dynamic in more than one dimension

If you don't know the size of the array at compile time, you'll want to dynamically allocate the array. It is tempting to try

double *buf3;
buf3 = malloc(3*5*sizeof(double));
/* error checking goes here */

which should work if the compiler does not pad the allocation (stick extra space between the one-dimensional arrays). It might be safer to go with:

double *buf4;
buf4 = malloc(sizeof(double[3][5]));
/* error checking */

but either way the trick comes at dereferencing time. You can't write buf[i][j] because buf has the wrong type. Nor can you use

double **hdl4 = (double**)buf;
hdl4[2][3] = 0; /* Wrong! */

because the compiler expects hdl4 to be the address of an address of a double. Nor can you use double incomplete_ary4[][]; because this is an error;

So what can you do?

  • Do the row and column arithmetic yourself
  • Allocate and do the work in a function
  • Use an array of pointers (the mechanism qrdl is talking about)

Do the math yourself

Simply compute memory offset to each element like this:

  for (i=0; i<3; ++i){
     for(j=0; j<3; ++j){
        buf3[i * 5 + j] = someValue(i,j); /* Don't need to worry about 
                                             padding in this case */
     }
  }

Allocate and do the work in a function

Define a function that takes the needed size as an argument and proceed as normal

void dary(int x, int y){
  double ary4[x][y];
  ary4[2][3] = 5;
}

Of course, in this case ary4 is a local variable and you can not return it: all the work with the array must be done in the function you call of in functions that it calls.

An array of pointers

Consider this:

double **hdl5 = malloc(3*sizeof(double*));
/* Error checking */
for (i=0; i<3; ++i){
   hdl5[i] = malloc(5*sizeof(double))
   /* Error checking */
}

Now hdl5 points to an array of pointers each of which points to an array of doubles. The cool bit is that you can use the two-dimensional array notation to access this structure---hdl5[0][2] gets the middle element of the first row---but this is none-the-less a different kind of object than a two-dimensional array declared by double ary[3][5];.

This structure is more flexible then a two dimensional array (because the rows need not be the same length), but accessing it will generally be slower and it requires more memory (you need a place to hold the intermediate pointers).

Note that since I haven't setup any guards you'll have to keep track of the size of all the arrays yourself.

Arithmetic

c provides no support for vector, matrix or tensor math, you'll have to implement it yourself, or bring in a library.

Multiplication by a scaler and addition and subtraction of arrays of the same rank are easy: just loop over the elements and perform the operation as you go. Inner products are similarly straight forward.

Outer products mean more loops.

how to draw directed graphs using networkx in python?

You need to use a directed graph instead of a graph, i.e.

G = nx.DiGraph()

Then, create a list of the edge colors you want to use and pass those to nx.draw (as shown by @Marius).

Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.

enter image description here

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Ignoring NaNs with str.contains

You can also patern :

DF[DF.col.str.contains(pat = '(foo)', regex = True) ]

Trigger function when date is selected with jQuery UI datepicker

Use the following code:

$(document).ready(function() {
    $('.date-pick').datepicker( {
     onSelect: function(date) {
        alert(date)
     },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1,
  });
});

You can adjust the parameters yourself :-)

Java AES and using my own Key

MD5, AES, no padding

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import static org.apache.commons.io.Charsets.UTF_8;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class PasswordUtils {

    private PasswordUtils() {}

    public static String encrypt(String text, String pass) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(ENCRYPT_MODE, key);

            byte[] encrypted = cipher.doFinal(text.getBytes(UTF_8));
            byte[] encoded = Base64.getEncoder().encode(encrypted);
            return new String(encoded, UTF_8);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Cannot encrypt", e);
        }
    }

    public static String decrypt(String text, String pass) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(DECRYPT_MODE, key);

            byte[] decoded = Base64.getDecoder().decode(text.getBytes(UTF_8));
            byte[] decrypted = cipher.doFinal(decoded);
            return new String(decrypted, UTF_8);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Cannot decrypt", e);
        }
    }
}

using awk with column value conditions

Depending on the AWK implementation are you using == is ok or not.

Have you tried ~?. For example, if you want $1 to be "hello":

awk '$1 ~ /^hello$/{ print $3; }' <infile>

^ means $1 start, and $ is $1 end.

Styling HTML email for Gmail

I agree with everyone who supports classes AND inline styles. You might have learned this by now, but if there is a single mistake in your style sheet, Gmail will disregard it.

You might think that your CSS is perfect, because you've done it so often, why would I have mistakes in my CSS? Run it through the CSS Validator (for example http://www.css-validator.org/) and see what happens. I did that after encountering some Gmail display issues, and to my surprise, several Microsoft Outlook specific style declarations showed up as mistakes.

Which made sense to me, so I removed them from the style sheet and put them into a only for Microsoft code block, like so:

<!--[if mso]>
<style type="text/css">
body, table, td, .mobile-text {
font-family: Arial, sans-serif !important;
}
</style>
<xml>
  <o:OfficeDocumentSettings>
    <o:AllowPNG/>
    <o:PixelsPerInch>96</o:PixelsPerInch>
  </o:OfficeDocumentSettings>
</xml>
<![endif]-->

This is just a simple example, but, who know, it might come in handy some time.

Appending to 2D lists in Python

Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.

The easiest way I found to append to a 2D list is like this:

list=[[]]

list.append((var_1,var_2))

This will result in an entry with the 2 variables var_1, var_2. Hope this helps!

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

This was in response to your other question, that looks like it's been deleted....the point still stands.

Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.

.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).

My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:

using System.Text;

string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);

byte[] bAsciiString = encoder.GetBytes(inputString);

// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString); 
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));

Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)

Algorithm to randomly generate an aesthetically-pleasing color palette

An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time.

Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize.

API vs. Webservice

In a generic sense an webservice IS a API over HTTP. They often utilize JSON or XML, but there are some other approaches as well.

img onclick call to JavaScript function

Put the javascript part and the end right before the closing </body> then it should work.

http://jsfiddle.net/Q3Zy3/1/

  <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
  <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>

  <script type="text/javascript">
      function exportToForm(a,b,c,d,e) {
      alert(a + b);
      window.external.values(a.value, b.value, c.value, d.value, e.value);
  }
</script>

How to clear File Input

This works to

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

Setting default values to null fields when mapping with Jackson

There are already a lot of good suggestions, but here's one more. You can use @JsonDeserialize to perform an arbitrary "sanitizer" which Jackson will invoke post-deserialization:

@JsonDeserialize(converter=Message1._Sanitizer.class)  
public class Message1 extends MessageBase
{
    public String string1 = "";
    public int integer1;

    public static class _Sanitizer extends StdConverter<Message1,Message1> {
        @Override
        public Message1 convert(Message1 message) {
            if (message.string1 == null) message.string1 = "";
            return message;
        }
    }
}

What is the difference between a mutable and immutable string in C#?

To clarify there is no such thing as a mutable string in C# (or .NET in general). Other langues support mutable strings (string which can change) but the .NET framework does not.

So the correct answer to your question is ALL string are immutable in C#.

string has a specific meaning. "string" lowercase keyword is merely a shortcut for an object instantiated from System.String class. All objects created from string class are ALWAYS immutable.

If you want a mutable representation of text then you need to use another class like StringBuilder. StringBuilder allows you to iteratively build a collection of 'words' and then convert that to a string (once again immutable).

Best way to overlay an ESRI shapefile on google maps?

2018 already... I've found this fantastic online tool http://mapshaper.org/ to convert from ESRI shapefiles to SVG, TopoJSON, GeoJSON.

Here is the explanation of how to use it https://www.statsilk.com/maps/convert-esri-shapefile-map-geojson-format

Fast and straightforward! :)

mysqldump exports only one table

In case you encounter an error like this

mysqldump: 1044 Access denied when using LOCK TABLES

A quick workaround is to pass the –-single-transaction option to mysqldump.

So your command will be like this.

mysqldump --single-transaction -u user -p DBNAME > backup.sql

Laravel 5.2 not reading env file

I had some problems with this. It seemed to be a file permission issue somewhere in the app - not the .env-file.

I had to - stop my docker - use chown to set owning-rights to my own user for the whole project - start docker again

This time it worked.

How to post JSON to a server using C#?

var data = Encoding.ASCII.GetBytes(json);

byte[] postBytes = Encoding.UTF8.GetBytes(json);

Use ASCII instead of UFT8

How to convert JTextField to String and String to JTextField?

how to convert JTextField to string and string to JTextField in java

If you mean how to get and set String from jTextField then you can use following methods:

String str = jTextField.getText() // get string from jtextfield

and

jTextField.setText(str)  // set string to jtextfield
//or
new JTextField(str)     // set string to jtextfield

You should check JavaDoc for JTextField

How do I pass a command line argument while starting up GDB in Linux?

Another option, once inside the GDB shell, before running the program, you can do

(gdb) set args file1 file2

and inspect it with:

(gdb) show args

How to write a stored procedure using phpmyadmin and how to use it through php?

On local server your following query will work

DELIMITER |

CREATE PROCEDURE sample_sp_with_params (IN empId INT UNSIGNED, OUT oldName VARCHAR(20), INOUT newName VARCHAR(20))

BEGIN

SELECT `first name` into oldName FROM emp where id = empId;

UPDATE emp SET `first name`= newName where id = empId;

END

|

DELIMITER ;

but on production server it might not work. depend on mysql version you are using. I had a same problem on powweb server, i removed delimiter and begin keywords, it works fine. have a look at following query

CREATE PROCEDURE adminsections( IN adminId INT UNSIGNED ) SELECT tbl_adminusersection.ads_name, tbl_adminusersection.ads_controller FROM tbl_adminusersectionright LEFT JOIN tbl_adminusersection ON ( tbl_adminusersectionright.adsr_ads_id = tbl_adminusersection.ads_id ) LEFT JOIN tbl_adminusers ON ( tbl_adminusersectionright.adsr_adusr_id = tbl_adminusers.admusr_id ) WHERE tbl_adminusers.admusr_id = adminId;

Java: Static Class?

Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

My $.02

__init__() got an unexpected keyword argument 'user'

I got the same error.

On my view I was overriding get_form_kwargs() like this:

class UserAccountView(FormView):
    form_class = UserAccountForm
    success_url = '/'
    template_name = 'user_account/user-account.html'

def get_form_kwargs(self):
    kwargs = super(UserAccountView, self).get_form_kwargs()
    kwargs.update({'user': self.request.user})
    return kwargs

But on my form I failed to override the init() method. Once I did it. Problem solved

class UserAccountForm(forms.Form):
    first_name = forms.CharField(label='Your first name', max_length=30)
    last_name = forms.CharField(label='Your last name', max_length=30)
    email = forms.EmailField(max_length=75)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(UserAccountForm, self).__init__(*args, **kwargs)

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

[HttpPost] 
public ActionResult SubmitAction(FormCollection collection)
{
     // Get Post Params Here
 string var1 = collection["var1"];
}

You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:

//Defined in another file
class MyForm
{
  public string var1 { get; set; }
}

[HttpPost]
public ActionResult SubmitAction(MyForm form)
{      
  string var1 = form1.Var1;
}

HTML5 - mp4 video does not play in IE9

From what I've heard, video support is minimal at best.

From http://diveintohtml5.ep.io/video.html#what-works:

As of this writing, this is the landscape of HTML5 video:

  • Mozilla Firefox (3.5 and later) supports Theora video and Vorbis audio in an Ogg container. Firefox 4 also supports WebM.

  • Opera (10.5 and later) supports Theora video and Vorbis audio in an Ogg container. Opera 10.60 also supports WebM.

  • Google Chrome (3.0 and later) supports Theora video and Vorbis audio in an Ogg container. Google Chrome 6.0 also supports WebM.

  • Safari on Macs and Windows PCs (3.0 and later) will support anything that QuickTime supports. In theory, you could require your users to install third-party QuickTime plugins. In practice, few users are going to do that. So you’re left with the formats that QuickTime supports “out of the box.” This is a long list, but it does not include WebM, Theora, Vorbis, or the Ogg container. However, QuickTime does ship with support for H.264 video (main profile) and AAC audio in an MP4 container.

  • Mobile phones like Apple’s iPhone and Google Android phones support H.264 video (baseline profile) and AAC audio (“low complexity” profile) in an MP4 container.

  • Adobe Flash (9.0.60.184 and later) supports H.264 video (all profiles) and AAC audio (all profiles) in an MP4 container.

  • Internet Explorer 9 supports all profiles of H.264 video and either AAC or MP3 audio in an MP4 container. It will also play WebM video if you install a third-party codec, which is not installed by default on any version of Windows. IE9 does not support other third-party codecs (unlike Safari, which will play anything QuickTime can play).

  • Internet Explorer 8 has no HTML5 video support at all, but virtually all Internet Explorer users will have the Adobe Flash plugin. Later in this chapter, I’ll show you how you can use HTML5 video but gracefully fall back to Flash.

As well, you should note this section just below on the same page:

There is no single combination of containers and codecs that works in all HTML5 browsers.

This is not likely to change in the near future.

To make your video watchable across all of these devices and platforms, you’re going to need to encode your video more than once.

Unexpected token ILLEGAL in webkit

I got the same error when the script file I was including container some special characters and when I was running in local moode (directly from local disk). I my case the solution was to explicitly tell the encoding:

<script src="my.js" charset="UTF-8"></script>

How do I cast a JSON Object to a TypeScript class?

In TypeScript you can do a type assertion using an interface and generics like so:

var json = Utilities.JSONLoader.loadFromFile("../docs/location_map.json");
var locations: Array<ILocationMap> = JSON.parse(json).location;

Where ILocationMap describes the shape of your data. The advantage of this method is that your JSON could contain more properties but the shape satisfies the conditions of the interface.

However, this does NOT add class instance methods.

How to remove focus around buttons on click

.btn:focus:active {
  outline: none;
}

this removes the outline on click, but keeps the focus when tabbing (for a11y)

How to display an error message in an ASP.NET Web Application

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}

Creating a Zoom Effect on an image on hover using CSS?

_x000D_
_x000D_
@import url('https://fonts.googleapis.com/css?family=Muli:200,300,400,700&subset=latin-ext');_x000D_
 body{ font-family: 'Muli', sans-serif; color:white;}_x000D_
 #lists {_x000D_
   width: 350px;_x000D_
   height: 460px;_x000D_
   overflow: hidden;_x000D_
   background-color:#222222;_x000D_
   padding:0px;_x000D_
   float:left;_x000D_
    margin: 10px;_x000D_
 }_x000D_
 _x000D_
 .listimg {_x000D_
   width: 100%;_x000D_
   height: 220px;_x000D_
   overflow: hidden;_x000D_
   float: left;_x000D_
  _x000D_
 }_x000D_
  #lists .listimg img {_x000D_
   width: 350px;_x000D_
   height: 220px;_x000D_
   -moz-transition: all 0.3s;_x000D_
   -webkit-transition: all 0.3s;_x000D_
   transition: all 0.3s;_x000D_
 }_x000D_
 #lists:hover{cursor: pointer;}_x000D_
 #lists:hover > .listimg img {_x000D_
   -moz-transform: scale(1.3);_x000D_
   -webkit-transform: scale(1.3);_x000D_
   transform: scale(1.3);_x000D_
   -webkit-filter: blur(5px);_x000D_
   filter: blur(5px);_x000D_
 }_x000D_
_x000D_
#lists h1{margin:20px; display:inline-block; margin-bottom:0px; }_x000D_
#lists p{margin:20px;}_x000D_
_x000D_
.listdetail{ text-align:right; font-weight:200; padding-top:6px;padding-bottom:6px;}
_x000D_
<div id="lists">_x000D_
<div class="listimg">_x000D_
  <img src="https://lh3.googleusercontent.com/WeEw5I-wk2UO-y0u3Wsv8MxprCJjxTyTzvwdEc9pcdTsZVj_yK5thdtXNDKoZcUOHlegFhx7=w1920-h914-rw">_x000D_
</div>_x000D_
<div class="listtext">_x000D_
<h1>Eyes Lorem Impsum Samet</h1>_x000D_
<p>Impsum Samet Lorem</p>_x000D_
</div>_x000D_
<div class="listdetail">_x000D_
<p>Click for More Details...</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div id="lists">_x000D_
<div class="listimg">_x000D_
  <img src="https://lh4.googleusercontent.com/fqK7aQ7auobK_NyXRYCsL9SOpVj6SoYqVlgbOENw6IqQvEWzym_3988798NlkGDzu0MWnR-7nxIhj7g=w1920-h870-rw">_x000D_
</div>_x000D_
<div class="listtext">_x000D_
<h1>Two Frogs Lorem Impsum Samet</h1>_x000D_
<p>Impsum Samet Lorem</p>_x000D_
</div>_x000D_
<div class="listdetail">_x000D_
<p>More Details...</p>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting string to number in javascript/jQuery

You can adding a + before the string without using parseInt and parseFloat and radix, Simply

sample:

var votevalue = +$('button').data('votevalue');

alert(typeof(votevalue));

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

Extract a substring from a string in Ruby using a regular expression

A simpler scan would be:

String1.scan(/<(\S+)>/).last

How to specify an element after which to wrap in css flexbox?

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

Here's an article with your full list of options: https://tobiasahlin.com/blog/flexbox-break-to-new-row/

EDIT: This is really easy to do with Grid now: https://codepen.io/anon/pen/mGONxv?editors=1100

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

I don't think you can break after a specific item. The best you can probably do is change the flex-basis at your breakpoints. So:

ul {
  flex-flow: row wrap;
  display: flex;
}

li {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 50%;
}

@media (min-width: 40em;){
li {
  flex-basis: 30%;
}

Here's a sample: http://cdpn.io/ndCzD

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

EDIT: You CAN break after a specific element! Heydon Pickering unleashed some css wizardry in an A List Apart article: http://alistapart.com/article/quantity-queries-for-css

EDIT 2: Please have a look at this answer: Line break in multi-line flexbox

@luksak also provides a great answer

Recursively find files with a specific extension

find -name "*Robert*" \( -name "*.pdf" -o -name "*.jpg" \)

The -o repreents an OR condition and you can add as many as you wish within the braces. So this says to find all files containing the word "Robert" anywhere in their names and whose names end in either "pdf" or "jpg".

DB2 Query to retrieve all table names for a given schema

select name from sysibm.systables 
where name like '%ISP%' 
and type = 'T'

Alternative for frames in html5 using iframes

HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".

http://www.w3schools.com/html5/tag_iframe.asp

or you can use

<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>

log4net vs. Nlog

Based on my experience, SmartInspect beats both NLog and log4net.

Its extremely easy to use, documentation is great, and you can view and filter previously logged messages with their interactive log viewer, which is a huge real world advantage.

One thing I like is the tabbed views of data, like the browser tabs in Chrome. Each tab can provide a different filtered view of the log.

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

How to create a CPU spike with a bash command

To enhance dimba's answer and provide something more pluggable (because i needed something similar). I have written the following using the dd load-up concept :D

It will check current cores, and create that many dd threads. Start and End core load with Enter

#!/bin/bash

load_dd() {
    dd if=/dev/zero of=/dev/null
}

fulload() {
    unset LOAD_ME_UP_SCOTTY
    export cores="$(grep proc /proc/cpuinfo -c)"
    for i in $( seq 1 $( expr $cores - 1 ) )
      do
    export LOAD_ME_UP_SCOTTY="${LOAD_ME_UP_SCOTTY}$(echo 'load_dd | ')"
  done
        export LOAD_ME_UP_SCOTTY="${LOAD_ME_UP_SCOTTY}$(echo 'load_dd &')"
    eval ${LOAD_ME_UP_SCOTTY}
}

echo press return to begin and stop fullload of cores
  read
  fulload
  read
  killall -9 dd

Strangest language feature

In c++

const char* wtf()
{
    char buf[100];
    return buf;
}
string s = ... + wtf() + ...;

creates interesting values in s. Partly string, partly stack contents, mixed with zeroes so that s.length()!=strlen(s.c_str()). The strangest thing is that compiler has absolutely no problems with returning pointers to stack - compiler programmers's hand would probably fall off if he would have added a warning there.

.NET HttpClient. How to POST string value?

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

Using Excel as front end to Access database (with VBA)

If the end user has Access, it might be easier to develop the whole thing in Access. Access has some WYSIWYG form design tools built-in.

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

Printing pointers in C

"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".

When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";

char s[] = "asd";
char *p = &s[0];  // alternately you could use the shorthand char*p = s;
char **pp = &p;

Opening Chrome From Command Line

Let's take a look at the start command.

Open Windows command prompt

To open a new Chrome window (blank), type the following:

start chrome --new-window 

or

start chrome

To open a URL in Chrome, type the following:

start chrome --new-window "http://www.iot.qa/2018/02/narrowband-iot.html"

To open a URL in Chrome in incognito mode, type the following:

start chrome --new-window --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"

or

start chrome --incognito "http://www.iot.qa/2018/02/narrowband-iot.html"

Get the Query Executed in Laravel 3/4

In Laravel 8.x you can listen to the event by registering your query listener in a service provider as documented in laravel.com website.

//header
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot()
{
   
  DB::listen(function ($query) {            
   Log::debug("SQL : " . $query->sql);
  });

}

You can then see all the queries in the laravel.log file inside storage\logs\laravel.log

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

try these

sudo chown -R $(whoami) ~/.npm

sudo chown -R $(whoami) /usr/local/lib

sudo chown -R $(whoami) /usr/local/bin

Then try your command again without sudo. e.g.

npm install -g npm@latest

Check this link for more details

Renaming files using node.js

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');

First letter capitalization for EditText

Earlier it used to be android:capitalize="words", which is now deprecated. The recommended alternative is to use android:inputType="textCapWords"

Please note that this will only work if your device keyboard Auto Capitalize Setting enabled.

To do this programatically, use the following method:

setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);

How to delete node from XML file using C#

Deleting nodes from XML

            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
            for (int i = nodes.Count - 1; i >= 0; i--)
            {
                nodes[i].ParentNode.RemoveChild(nodes[i]);
            }
            doc.Save(path);

Adding attribute to Nodes in XML

    XmlDocument originalXml = new XmlDocument();
    originalXml.Load(path);
    XmlNode menu = originalXml.SelectSingleNode("//Settings");
    XmlNode newSub = originalXml.CreateNode(XmlNodeType.Element, "Setting", null);
    XmlAttribute xa = originalXml.CreateAttribute("name");
    xa.Value = "qwerty";
    XmlAttribute xb = originalXml.CreateAttribute("value");
    xb.Value = "555";
    newSub.Attributes.Append(xa);
    newSub.Attributes.Append(xb);
    menu.AppendChild(newSub);
    originalXml.Save(path);

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

  1. Due to optimization, it is very easy to compare given integers just with min and max range.
  2. The reason that range() function is so fast in Python3 is that here we use mathematical reasoning for the bounds, rather than a direct iteration of the range object.
  3. So for explaining the logic here:
    • Check whether the number is between the start and stop.
    • Check whether the step precision value doesn't go over our number.
  4. Take an example, 997 is in range(4, 1000, 3) because:

    4 <= 997 < 1000, and (997 - 4) % 3 == 0.

How to trap on UIViewAlertForUnsatisfiableConstraints?

This post helped me A LOT!

I added UIViewAlertForUnsatisfiableConstraints symbolic breakpoint with suggested action:

Obj-C project

po [[UIWindow keyWindow] _autolayoutTrace]

Symbolic breakpoint with custom action in Objective-C project

Swift project

expr -l objc++ -O -- [[UIWindow keyWindow] _autolayoutTrace]

Symbolic breakpoint with custom action

With this hint, the log became more detailed, and It was easier for me identify which view had the constraint broken.

UIWindow:0x7f88a8e4a4a0
|   UILayoutContainerView:0x7f88a8f23b70
|   |   UINavigationTransitionView:0x7f88a8ca1970
|   |   |   UIViewControllerWrapperView:0x7f88a8f2aab0
|   |   |   |   •UIView:0x7f88a8ca2880
|   |   |   |   |   *UIView:0x7f88a8ca2a10
|   |   |   |   |   |   *UIButton:0x7f88a8c98820'Archived'
|   |   |   |   |   |   |   UIButtonLabel:0x7f88a8cb0e30'Archived'
|   |   |   |   |   |   *UIButton:0x7f88a8ca22d0'Download'
|   |   |   |   |   |   |   UIButtonLabel:0x7f88a8cb04e0'Download'
|   |   |   |   |   |   *UIButton:0x7f88a8ca1580'Deleted'
|   |   |   |   |   |   |   UIButtonLabel:0x7f88a8caf100'Deleted'
|   |   |   |   |   *UIView:0x7f88a8ca33e0
|   |   |   |   |   *_UILayoutGuide:0x7f88a8ca35b0
|   |   |   |   |   *_UILayoutGuide:0x7f88a8ca4090
|   |   |   |   |   _UIPageViewControllerContentView:0x7f88a8f1a390
|   |   |   |   |   |   _UIQueuingScrollView:0x7f88aa031c00
|   |   |   |   |   |   |   UIView:0x7f88a8f38070
|   |   |   |   |   |   |   UIView:0x7f88a8f381e0
|   |   |   |   |   |   |   |   •UIView:0x7f88a8f39fa0, MISSING HOST CONSTRAINTS
|   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8cb9bf0'Retrieve data'- AMBIGUOUS LAYOUT for UIButton:0x7f88a8cb9bf0'Retrieve data'.minX{id: 170}, UIButton:0x7f88a8cb9bf0'Retrieve data'.minY{id: 171}
|   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8f3ad80- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8f3ad80.minX{id: 172}, UIImageView:0x7f88a8f3ad80.minY{id: 173}
|   |   |   |   |   |   |   |   |   *App.RecordInfoView:0x7f88a8cbe530- AMBIGUOUS LAYOUT for App.RecordInfoView:0x7f88a8cbe530.minX{id: 174}, App.RecordInfoView:0x7f88a8cbe530.minY{id: 175}, App.RecordInfoView:0x7f88a8cbe530.Width{id: 176}, App.RecordInfoView:0x7f88a8cbe530.Height{id: 177}
|   |   |   |   |   |   |   |   |   |   +UIView:0x7f88a8cc1d30- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1d30.minX{id: 178}, UIView:0x7f88a8cc1d30.minY{id: 179}, UIView:0x7f88a8cc1d30.Width{id: 180}, UIView:0x7f88a8cc1d30.Height{id: 181}
|   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8cc1ec0- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1ec0.minX{id: 153}, UIView:0x7f88a8cc1ec0.minY{id: 151}, UIView:0x7f88a8cc1ec0.Width{id: 154}, UIView:0x7f88a8cc1ec0.Height{id: 165}
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e68e10- AMBIGUOUS LAYOUT for UIView:0x7f88a8e68e10.minX{id: 155}, UIView:0x7f88a8e68e10.minY{id: 150}, UIView:0x7f88a8e68e10.Width{id: 156}
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e65de0- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e65de0.minX{id: 159}, UIImageView:0x7f88a8e65de0.minY{id: 182}
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8e69080'8-6-2015'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8e69080'8-6-2015'.minX{id: 183}, UILabel:0x7f88a8e69080'8-6-2015'.minY{id: 184}, UILabel:0x7f88a8e69080'8-6-2015'.Width{id: 185}
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0690'16:34'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8cc0690'16:34'.minX{id: 186}, UILabel:0x7f88a8cc0690'16:34'.minY{id: 187}, UILabel:0x7f88a8cc0690'16:34'.Width{id: 188}, UILabel:0x7f88a8cc0690'16:34'.Height{id: 189}
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8cc2050- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc2050.minX{id: 161}, UIView:0x7f88a8cc2050.minY{id: 166}, UIView:0x7f88a8cc2050.Width{id: 163}
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e69d90- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e69d90.minX{id: 190}, UIImageView:0x7f88a8e69d90.minY{id: 191}, UIImageView:0x7f88a8e69d90.Width{id: 192}, UIImageView:0x7f88a8e69d90.Height{id: 193}
|   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3cc00
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e618d0
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e5ba10
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3cd70
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e58e10
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e5e7a0
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3cee0
|   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3dc70
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e64dd0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8e65290'Average flow rate'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8e712d0'177.0 ml/s'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8c97150'1299.4'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3dde0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3df50'Maximum flow rate'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cbfdb0'371.6 ml/s'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0230'873.5'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3e2a0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3e410'Total volume'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0f20'371.6 ml'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3e870
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3ea00'Time do max. flow'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0ac0'3.6 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3ee10
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3efa0'Flow time'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cbf980'2.1 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3f3e0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3f570'Voiding time'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc17e0'3.5 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3f9a0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3fb30'Voiding delay'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc1380'1.0 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e65000
|   |   |   |   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8e52f20'Show'
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e6e1d0
|   |   |   |   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8e52c90'Send'
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e61bb0
|   |   |   |   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8e528e0'Delete'
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e6b3f0
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3ff60
|   |   |   |   |   |   |   |   |   *UIActivityIndicatorView:0x7f88a8cba080
|   |   |   |   |   |   |   |   |   |   UIImageView:0x7f88a8cba700
|   |   |   |   |   |   |   |   |   *_UILayoutGuide:0x7f88a8cc3150
|   |   |   |   |   |   |   |   |   *_UILayoutGuide:0x7f88a8cc3b10
|   |   |   |   |   |   |   UIView:0x7f88a8f339c0
|   |   UINavigationBar:0x7f88a8c96810
|   |   |   _UINavigationBarBackground:0x7f88a8e45c00
|   |   |   |   UIImageView:0x7f88a8e46410
|   |   |   UINavigationItemView:0x7f88a8c97520'App'
|   |   |   |   UILabel:0x7f88a8c97cc0'App'
|   |   |   UINavigationButton:0x7f88a8e3e850
|   |   |   |   UIImageView:0x7f88a8e445b0
|   |   |   _UINavigationBarBackIndicatorView:0x7f88a8f2b530

Legend:
    * - is laid out with auto layout
    + - is laid out manually, but is represented in the layout engine because translatesAutoresizingMaskIntoConstraints = YES
    • - layout engine host

Then I paused execution Pause and I changed problematic view's background color with the command (replacing 0x7f88a8cc2050 with the memory address of your object of course)...

Obj-C

expr ((UIView *)0x7f88a8cc2050).backgroundColor = [UIColor redColor]

Swift 3.0

expr -l Swift -- import UIKit
expr -l Swift -- unsafeBitCast(0x7f88a8cc2050, to: UIView.self).backgroundColor = UIColor.red

... and the result It was awesome!

Hinted View

Simply amazing! Hope It helps.

CodeIgniter: How to use WHERE clause and OR clause

What worked for me :

  $where = '';
   /* $this->db->like('ust.title',$query_data['search'])
        ->or_like('usr.f_name',$query_data['search'])
        ->or_like('usr.l_name',$query_data['search']);*/
        $where .= "(ust.title like '%".$query_data['search']."%'";
        $where .= " or usr.f_name like '%".$query_data['search']."%'";
        $where .= "or usr.l_name like '%".$query_data['search']."%')";
        $this->db->where($where);



$datas = $this->db->join(TBL_USERS.' AS usr','ust.user_id=usr.id')
            ->where_in('ust.id', $blog_list) 
            ->select('ust.*,usr.f_name as f_name,usr.email as email,usr.avatar as avatar, usr.sex as sex')
            ->get_where(TBL_GURU_BLOG.' AS ust',[
                'ust.deleted_at'     =>  NULL,
                'ust.status'     =>  1,
            ]); 

I have to do this to create a query like this :

SELECT `ust`.*, `usr`.`f_name` as `f_name`, `usr`.`email` as `email`, `usr`.`avatar` as `avatar`, `usr`.`sex` as `sex` FROM `blog` AS `ust` JOIN `users` AS `usr` ON `ust`.`user_id`=`usr`.`id` WHERE (`ust`.`title` LIKE '%mer%' ESCAPE '!' OR  `usr`.`f_name` LIKE '%lok%' ESCAPE '!' OR  `usr`.`l_name` LIKE '%mer%' ESCAPE '!') AND `ust`.`id` IN('36', '37', '38') AND `ust`.`deleted_at` IS NULL AND `ust`.`status` = 1 ;

How do you decrease navbar height in Bootstrap 3?

In Bootstrap 4

In my case I have just changed the .navbar min-height and the links font-size and it decreased the navbar.

For example:

.navbar{
    min-height:12px;
}
.navbar  a {
    font-size: 11.2px;
}

And this also worked for increasing the navbar height.

This also helps to change the navbar size when scrolling down the browser.

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

Enable gzip compression in php.ini:

zlib.output_compression = On

And add this to your .htaccess file:

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

How do I correctly detect orientation change using Phonegap on iOS?

I use window.onresize = function(){ checkOrientation(); } And in checkOrientation you can employ window.orientation or body width checking but the idea is, the "window.onresize" is the most cross browser method, at least with the majority of the mobile and desktop browsers that I've had an opportunity to test with.

Difference between links and depends_on in docker_compose.yml

This answer is for docker-compose version 2 and it also works on version 3

You can still access the data when you use depends_on.

If you look at docker docs Docker Compose and Django, you still can access the database like this:

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

What is the difference between links and depends_on?

links:

When you create a container for a database, for example:

docker run -d --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" -P mysql

docker inspect d54cf8a0fb98 |grep HostPort

And you may find

"HostPort": "32777"

This means you can connect the database from your localhost port 32777 (3306 in container) but this port will change every time you restart or remove the container. So you can use links to make sure you will always connect to the database and don't have to know which port it is.

web:
  links:
   - db

depends_on:

I found a nice blog from Giorgio Ferraris Docker-compose.yml: from V1 to V2

When docker-compose executes V2 files, it will automatically build a network between all of the containers defined in the file, and every container will be immediately able to refer to the others just using the names defined in the docker-compose.yml file.

And

So we don’t need links anymore; links were used to start a network communication between our db container and our web-server container, but this is already done by docker-compose

Update

depends_on

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

Simple example:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

Note: depends_on will not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

getMinutes() 0-9 - How to display two digit numbers?

Yikes these answers aren't great, even the top post upticked. Here y'go, cross-browser and cleaner int/string conversion. Plus my advice is don't use a variable name 'date' with code like date = Date(...) where you're relying heavily on language case sensitivity (it works, but risky when you're working with server/browser code in different languages with different rules). So assuming the javascript Date in a var current_date:

mins = ('0'+current_date.getMinutes()).slice(-2);

The technique is take the rightmost 2 characters (slice(-2)) of "0" prepended onto the string value of getMinutes(). So:

"0"+"12" -> "012".slice(-2) -> "12"

and

"0"+"1" -> "01".slice(-2) -> "01"

Multiple values in single-value context

No, but that is a good thing since you should always handle your errors.

There are techniques that you can employ to defer error handling, see Errors are values by Rob Pike.

ew := &errWriter{w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
    return ew.err
}

In this example from the blog post he illustrates how you could create an errWriter type that defers error handling till you are done calling write.

Git: How to squash all commits on branch

Since I had some trouble with the solutions proposed here, I want to share a really simple solution (which really works regardless):

git merge origin/master && git reset --soft origin/master

The preceding merge cmd ensures, that no recent changes from master will go on your head (inverted) when committing! After that, just commit the changes and do git push -f

How to make my font bold using css?

You can use the CSS declaration font-weight: bold;.

I would advise you to read the CSS beginner guide at http://htmldog.com/guides/cssbeginner/ .

how do I create an array in jquery?

You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.

array('Item 1', 'Item 2', 'Items 3')  // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2')  // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')

Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:

['Item 1', 'Item 2', 'Item 3']  // array (numerically indexed)

An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:

{ first : 'Item 1', second : 'Item 2' }  // object (a.k.a. "associative array")

They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.


* Technically everything is an Object in Javascript, please put that aside for this argument. ;)

Header and footer in CodeIgniter

Try following

Folder structure

-application
 --controller
   ---dashboards.php
 --views
   ---layouts
      ----application.php
   ---dashboards
      ----index.php

Controller

class Dashboards extends CI_Controller
{

   public function __construct()
   {
     parent::__construct();
     $data                = array();
     $data['js']          = 'dashboards.js'
     $data['css']         = 'dashbaord.css'
   }

   public function index()
   { 
     $data                = array();
     $data['yield']       = 'dashboards/index';

     $this->load->view('layouts/application', $data);
   }
}

View

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" />
      <title>Some Title</title>
      <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/app.css" />
      <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/<?php echo $css; ?>" />
   </head>
   <body>
     <header></header>
     <section id="container" role="main">
     <?php $this->load->view($yield); ?>
     </section>
     <footer></footer>
     <script src="<php echo base_url(); ?>assets/js/app.js"></script>
     <script src="<php echo base_url(); ?>assets/js/<?php echo $js; ?>"></script>
  </body>
</html>

When you need to load different js, css or whatever in the header or footer use the __construct function to $this->load->vars

Kind of a rails like approach here

Decoding a Base64 string in Java

Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):

byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

C# DLL config file

I've found what seems like a good solution to this issue. I am using VS 2008 C#. My solution involves the use of distinct namespaces between multiple configuration files. I've posted the solution on my blog: http://tommiecarter.blogspot.com/2011/02/how-to-access-multiple-config-files-in.html.

For example:

This namespace read/writes dll settings:

var x = company.dlllibrary.Properties.Settings.Default.SettingName;
company.dlllibrary.Properties.Settings.Default.SettingName = value;

This namespace read/writes the exe settings:

company.exeservice.Properties.Settings.Default.SettingName = value;
var x = company.exeservice.Properties.Settings.Default.SettingName;

There are some caveats mentioned in the article. HTH

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained here:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

How to concatenate two strings to build a complete path

The POSIX standard mandates that multiple / are treated as a single / in a file name. Thus //dir///subdir////file is the same as /dir/subdir/file.

As such concatenating a two strings to build a complete path is a simple as:

full_path="$part1/$part2"

Java Command line arguments

As everyone else has said... the .equals method is what you need.

In the off chance you used something like:

if(argv[0] == "a")

then it does not work because == compares the location of the two objects (physical equality) rather than the contents (logical equality).

Since "a" from the command line and "a" in the source for your program are allocated in two different places the == cannot be used. You have to use the equals method which will check to see that both strings have the same characters.

Another note... "a" == "a" will work in many cases, because Strings are special in Java, but 99.99999999999999% of the time you want to use .equals.

Increment value in mysql update query

Why don't you let PHP do the job?

"UPDATE member_profile SET points= ' ". ($points+1) ." '  WHERE user_id = '".$userid."'"

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

How to ignore user's time zone and force Date() use specific time zone

Use this and always use UTC functions afterwards e.g. mydate.getUTCHours();

_x000D_
_x000D_
   function getDateUTC(str) {
        function getUTCDate(myDateStr){
            if(myDateStr.length <= 10){
                //const date = new Date(myDateStr); //is already assuming UTC, smart - but for browser compatibility we will add time string none the less
                const date = new Date(myDateStr.trim() + 'T00:00:00Z');
                return date;
            }else{
                throw "only date strings, not date time";
            }
        }

        function getUTCDatetime(myDateStr){
            if(myDateStr.length <= 10){
                throw "only date TIME strings, not date only";
            }else{
                return new Date(myDateStr.trim() +'Z'); //this assumes no time zone is part of the date string. Z indicates UTC time zone
            }
        }  
        
        let rv = '';
        
        if(str && str.length){
            if(str.length <= 10){
                rv = getUTCDate(str);
            }else if(str.length > 10){
                rv = getUTCDatetime(str);
            } 
        }else{
            rv = '';
        }
        return rv;
    }

console.info(getDateUTC('2020-02-02').toUTCString());

var mydateee2 = getDateUTC('2020-02-02 02:02:02');
console.info(mydateee2.toUTCString());

// you are free to use all UTC functions on date e.g.
console.info(mydateee2.getUTCHours())
console.info('all is good now if you use UTC functions')
_x000D_
_x000D_
_x000D_

A simple scenario using wait() and notify() in java

Have you taken a look at this Java Tutorial?

Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.

That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.

When to use std::size_t?

When using size_t be careful with the following expression

size_t i = containner.find("mytoken");
size_t x = 99;
if (i-x>-1 && i+x < containner.size()) {
    cout << containner[i-x] << " " << containner[i+x] << endl;
}

You will get false in the if expression regardless of what value you have for x. It took me several days to realize this (the code is so simple that I did not do unit test), although it only take a few minutes to figure the source of the problem. Not sure it is better to do a cast or use zero.

if ((int)(i-x) > -1 or (i-x) >= 0)

Both ways should work. Here is my test run

size_t i = 5;
cerr << "i-7=" << i-7 << " (int)(i-7)=" << (int)(i-7) << endl;

The output: i-7=18446744073709551614 (int)(i-7)=-2

I would like other's comments.

Adding +1 to a variable inside a function

points is not within the function's scope. You can grab a reference to the variable by using nonlocal:

points = 0
def test():
    nonlocal points
    points += 1

If points inside test() should refer to the outermost (module) scope, use global:

points = 0
def test():
    global points
    points += 1

c# foreach (property in object)... Is there a simple way of doing this?

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

Call method when home button pressed

I found that when I press the button HOME the onStop() method is called.You can use the following piece of code to monitor it:

@Override
    protected void onStop() 
    {
        super.onStop();
        Log.d(tag, "MYonStop is called");
        // insert here your instructions
    }

Why doesn't logcat show anything in my Android?

I had faced the same issue but in my case logs are shown when other devices are connected and not shown when my device is connected.

It took me days and finally, the issue resolved when I restarted my phone.

Difference between window.location.href, window.location.replace and window.location.assign

The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.

(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)

If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

css3 transition animation on load?

Similar to @Rolf's solution, but skip reference to external functions or playing with class. If opacity is to remain fixed to 1 once loaded, simply use inline script to directly change opacity via style. For example

<body class="fadein" onload="this.style.opacity=1">

where CSS sytle "fadein" is defined per @Rolf,defining transition and setting opacity to initial state (i.e. 0)

the only catch is that this does not work with SPAN or DIV elements, since they do not have working onload event

Visualizing decision tree in scikit-learn

Alternatively, you could try using pydot for producing the png file from dot:

...
tree.export_graphviz(dtreg, out_file='tree.dot') #produces dot file

import pydot
dotfile = StringIO()
tree.export_graphviz(dtreg, out_file=dotfile)
pydot.graph_from_dot_data(dotfile.getvalue()).write_png("dtree2.png")
...

Get second child using jQuery

Use .find() method

$(t).find("td:eq(1)");

td:eq(x) // x is index of child you want to retrieve. eq(1) means equal to 1. //1 denote second element

How to pause javascript code execution for 2 seconds

Javascript is single-threaded, so by nature there should not be a sleep function because sleeping will block the thread. setTimeout is a way to get around this by posting an event to the queue to be executed later without blocking the thread. But if you want a true sleep function, you can write something like this:

function sleep(miliseconds) {
   var currentTime = new Date().getTime();

   while (currentTime + miliseconds >= new Date().getTime()) {
   }
}

Note: The above code is NOT recommended.

Check if a value is within a range of numbers

I like Pointy's between function so I wrote a similar one that worked well for my scenario.

/**
 * Checks if an integer is within ±x another integer.
 * @param {int} op - The integer in question
 * @param {int} target - The integer to compare to
 * @param {int} range - the range ±
 */
function nearInt(op, target, range) {
    return op < target + range && op > target - range;
}

so if you wanted to see if x was within ±10 of y:

var x = 100;
var y = 115;
nearInt(x,y,10) = false

I'm using it for detecting a long-press on mobile:

//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);

Configure Flask dev server to be visible across the network

go to project path set FLASK_APP=ABC.py SET FLASK_ENV=development

flask run -h [yourIP] -p 8080 you will following o/p on CMD:- * Serving Flask app "expirement.py" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 199-519-700 * Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);
        }
    });

    mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}

How to count number of files in each directory?

I combined @glenn jackman's answer and @pcarvalho's answer(in comment list, there is something wrong with pcarvalho's answer because the extra style control function of character '`'(backtick)).

My script can accept path as an augument and sort the directory list as ls -l, also it can handles the problem of "space in file name".

#!/bin/bash
OLD_IFS="$IFS"
IFS=$'\n'
for dir in $(find $1 -maxdepth 1 -type d | sort); 
do
    files=("$dir"/*)
    printf "%5d,%s\n" "${#files[@]}" "$dir"
done
FS="$OLD_IFS"

My first answer in stackoverflow, and I hope it can help someone ^_^

How to find and return a duplicate value in array

Alas most of the answers are O(n^2).

Here is an O(n) solution,

a = %w{the quick brown fox jumps over the lazy dog}
h = Hash.new(0)
a.find { |each| (h[each] += 1) == 2 } # => 'the"

What is the complexity of this?

  • Runs in O(n) and breaks on first match
  • Uses O(n) memory, but only the minimal amount

Now, depending on how frequent duplicates are in your array these runtimes might actually become even better. For example if the array of size O(n) has been sampled from a population of k << n different elements only the complexity for both runtime and space becomes O(k), however it is more likely that the original poster is validating input and wants to make sure there are no duplicates. In that case both runtime and memory complexity O(n) since we expect the elements to have no repetitions for the majority of inputs.

Find objects between two dates MongoDB

Why not convert the string to an integer of the form YYYYMMDDHHMMSS? Each increment of time would then create a larger integer, and you can filter on the integers instead of worrying about converting to ISO time.

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

It's really surprising to me that the redirection methods in ProcessBuilder don't accept an OutputStream, only File. Yet another proof of forced boilerplate code that Java forces you to write.

That said, let's look at a list of comprehensive options:

  1. If you want the process output to simply be redirected to its parent's output stream, inheritIO will do the job.
  2. If you want the process output to go to a file, use redirect*(file).
  3. If you want the process output to go to a logger, you need to consume the process InputStream in a separate thread. See the answers that use a Runnable or CompletableFuture. You can also adapt the code below to do this.
  4. If you want to the process output to go to a PrintWriter, that may or may not be the stdout (very useful for testing), you can do the following:
static int execute(List<String> args, PrintWriter out) {
    ProcessBuilder builder = new ProcessBuilder()
            .command(args)
            .redirectErrorStream(true);
    Process process = null;
    boolean complete = false;
    try {
        process = builder.start();
        redirectOut(process.getInputStream(), out)
                .orTimeout(TIMEOUT, TimeUnit.SECONDS);
        complete = process.waitFor(TIMEOUT, TimeUnit.SECONDS);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (InterruptedException e) {
        LOG.warn("Thread was interrupted", e);
    } finally {
        if (process != null && !complete) {
            LOG.warn("Process {} didn't finish within {} seconds", args.get(0), TIMEOUT);
            process = process.destroyForcibly();
        }
    }

    return process != null ? process.exitValue() : 1;
}

private static CompletableFuture<Void> redirectOut(InputStream in, PrintWriter out) {
    return CompletableFuture.runAsync(() -> {
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(in);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
        ) {
            bufferedReader.lines()
                    .forEach(out::println);
        } catch (IOException e) {
            LOG.error("Failed to redirect process output", e);
        }
    });
}

Advantages of the code above over the other answers thus far:

  1. redirectErrorStream(true) redirects the error stream to the output stream, so that we only have to bother with one.
  2. CompletableFuture.runAsync runs from the ForkJoinPool. Note that this code doesn't block by calling get or join on the CompletableFuture but sets a timeout instead on its completion (Java 9+). There's no need for CompletableFuture.supplyAsync because there's nothing really to return from the method redirectOut.
  3. BufferedReader.lines is simpler than using a while loop.

In Python, what is the difference between ".append()" and "+= []"?

+= is an assignment. When you use it you're really saying ‘some_list2= some_list2+['something']’. Assignments involve rebinding, so:

l= []

def a1(x):
    l.append(x) # works

def a2(x):
    l= l+[x] # assign to l, makes l local
             # so attempt to read l for addition gives UnboundLocalError

def a3(x):
    l+= [x]  # fails for the same reason

The += operator should also normally create a new list object like list+list normally does:

>>> l1= []
>>> l2= l1

>>> l1.append('x')
>>> l1 is l2
True

>>> l1= l1+['x']
>>> l1 is l2
False

However in reality:

>>> l2= l1
>>> l1+= ['x']
>>> l1 is l2
True

This is because Python lists implement __iadd__() to make a += augmented assignment short-circuit and call list.extend() instead. (It's a bit of a strange wart this: it usually does what you meant, but for confusing reasons.)

In general, if you're appending/extended an existing list, and you want to keep the reference to the same list (instead of making a new one), it's best to be explicit and stick with the append()/extend() methods.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

This answer may not apply universally, but it fixed the occurrence of this error I was encountering when importing a small text file. The flat file provider was importing based on fixed 50-character text columns in the source, which was incorrect. No amount of remapping the destination columns affected the issue.

To solve the issue, in the "Choose a Data Source" for the flat-file provider, after selecting the file, a "Suggest Types.." button appears beneath the input column list. After hitting this button, even if no changes were made to the enusing dialog, the Flat File provider then re-queried the source .csv file and then correctly determined the lengths of the fields in the source file.

Once this was done, the import proceeded with no further issues.

React: why child component doesn't update when prop changes

You should probably make the Child as functional component if it does not maintain any state and simply renders the props and then call it from the parent. Alternative to this is that you can use hooks with the functional component (useState) which will cause stateless component to re-render.

Also you should not alter the propas as they are immutable. Maintain state of the component.

Child = ({bar}) => (bar);

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

Requery a subform from another form?

I had a similar kind of issue, but with some differences...

In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:

Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef

'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
            "[Qry_Pedidos distintos].[Codigo], " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
            "SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
            "FROM [Qry_Pedidos distintos] " & _
            "WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
            " Group BY " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "[Qry_Pedidos distintos].[Codigo];"
End Sub

Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".

But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:

Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query 
    Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)

'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
    Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub

No refresh, recalc, requery, etc, was necessary after all...

How many threads is too many?

If your threads are performing any kind of resource-intensive work (CPU/Disk) then you'll rarely see benefits beyond one or two, and too many will kill performance very quickly.

The 'best-case' is that your later threads will stall while the first ones complete, or some will have low-overhead blocks on resources with low contention. Worst-case is that you start thrashing the cache/disk/network and your overall throughput drops through the floor.

A good solution is to place requests in a pool that are then dispatched to worker threads from a thread-pool (and yes, avoiding continuous thread creation/destruction is a great first step).

The number of active threads in this pool can then be tweaked and scaled based on the findings of your profiling, the hardware you are running on, and other things that may be occurring on the machine.

git: fatal: Could not read from remote repository

I would recommend to check all remotes you have configured with git remote -v If you had your repo configured to a remote that was deleted you will receive this error message: fatal: Could not read from remote repository. Please make sure you have the correct access rightsand the repository exists. Even when trying to push or pull to an other (existing) remote. So if you have a remote that was deleted, you can remove with git remote remove name-of-remote-to-remove and after that you can push or pull to your existing remotes without problems.

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

Converting a Java Keystore into PEM Format

In case you don't have openssl installed and you are looking for a quick solution, there is software called portcle which is very useful and small to download.

The disadvantage is that there is no command line as far as I know. But from the GUI, it is pretty straight forward to export a PEM private key:

  1. Open you JKS key store
  2. Right click over your private key entry and select export
  3. Select Private Key and certificates and PEM format

    Export PEM private key from JKS with Portcle

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

put file slf4j-log4j12-1.6.4.jar in the classpath will do the trick.

Adding elements to a collection during iteration

You may also want to look at some of the more specialised types, like ListIterator, NavigableSet and (if you're interested in maps) NavigableMap.

How to compile and run C/C++ in a Unix console/Mac terminal?

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

jQuery UI - Draggable is not a function?

I went through both your question and a another duplicate.
In the end, the following answer helped me sorting things out:
uncaught-typeerror-draggable-is-not-a-function

To get rid of :

$(".draggable").draggable is not a function anymore

I had to put links to Javascript libraries above the script tag I expected to be working.

My code:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" />

<script>
    $(function(){
        $("#container-speed").draggable();
    });
</script>

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="rowbackground"style="width: 600px; height: 400px; margin: 0 auto">
                <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
                <div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
            </div>
        </div>
    </div>
</div>

How to retrieve value from elements in array using jQuery?

Your syntax is incorrect.

card_value = $(array[i]).val(); or card_value = array[i].value;

array[i] is not a jQuery object (for some reason).

Checking your browser's console can be helpful for things like this.

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

EntityType has no key defined error

You don't have to use key attribute all the time. Make sure the mapping file properly addressed the key

this.HasKey(t => t.Key);
this.ToTable("PacketHistory");
this.Property(p => p.Key)
            .HasColumnName("PacketHistorySK");

and don't forget to add the mapping in the Repository's OnModelCreating

modelBuilder.Configurations.Add(new PacketHistoryMap());

No Exception while type casting with a null in java

Print:

Print an object. The string produced by the String.valueOf(Object) method is translated into bytes

ValueOf:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

It wil simply return a string with value "null" when the object is null.

Get safe area inset top and bottom heights

safeAreaLayoutGuide When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

Then to get the height of the red arrow in the screenshot it's:

self.safeAreaLayoutGuide.layoutFrame.size.height

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

How to display a date as iso 8601 format with PHP

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

What does the ^ (XOR) operator do?

XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.

This is its function table:

a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

This operation is performed between every two corresponding bits of a number.

Example: 7 ^ 10
In binary: 0111 ^ 1010

  0111
^ 1010
======
  1101 = 13

Properties: The operation is commutative, associative and self-inverse.

It is also the same as addition modulo 2.

Single selection in RecyclerView

Please try this... This works for me..

In adapter,take a sparse boolean array.

SparseBooleanArray sparseBooleanArray;

In constructor initialise this,

   sparseBooleanArray=new SparseBooleanArray();

In bind holder add,

@Override
public void onBindViewHolder(DispositionViewHolder holder, final int position) {
   holder.tv_disposition.setText(dispList.get(position).getName());
    if(sparseBooleanArray.get(position,false))
    {
        holder.rd_disp.setChecked(true);
    }
    else
    {
        holder.rd_disp.setChecked(false);


    }
    setClickListner(holder,position);
}

private void setClickListner(final DispositionViewHolder holder, final int position) {
    holder.rd_disp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sparseBooleanArray.clear();
            sparseBooleanArray.put(position, true);
            notifyDataSetChanged();


        }
    });
}

rd_disp is radio button in xml file.

So when the recycler view load the items,in bindView Holder it check whether the sparseBooleanArray contain the value "true" correspnding to its position.

If the value returned is true then we set the radio button selection true.Else we set the selection false. In onclickHolder I have cleared the sparseArray and set the value true corresponding to that position. When I call notify datasetChange it again call the onBindViewHolder and the condition are checked again. This makes our selection to only select particular radio.

GET URL parameter in PHP

To make sure you're always on the safe side, without getting all kinds of unwanted code insertion use FILTERS:

echo filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);

More reading on php.net function filter_input, or check out the description of the different filters

How to give environmental variable path for file appender in configuration file in log4j

java -DLOG_DIR=${LOG_DIR} -jar myjar.jar "param1" "param2" ==> in cmd line if you have "value="${LOG_DIR}/log/clientProject/project-error.log" in xml

How to move screen without moving cursor in Vim?

Additionally:

  • Ctrl-y Moves screen up one line
  • Ctrl-e Moves screen down one line
  • Ctrl-u Moves cursor & screen up ½ page
  • Ctrl-d Moves cursor & screen down ½ page
  • Ctrl-b Moves screen up one page, cursor to last line
  • Ctrl-f Moves screen down one page, cursor to first line

Ctrl-y and Ctrl-e only change the cursor position if it would be moved off screen.

Courtesy of http://www.lagmonster.org/docs/vi2.html

Get domain name

I'm going to add an answer to try to clear up a few things here as there seems to be some confusion. The main issue is that people are asking the wrong question, or at least not being specific enough.

What does a computer's "domain" actually mean?

When we talk about a computer's "domain", there are several things that we might be referring to. What follows is not an exhaustive list, but it covers the most common cases:

  • A user or computer security principal may belong to an Active Directory domain.
  • The network stack's primary DNS search suffix may be referred to as the computer's "domain".
  • A DNS name that resolves to the computer's IP address may be referred to as the computer's "domain".

Which one do I want?

This is highly dependent on what you are trying to do. The original poster of this question was looking for the computer's "Active Directory domain", which probably means they are looking for the domain to which either the computer's security principal or a user's security principal belongs. Generally you want these when you are trying to talk to Active Directory in some way. Note that the current user principal and the current computer principal are not necessarily in the same domain.

Pieter van Ginkel's answer is actually giving you the local network stack's primary DNS suffix (the same thing that's shown in the top section of the output of ipconfig /all). In the 99% case, this is probably the same as the domain to which both the computer's security principal and the currently authenticated user's principal belong - but not necessarily. Generally this is what you want when you are trying to talk to devices on the LAN, regardless of whether or not the devices are anything to do with Active Directory. For many applications, this will still be a "good enough" answer for talking to Active Directory.

The last option, a DNS name, is a lot fuzzier and more ambiguous than the other two. Anywhere between zero and infinity DNS records may resolve to a given IP address - and it's not necessarily even clear which IP address you are interested in. user2031519's answer refers to the value of HTTP_HOST, which is specifically useful when determining how the user resolved your HTTP server in order to send the request you are currently processing. This is almost certainly not what you want if you are trying to do anything with Active Directory.

How do I get them?

Domain of the current user security principal

This one's nice and simple, it's what Tim's answer is giving you.

System.Environment.UserDomainName

Domain of the current computer security principal

This is probably what the OP wanted, for this one we're going to have to ask Active Directory about it.

System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain()

This one will throw a ActiveDirectoryObjectNotFoundException if the local machine is not part of domain, or the domain controller cannot be contacted.

Network stack's primary DNS suffix

This is what Pieter van Ginkel's answer is giving you. It's probably not exactly what you want, but there's a good chance it's good enough for you - if it isn't, you probably already know why.

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName

DNS name that resolves to the computer's IP address

This one's tricky and there's no single answer to it. If this is what you are after, comment below and I will happily discuss your use-case and help you to work out the best solution (and expand on this answer in the process).

How to format a java.sql Timestamp for displaying?

For this particular question, the standard suggestion of java.text.SimpleDateFormat works, but has the unfortunate side effect that SimpleDateFormat is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!

I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).

convert big endian to little endian in C [without using provided func]

Will this work / be faster?

 uint32_t swapped, result;

((byte*)&swapped)[0] = ((byte*)&result)[3];
((byte*)&swapped)[1] = ((byte*)&result)[2];
((byte*)&swapped)[2] = ((byte*)&result)[1];
((byte*)&swapped)[3] = ((byte*)&result)[0];

Is the LIKE operator case-sensitive with MSSQL Server?

You can change from the property of every item.

case sensitive

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

React JS - Uncaught TypeError: this.props.data.map is not a function

More generally, you can also convert the new data into an array and use something like concat:

var newData = this.state.data.concat([data]);  
this.setState({data: newData})

This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.

What is Join() in jQuery?

I use join to separate the word in array with "and, or , / , &"

EXAMPLE

HTML

<p>London Mexico Canada</p>
<div></div>

JS

 newText = $("p").text().split(" ").join(" or ");
 $('div').text(newText);

Results

London or Mexico or Canada

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

Because you set visibility either true or false. try that setVisible(0) to visible true . and setVisible(4) to visible false.

Regex Email validation

Regex Email Pattern:

^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$

Align the form to the center in Bootstrap 4

You need to use the various Bootstrap 4 centering methods...

  • Use text-center for inline elements.
  • Use justify-content-center for flexbox elements (ie; form-inline)

https://codeply.com/go/Am5LvvjTxC

Also, to offset the column, the col-sm-* must be contained within a .row, and the .row must be in a container...

<section id="cover">
    <div id="cover-caption">
        <div id="container" class="container">
            <div class="row">
                <div class="col-sm-10 offset-sm-1 text-center">
                    <h1 class="display-3">Welcome to Bootstrap 4</h1>
                    <div class="info-form">
                        <form action="" class="form-inline justify-content-center">
                            <div class="form-group">
                                <label class="sr-only">Name</label>
                                <input type="text" class="form-control" placeholder="Jane Doe">
                            </div>
                            <div class="form-group">
                                <label class="sr-only">Email</label>
                                <input type="text" class="form-control" placeholder="[email protected]">
                            </div>
                            <button type="submit" class="btn btn-success ">okay, go!</button>
                        </form>
                    </div>
                    <br>

                    <a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
                </div>
            </div>
        </div>
    </div>
</section>

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

None of the above worked for me (tomcat 7.0.62)... As Sensei_Shoh notes see the class above the message and add this to logging.properties. My logs were:

Jan 18, 2016 8:44:21 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

so I added

org.apache.catalina.startup.TldConfig.level = FINE

in conf/logging.properties

After that I got so many "offending" files that I did not bother skipping them (and also reverted to normal logging...)

How to load html string in a webview?

To load your data in WebView. Call loadData() method of WebView

wv.loadData(yourData, "text/html", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

[Edit 1]

You should add -- \ -- before -- " -- for example --> name=\"spanish press\"

below string worked for me

String webData =  "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
 "<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";

How to embed new Youtube's live video permanent URL?

Have you tried plugin called " Youtube Live Stream Auto Embed"

Its seems to be working. Check it once.

How to correctly iterate through getElementsByClassName

I followed Alohci's recommendation of looping in reverse because it's a live nodeList. Here's what I did for those who are curious...

  var activeObjects = documents.getElementsByClassName('active'); // a live nodeList

  //Use a reverse-loop because the array is an active NodeList
  while(activeObjects.length > 0) {
    var lastElem = activePaths[activePaths.length-1]; //select the last element

    //Remove the 'active' class from the element.  
    //This will automatically update the nodeList's length too.
    var className = lastElem.getAttribute('class').replace('active','');
    lastElem.setAttribute('class', className);
  }

Phone: numeric keyboard for text input

Using the type="email" or type="url" will give you a keyboard on some phones at least, such as iPhone. For phone numbers, you can use type="tel".

XDocument or XmlDocument

I believe that XDocument makes a lot more object creation calls. I suspect that for when you're handling a lot of XML documents, XMLDocument will be faster.

One place this happens is in managing scan data. Many scan tools output their data in XML (for obvious reasons). If you have to process a lot of these scan files, I think you'll have better performance with XMLDocument.