Programs & Examples On #Unassigned variable

What does "Use of unassigned local variable" mean?

Not all code paths set a value for lateFee. You may want to set a default value for it at the top.

Android Fragment no view found for ID?

This issue also happens when you don't put <include layout="@layout/your_fragment_layout"/> in your app_bar_main.xml

OS detecting makefile

Another way to do this is by using a "configure" script. If you are already using one with your makefile, you can use a combination of uname and sed to get things to work out. First, in your script, do:

UNAME=uname

Then, in order to put this in your Makefile, start out with Makefile.in which should have something like

UNAME=@@UNAME@@

in it.

Use the following sed command in your configure script after the UNAME=uname bit.

sed -e "s|@@UNAME@@|$UNAME|" < Makefile.in > Makefile

Now your makefile should have UNAME defined as desired. If/elif/else statements are all that's left!

Unsupported major.minor version 52.0 when rendering in Android Studio

I've all done, setting JAVA_HOME, JAVA8_HOME, ... and i had always the error. For me the solution was to set the version 2.1.0 of gradle to work with Jdk 1.8.0_92 and android studio 2.11

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
    //classpath 'com.android.tools.build:gradle:2.+'
}

Can we have multiple "WITH AS" in single sql - Oracle SQL

Yes you can...

WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
     SET2 AS (SELECT * FROM SET1)        -- SET1 accessed
SELECT * FROM SET2;                      -- SET2 projected

10/29/2013 10:43:26 AM

Follow the order in which it should be initialized in Common Table Expressions

Parsing boolean values with argparse

I think the most canonical way will be:

parser.add_argument('--ensure', nargs='*', default=None)

ENSURE = config.ensure is None

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

connecting to phpMyAdmin database with PHP/MySQL

Set up a user, a host the user is allowed to talk to MySQL by using (e.g. localhost), grant that user adequate permissions to do what they need with the database .. and presto.

The user will need basic CRUD privileges to start, that's sufficient to store data received from a form. The rest of the permissions are self explanatory, i.e. permission to alter tables, etc. Give the user no more, no less power than it needs to do its work.

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

Example of a strong and weak entity types

A company insurance policy insures an employee and any dependents, the DEPENDENT cannot exist without the EMPLOYEE; that is, a person cannot get insurance coverage as a dependent unless the person is a dependent of an employee.DEPENDENT is the weak entity in the relationship "EMPLOYEE has DEPENDENT"

How can I scroll to a specific location on the page using jquery?

<script type="text/javascript">
    $(document).ready(function(){
        $(".scroll-element").click(function(){
            $('html,body').animate({
                scrollTop: $('.our_companies').offset().top
            }, 1000);

            return false;
        });
    })
</script>

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

How do I tell Maven to use the latest version of a dependency?

NOTE:

The mentioned LATEST and RELEASE metaversions have been dropped for plugin dependencies in Maven 3 "for the sake of reproducible builds", over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this Maven 3 compliant solution.


If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using.

When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all.

See the POM Syntax section of the Maven book for more details. Or see this doc on Dependency Version Ranges, where:

  • A square bracket ( [ & ] ) means "closed" (inclusive).
  • A parenthesis ( ( & ) ) means "open" (exclusive).

Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:

<?xml version="1.0" encoding="UTF-8"?><metadata>
  <groupId>com.foo</groupId>
  <artifactId>my-foo</artifactId>
  <version>2.0.0</version>
  <versioning>
    <release>1.1.1</release>
    <versions>
      <version>1.0</version>
      <version>1.0.1</version>
      <version>1.1</version>
      <version>1.1.1</version>
      <version>2.0.0</version>
    </versions>
    <lastUpdated>20090722140000</lastUpdated>
  </versioning>
</metadata>

If a dependency on that artifact is required, you have the following options (other version ranges can be specified of course, just showing the relevant ones here):

Declare an exact version (will always resolve to 1.0.1):

<version>[1.0.1]</version>

Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):

<version>1.0.1</version>

Declare a version range for all 1.x (will currently resolve to 1.1.1):

<version>[1.0.0,2.0.0)</version>

Declare an open-ended version range (will resolve to 2.0.0):

<version>[1.0.0,)</version>

Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)

<version>LATEST</version>

Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):

<version>RELEASE</version>

Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the Maven super POM. You can do this with either "-Prelease-profile" or "-DperformRelease=true"


It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results).

It is therefore generally a good idea to define exact versions in releases. As Tim's answer points out, the maven-versions-plugin is a handy tool for updating dependency versions, particularly the versions:use-latest-versions and versions:use-latest-releases goals.

Weird behavior of the != XPath operator

The problem is that the 'and' is being treated as an 'or'.

No, the problem is that you are using the XPath != operator and you aren't aware of its "weird" semantics.

Solution:

Just replace the any x != y expressions with a not(x = y) expression.

In your specific case:

Replace:

<xsl:when test="$AccountNumber != '12345' and $Balance != '0'">

with:

<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">

Explanation:

By definition whenever one of the operands of the != operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.

So:

 $someNodeSet != $someValue

generally doesn't produce the same result as:

 not($someNodeSet = $someValue)

The latter (by definition) is true exactly when there isn't a node in $someNodeSet whose string value is equal to $someValue.

Lesson to learn:

Never use the != operator, unless you are absolutely sure you know what you are doing.

pip not working in Python Installation in Windows 10

It's a really weird issue and I am posting this after wasting my 2 hours.

You installed Python and added it to PATH. You've checked it too(like 64-bit etc). Everything should work but it is not.

what you didn't do is a terminal/cmd restart

restart your terminal and everything would work like a charm.

I Hope, it helped/might help others.

Recursively looping through an object to build a property list

I made a FIDDLE for you. I am storing a stack string and then output it, if the property is of primitive type:

function iterate(obj, stack) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], stack + '.' + property);
                } else {
                    console.log(property + "   " + obj[property]);
                    $('#output').append($("<div/>").text(stack + '.' + property))
                }
            }
        }
    }

iterate(object, '')

UPDATE (17/01/2019) - <There used to be a different implementation, but it didn't work. See this answer for a prettier solution :)>

Maven Modules + Building a Single Specific Module

Any best practices here?

Use the Maven advanced reactor options, more specifically:

-pl, --projects
        Build specified reactor projects instead of all projects
-am, --also-make
        If project list is specified, also build projects required by the list

So just cd into the parent P directory and run:

mvn install -pl B -am

And this will build B and the modules required by B.

Note that you need to use a colon if you are referencing an artifactId which differs from the directory name:

mvn install -pl :B -am

As described here: https://stackoverflow.com/a/26439938/480894

Git removing upstream from local repository

git remote manpage is pretty straightforward:

Use

Older (backwards-compatible) syntax:
$ git remote rm upstream
Newer syntax for newer git versions: (* see below)
$ git remote remove upstream

Then do:    
$ git remote add upstream https://github.com/Foo/repos.git

or just update the URL directly:

$ git remote set-url upstream https://github.com/Foo/repos.git

or if you are comfortable with it, just update the .git/config directly - you can probably figure out what you need to change (left as exercise for the reader).

...
[remote "upstream"]
    fetch = +refs/heads/*:refs/remotes/upstream/*
    url = https://github.com/foo/repos.git
...

===

* Regarding 'git remote rm' vs 'git remote remove' - this changed around git 1.7.10.3 / 1.7.12 2 - see

https://code.google.com/p/git-core/source/detail?spec=svne17dba8fe15028425acd6a4ebebf1b8e9377d3c6&r=e17dba8fe15028425acd6a4ebebf1b8e9377d3c6

Log message

remote: prefer subcommand name 'remove' to 'rm'

All remote subcommands are spelled out words except 'rm'. 'rm', being a
popular UNIX command name, may mislead users that there are also 'ls' or
'mv'. Use 'remove' to fit with the rest of subcommands.

'rm' is still supported and used in the test suite. It's just not
widely advertised.

Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.

How to install Python packages from the tar.gz file without using pip install

Install it by running

python setup.py install

Better yet, you can download from github. Install git via apt-get install git and then follow this steps:

git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install

Plot two histograms on single chart with matplotlib

Here you have a working example:

import random
import numpy
from matplotlib import pyplot

x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

pyplot.hist(x, bins, alpha=0.5, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legend(loc='upper right')
pyplot.show()

enter image description here

Replace all spaces in a string with '+'

Use global search in the string. g flag

str.replace(/\s+/g, '+');

source: replaceAll function

How to run Selenium WebDriver test cases in Chrome

You can use the below code to run test cases in Chrome using Selenium WebDriver:

import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeTest {

    /**
     * @param args
     * @throws InterruptedException
     * @throws IOException
     */
    public static void main(String[] args) throws InterruptedException, IOException {
        // Telling the system where to find the Chrome driver
        System.setProperty(
                "webdriver.chrome.driver",
                "E:/chromedriver_win32/chromedriver.exe");

        WebDriver webDriver = new ChromeDriver();

        // Open google.com
        webDriver.navigate().to("http://www.google.com");

        String html = webDriver.getPageSource();

        // Printing result here.
        System.out.println(html);

        webDriver.close();
        webDriver.quit();
    }
}

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

This happened to me when I imported a Java 1.8 project from Eclipse Luna into Eclipse Kepler.

  1. Right click on project > Build path > configure build path...
  2. Select the Libraries tab, you should see the Java 1.8 jre with an error
  3. Select the java 1.8 jre and click the Remove button
  4. Add Library... > JRE System Library > Next > workspace default > Finish
  5. Click OK to close the properties window
  6. Go to the project menu > Clean... > OK

Et voilà, that worked for me.

Black transparent overlay on image hover with only CSS?

You can accomplish this by playing with the opacity of the image and setting the background color of the image to black. By making the image transparent, it will appear darker.

<div class="image">
    <img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div> 

CSS:

.image { position: relative; border: 1px solid black; width: 200px; height: 200px; background: black; }
.image img { max-width: 100%; max-height: 100%; }
.image img:hover { opacity: .5 }

You might need to set the browser-specific opacity too to make this work in other browsers too.

how to display data values on Chart.js

Based on @Ross's answer answer for Chart.js 2.0 and up, I had to include a little tweak to guard against the case when the bar's heights comes too chose to the scale boundary.

Example

The animation attribute of the bar chart's option:

animation: {
            duration: 500,
            easing: "easeOutQuart",
            onComplete: function () {
                var ctx = this.chart.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';

                this.data.datasets.forEach(function (dataset) {
                    for (var i = 0; i < dataset.data.length; i++) {
                        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
                            scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
                        ctx.fillStyle = '#444';
                        var y_pos = model.y - 5;
                        // Make sure data value does not get overflown and hidden
                        // when the bar's value is too close to max value of scale
                        // Note: The y value is reverse, it counts from top down
                        if ((scale_max - model.y) / scale_max >= 0.93)
                            y_pos = model.y + 20; 
                        ctx.fillText(dataset.data[i], model.x, y_pos);
                    }
                });               
            }
        }

Determine the line of code that causes a segmentation fault?

There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).

Modern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking.

According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:

int main() {
  volatile int *ptr = (int*)0;
  *ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
    #0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
    #1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
    #2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING

The output is slightly more complicated than what gdb would output but there are upsides:

  • There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.

  • ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.


¹ That is Clang 3.1+ and GCC 4.8+.

Windows equivalent to UNIX pwd

You can simply put "." the dot sign. I've had a cmd application that was requiring the path and I was already in the needed directory and I used the dot symbol.

Hope it helps.

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Long Press in JavaScript?

like this?

doc.addEeventListener("touchstart", function(){
    // your code ...
}, false);    

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

What's the actual use of 'fail' in JUnit test case?

I, for example, use fail() to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

Inner text shadow with CSS

There's a much simpler way to achieve this

.inner{color: red; text-shadow: 0 -1px 0 #666;} // #666 is the color of the inner shadow

Voilà

Check if a time is between two times (time DataType)

Should be AND instead of OR

select *
from MyTable
where CAST(Created as time) >= '23:00:00' 
   AND CAST(Created as time) < '07:00:00'

htaccess redirect all pages to single page

If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$ 
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L] 

Where 000 000 000 000 should be replaced by your ip adress.

Source:

http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

'this' is undefined in JavaScript class methods

In ES2015 a.k.a ES6, class is a syntactic sugar for functions.

If you want to force to set a context for this you can use bind() method. As @chetan pointed, on invocation you can set the context as well! Check the example below:

class Form extends React.Component {
constructor() {
    super();
  }
  handleChange(e) {
    switch (e.target.id) {
      case 'owner':
        this.setState({owner: e.target.value});
        break;
      default:
    }
  }
  render() {
    return (
      <form onSubmit={this.handleNewCodeBlock}>
        <p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
      </form>
    );
  }
}

Here we forced the context inside handleChange() to Form.

How to convert .pem into .key?

If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.

See this SO question/answer for more details on the SSL options in that file.

Why is SSLCertificateKeyFile needed for Apache?

Get remote registry value

You can try using .net:

$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer1)
$RegKey= $Reg.OpenSubKey("SOFTWARE\\Veritas\\NetBackup\\CurrentVersion")
$NetbackupVersion1 = $RegKey.GetValue("PackageVersion")

How to set thousands separator in Java?

For decimals:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat dfDecimal = new DecimalFormat("###########0.00###");
dfDecimal.setDecimalFormatSymbols(symbols);
dfDecimal.setGroupingSize(3);
dfDecimal.setGroupingUsed(true);
System.out.println(dfDecimal.format(number));

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

I did not get it. I had a similar problem but in my nav bar.

What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a

In order to put hover effects on a I positioned a to relative and designed a::before and a::after then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a> they will pop from outside a to fill <a>.

The problem is that the overflow hidden is not working on <a>.

What i discovered is if i removed <li> and simply put <a> without <ul> and <li> then it worked.

What may be the problem?

Deep cloning objects

I came up with this to overcome a .NET shortcoming having to manually deep copy List<T>.

I use this:

static public IEnumerable<SpotPlacement> CloneList(List<SpotPlacement> spotPlacements)
{
    foreach (SpotPlacement sp in spotPlacements)
    {
        yield return (SpotPlacement)sp.Clone();
    }
}

And at another place:

public object Clone()
{
    OrderItem newOrderItem = new OrderItem();
    ...
    newOrderItem._exactPlacements.AddRange(SpotPlacement.CloneList(_exactPlacements));
    ...
    return newOrderItem;
}

I tried to come up with oneliner that does this, but it's not possible, due to yield not working inside anonymous method blocks.

Better still, use generic List<T> cloner:

class Utility<T> where T : ICloneable
{
    static public IEnumerable<T> CloneList(List<T> tl)
    {
        foreach (T t in tl)
        {
            yield return (T)t.Clone();
        }
    }
}

Dropdown using javascript onchange

easy

<script>
jQuery.noConflict()(document).ready(function() {
    $('#hide').css('display','none');
    $('#plano').change(function(){

        if(document.getElementById('plano').value == 1){
            $('#hide').show('slow');    

        }else 
            if(document.getElementById('plano').value == 0){

             $('#hide').hide('slow'); 
        }else
            if(document.getElementById('plano').value == 0){
             $('#hide').css('display','none');  

            }

    });
    $('#plano').change();
});
</script>

this example shows and hides the div if selected in combobox some specific value

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

Iterate through string array in Java

You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:

String[] elements = {"a", "a", "a", "a"};   
for (String s: elements) {           
    //Do your stuff here
    System.out.println(s); 
}

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

I faced the same problem on Mac OS X and with Miniconda. After trying many of the proposed solutions for hours I found that I needed to correctly set Condas environment – specifically requests environment variable – to use the Root certificate that my company provided rather than the generic ones that Conda provides.

Here is how I solved it:

  1. Open Chrome, got to any website, click on the lock icon on the left of the URL. Click on «Certificate» on the dropdown. In the next window you see a stack of certificates. The uppermost (aka top line in window) is the root certificate (e.g. Zscaler Root CA in my case, yours will very likely be a different one).

enter image description here

  1. Open Mac OS keychain, click on «Certificates» and choose among the many certificates the root certificate that you just identified. Export this to any folder of your choosing.
  2. Convert this certificate with openssl: openssl x509 -inform der -in /path/to/your/certificate.cer -out /path/to/converted/certificate.pem
  3. For a quick check set your shell to acknowledge the certificate: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem
  4. To set this permanently open your shell profile (.bshrs or e.g. .zshrc) and add this line: export REQUESTS_CA_BUNDLE=/path/to/converted/certificate.pem. Now exit your terminal/shell and reopen. Check again.

You should be set and Conda should work fine.

Why does Google prepend while(1); to their JSON responses?

As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]

This attack can be achieved in 3 major steps:

Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

<script src="http://<jsonsite>/json_server.php"></script>

The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

Object.prototype.__defineSetter__('ccnum',function(obj){

secrets =secrets.concat(" ", obj);

});

At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

There are several ways in which JSON Hijacking can be prevented:

  • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

  • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

  • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

*

FIX CSS <!--[if lt IE 8]> in IE

How about

<!--[if IE]>
...
<![endif]-->

You can read here about conditional comments.

jQuery $(".class").click(); - multiple elements, click event once

Simply enter code hereIn JQuery, ones event is triggered you just check number of occurrences of classes in file and use for loop for next logic. for identify number of occurrences of any class, tag or any DOM element through JQuery : var len = $(".addproduct").length;

 $(".addproduct").click(function(){
       var len = $(".addproduct").length; 
       for(var i=0;i<len;i++){
          ...
        }
 });

Cordova : Requirements check failed for JDK 1.8 or greater

Guys to get the mix right on Windows, you need to do the following

  1. Download and install any version of JDK 1.8 or higher.
  2. Open environment variables, create an environment variable called JAVA_HOME and set value to JDK install path. C:\Program Files\Java\jdk1.8.0_162 make sure you do not add the \bin in the value.

enter image description here

  1. In your system path variable, put a semi-colon ; and add this value to system path e.g C:\Program Files\Java\jdk1.8.0_162\bin; Here the \bin is added.

Note: The environment variables are tricky.They are supposed to be closed by a ; before opening another. That is why we put one before adding the value and one after the value to close it.

enter image description here

  1. Now close terminal and reopen then run previous commands.

Using SQL LOADER in Oracle to import CSV file

I hade a csv file named FAR_T_SNSA.csv that i wanted to import in oracle database directly. For this i have done the following steps and it worked absolutely fine. Here are the steps that u vand follow out:

HOW TO IMPORT CSV FILE IN ORACLE DATABASE ?

  1. Get a .csv format file that is to be imported in oracle database. Here this is named “FAR_T_SNSA.csv”
  2. Create a table in sql with same column name as there were in .csv file. create table Billing ( iocl_id char(10), iocl_consumer_id char(10));

  3. Create a Control file that contains sql*loder script. In notepad type the script as below and save this with .ctl extension, in selecting file type as All Types(*). Here control file is named as Billing. And the Script is as Follows:

    LOAD DATA
    INFILE 'D:FAR_T_SNSA.csv'
    INSERT INTO TABLE Billing
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    TRAILING NULLCOLS
    (
    iocl_id,
    iocl_consumer_id
    )
    
  4. Now in Command prompt run command:

    Sqlldr UserId/Password
    Control = “ControlFileName” 
    --------------------------------
    Here ControlFileName is Billing.
    

How do I auto size a UIScrollView to fit its content

Set dynamic content size like this.

 self.scroll_view.contentSize = CGSizeMake(screen_width,CGRectGetMaxY(self.controlname.frame)+20);

Creating virtual directories in IIS express

@Be.St.'s aprroach is true, but incomplete. I'm just copying his explanation with correcting the incorrect part.

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
   <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Instead of adding a new application block, you should just add a new virtualDirectory element to the application parent element.

Edit - Visual Studio 2015

If you're looking for the applicationHost.config file and you're using VS2015 you'll find it in:

[solution_directory]/.vs/config/applicationHost.config

Stack Memory vs Heap Memory

It's a language abstraction - some languages have both, some one, some neither.

In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new to allocate memory in a loop without calling delete to free it it. But make a system backup before doing this.

display:inline vs display:block

block elements expand to fill their parent.

inline elements contract to be just big enough to hold their children.

How to change position of Toast in Android?

Toast toast = Toast.makeText(this, "Custom toast creation", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
    toast.show();

How do I determine height and scrolling position of window in jQuery?

$(window).height()

$(window).width()

There is also a plugin to jquery to determine element location and offsets

http://plugins.jquery.com/project/dimensions

scrolling offset = offsetHeight property of an element

jQuery Cross Domain Ajax

The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.

$.ajax({
    type: 'GET',
    dataType: "text", // You need to use dataType text else it will try to parse it.
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

What is a callback URL in relation to an API?

If you use the callback URL, then the API can connect to the callback URL and send or receive some data. That means API can connect to you later (after API call).

Example

Diagram

  1. YOU send data using request to API
  2. API sends data using second request to YOU

Exact definition should be in API documentation.

#pragma pack effect

I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.

How do I get the path of a process in Unix / Linux

There's no "guaranteed to work anywhere" method.

Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().

Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user's PATH from the environment and go through that to see if there's a suitable executable binary with the same name.

Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.

Sql query to insert datetime in SQL Server

A more language-independent choice for string literals is the international standard ISO 8601 format "YYYY-MM-DDThh:mm:ss". I used the SQL query below to test the format, and it does indeed work in all SQL languages in sys.syslanguages:

declare @sql nvarchar(4000)

declare @LangID smallint
declare @Alias sysname

declare @MaxLangID smallint
select @MaxLangID = max(langid) from sys.syslanguages

set @LangID = 0

while @LangID <= @MaxLangID
begin

    select @Alias = alias
    from sys.syslanguages
    where langid = @LangID

    if @Alias is not null
    begin

        begin try
            set @sql = N'declare @TestLang table (langdate datetime)
    set language ''' + @alias + N''';
    insert into @TestLang (langdate)
    values (''2012-06-18T10:34:09'')'
            print 'Testing ' + @Alias

            exec sp_executesql @sql
        end try
        begin catch
            print 'Error in language ' + @Alias
            print ERROR_MESSAGE()
        end catch
    end

    select @LangID = min(langid)
    from sys.syslanguages
    where langid > @LangID
end

According to the String Literal Date and Time Formats section in Microsoft TechNet, the standard ANSI Standard SQL date format "YYYY-MM-DD hh:mm:ss" is supposed to be "multi-language". However, using the same query, the ANSI format does not work in all SQL languages.

For example, in Danish, you will many errors like the following:

Error in language Danish The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

If you want to build a query in C# to run on SQL Server, and you need to pass a date in the ISO 8601 format, use the Sortable "s" format specifier:

string.Format("select convert(datetime2, '{0:s}'", DateTime.Now);

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Copy text from nano editor to shell

M-^ is copy Text. "M" in my environment is "Esc" key ! not "Ctrl"; so I use Esc + 6 to copy that.

[nano help] Escape-key sequences are notated with the Meta (M-) symbol and can be entered using either the Esc, Alt, or Meta key depending on your keyboard setup.

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

If you're using Hibernate then change in your "hibernate.cfg.xml" the following:

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

To:

<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

That should do :)

Android Studio - Failed to apply plugin [id 'com.android.application']

I found the simplest answer to this.

Just go gradle.properties file and change the enableUnitTestBinaryResources from true to false

android.enableUnitTestBinaryResources=false

The snapshot is shown below

enter image description here

Logical operator in a handlebars.js {{#if}} conditional

Similar to Jim's answer but a using a bit of creativity we could also do something like this:

Handlebars.registerHelper( "compare", function( v1, op, v2, options ) {

  var c = {
    "eq": function( v1, v2 ) {
      return v1 == v2;
    },
    "neq": function( v1, v2 ) {
      return v1 != v2;
    },
    ...
  }

  if( Object.prototype.hasOwnProperty.call( c, op ) ) {
    return c[ op ].call( this, v1, v2 ) ? options.fn( this ) : options.inverse( this );
  }
  return options.inverse( this );
} );

Then to use it we get something like:

{{#compare numberone "eq" numbretwo}}
  do something
{{else}}
  do something else
{{/compare}}

I would suggest moving the object out of the function for better performance but otherwise you can add any compare function you want, including "and" and "or".

Convert RGB to Black & White in OpenCV

Simple binary threshold method is sufficient.

include

#include <string>
#include "opencv/highgui.h"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("./img.jpg",0);//loading gray scale image
    threshold(img, img, 128, 255, CV_THRESH_BINARY);//threshold binary, you can change threshold 128 to your convenient threshold
    imwrite("./black-white.jpg",img);
    return 0;
}

You can use GaussianBlur to get a smooth black and white image.

How to store a datetime in MySQL with timezone info

MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.

So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!

Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:

  1. You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW()).

  2. You do INSERT INTO table (dateCreated) VALUES (?), and specify the current time from your application code.

CASE #1

MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.

So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.

CASE #2

It depends on what type of value you pass as ?. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

How to add icon inside EditText view in Android ?

Use :

<EditText
    ..     
    android:drawableStart="@drawable/icon" />

android studio 0.4.2: Gradle project sync failed error

I was seeing this error along with: "Error:compileSdkVersion android-21 requires compiling with JDK 7"

For me, the solution was found here, where I had to update the JDK location in the project structure.

UTF-8 byte[] to String

Knowing that you are dealing with a UTF-8 byte array, you'll definitely want to use the String constructor that accepts a charset name. Otherwise you may leave yourself open to some charset encoding based security vulnerabilities. Note that it throws UnsupportedEncodingException which you'll have to handle. Something like this:

public String openFileToString(String fileName) {
    String file_string;
    try {
        file_string = new String(_bytes, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // this should never happen because "UTF-8" is hard-coded.
        throw new IllegalStateException(e);
    }
    return file_string;
}

System has not been booted with systemd as init system (PID 1). Can't operate

use this command for run every service just write name service for example :

for xrdp :

sudo /etc/init.d/xrdp start

for redis :

sudo /etc/init.d/redis start

(for any other service, check the init.d folder for filenames)

How to get the height of a body element

Simply use

$(document).height() // - $('body').offset().top

and / or

$(window).height()

instead of $('body').height();

How to get HQ youtube thumbnails?

YouTube resolutions and images

http://img.youtube.com/vi/<video-id>/<resolution><image>.jpg

Resolution
- lowest resolution
sd - Standard Definition
mq - Medium Quality
hq - High Quality
maxres - MAXimum RESolution

Image
default - Default image (1, 2, 3 shot from video, or custom uploaded)
1 - First shot from video
2 - Second shot from video
3 - Third shot from video

What is the string concatenation operator in Oracle?

Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD

Item frequency count in Python

The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})

Validation for 10 digit mobile number and focus input field on invalid

Use jquery validator in your script tag DEMO

<script src="js/jquery.validate.min.js"></script> 

and validate your element by like this

   <form name="enquiry_form" method="post" id="enquiry_form">

    Full Name *
    <input class="input-style" name="name"  id="name" type="text"/>
    <br>
    Email *
    <input class="input-style" name="email"  id="email" type="email"><br>
    Phone * 
        <input id="mobile" name="mobile"  id="mobile"></input><br>

    <input type="submit" value="SUBMIT"  id="enq_submit">

</form>

 $('#enquiry_form').validate({
      rules:{
      name:"required",
      email:{
      required:true,
      email:true
      },
      mobile:{
          required:true,
      minlength:9,
      maxlength:10,
      }
      },
      messages:{
      name:"Please enter your username..!",
      email:"Please enter your email..!",
          mobile:"Enter your mobile no"
      },

      submitHandler: function(form) {
alert("working");
      //write your success code here  
      }
      });

Undefined reference to main - collect2: ld returned 1 exit status

I my case I found out the void for the main function declaration was missing.

I was previously using Visual Studio in Windows and this was never a problem, so I thought I might leave it out now too.

Android webview slow

If you are binding to the onclick event, it might be slow on touch screens.

To make it faster, I use fastclick, which uses the much faster touch events to mimic the click event.

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

additionally for accepted answer you can use UseSubmitBehavior="false" MSDN

What is the difference between id and class in CSS, and when should I use them?

For more info on this click here.

Example

<div id="header_id" class="header_class">Text</div>

#header_id {font-color:#fff}
.header_class {font-color:#000}

(Note that CSS uses the prefix # for IDs and . for Classes.)

However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5. In CSS there is no "font-color", the style is color so the above should read:

Example

<div id="header_id" class="header_class">Text</div>

#header_id {color:#fff}
.header_class {color:#000}

The text would be white.

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

$(document).ready shorthand

Even shorter variant is to use

$(()=>{

});

where $ stands for jQuery and ()=>{} is so called 'arrow function' that inherits this from the closure. (So that in this you'll probably have window instead of document.)

What is the difference between task and thread?

Thread

The bare metal thing, you probably don't need to use it, you probably can use a LongRunning task and take the benefits from the TPL - Task Parallel Library, included in .NET Framework 4 (february, 2002) and above (also .NET Core).

Tasks

Abstraction above the Threads. It uses the thread pool (unless you specify the task as a LongRunning operation, if so, a new thread is created under the hood for you).

Thread Pool

As the name suggests: a pool of threads. Is the .NET framework handling a limited number of threads for you. Why? Because opening 100 threads to execute expensive CPU operations on a Processor with just 8 cores definitely is not a good idea. The framework will maintain this pool for you, reusing the threads (not creating/killing them at each operation), and executing some of them in parallel, in a way that your CPU will not burn.

OK, but when to use each one?

In resume: always use tasks.

Task is an abstraction, so it is a lot easier to use. I advise you to always try to use tasks and if you face some problem that makes you need to handle a thread by yourself (probably 1% of the time) then use threads.

BUT be aware that:

  • I/O Bound: For I/O bound operations (database calls, read/write files, APIs calls, etc) avoid using normal tasks, use LongRunning tasks (or threads if you need to). Because using tasks would lead you to a thread pool with a few threads busy and a lot of another tasks waiting for its turn to take the pool.
  • CPU Bound: For CPU bound operations just use the normal tasks (that internally will use the thread pool) and be happy.

What's the best way to build a string of delimited items in Java?

You could write a little join-style utility method that works on java.util.Lists

public static String join(List<String> list, String delim) {

    StringBuilder sb = new StringBuilder();

    String loopDelim = "";

    for(String s : list) {

        sb.append(loopDelim);
        sb.append(s);            

        loopDelim = delim;
    }

    return sb.toString();
}

Then use it like so:

    List<String> list = new ArrayList<String>();

    if( condition )        list.add("elementName");
    if( anotherCondition ) list.add("anotherElementName");

    join(list, ",");

Simple If/Else Razor Syntax

I would just go with

<tr @(if (count++ % 2 == 0){<text>class="alt-row"</text>})>

Or even better

<tr class="alt-row@(count++ % 2)">

this will give you lines like

<tr class="alt-row0">
<tr class="alt-row1">
<tr class="alt-row0">
<tr class="alt-row1">

Show just the current branch in Git

In Git 1.8.1 you can use the git symbolic-ref command with the "--short" option:

$ git symbolic-ref HEAD
refs/heads/develop
$ git symbolic-ref --short HEAD
develop

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Python IndentationError unindent does not match any outer indentation level

You have mixed indentation formatting (spaces and tabs)

On Notepad++

Change Tab Settings to 4 spaces

Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Fix the current file mixed indentations

Select everything CTRL+A

Click TAB once, to add an indentation everywhere

Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.

Regular expression search replace in Sublime Text 2

Here is a visual presentation of the approved answer.

enter image description here

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

enter image description hereI had to login as the owner and go to Settings -> Apps, then swipe to the All tab. Scroll down to the very end of the list where the old versions are listed with a mark 'not installed'. Select it and press the 'settings' button in the top right corner and finally 'uninstall for all users'

MVC3 EditorFor readOnly

I use the readonly attribute instead of disabled attribute - as this will still submit the value when the field is readonly.

Note: Any presence of the readonly attribute will make the field readonly even if set to false, so hence why I branch the editor for code like below.

 @if (disabled)
 {
     @Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control", @readonly = "" } })
 }
 else
 {
     @Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
 }

SameSite warning Chrome 77

This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.

It has nothing to do with your code. It is something their web servers will have to support.

Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site

February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.

For the full Chrome release schedule, see here.

I solved same problem by adding in response header

response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");

SameSite prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.

SameSite cookies explained here

Please refer this before applying any option.

Hope this helps you.

How does Java handle integer underflows and overflows and how would you check for it?

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

You can check that beforehand as follows:

public static boolean willAdditionOverflow(int left, int right) {
    if (right < 0 && right != Integer.MIN_VALUE) {
        return willSubtractionOverflow(left, -right);
    } else {
        return (~(left ^ right) & (left ^ (left + right))) < 0;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    if (right < 0) {
        return willAdditionOverflow(left, -right);
    } else {
        return ((left ^ right) & (left ^ (left - right))) < 0;
    }
}

(you can substitute int by long to perform the same checks for long)

If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. long or maybe java.math.BigInteger. The last one doesn't overflow, practically, the available JVM memory is the limit.


If you happen to be on Java8 already, then you can make use of the new Math#addExact() and Math#subtractExact() methods which will throw an ArithmeticException on overflow.

public static boolean willAdditionOverflow(int left, int right) {
    try {
        Math.addExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    try {
        Math.subtractExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

The source code can be found here and here respectively.

Of course, you could also just use them right away instead of hiding them in a boolean utility method.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

What does enctype='multipart/form-data' mean?

When you make a POST request, you have to encode the data that forms the body of the request in some way.

HTML forms provide three methods of encoding.

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain

Work was being done on adding application/json, but that has been abandoned.

(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)

The specifics of the formats don't matter to most developers. The important points are:

  • Never use text/plain.

When you are writing client-side code:

  • use multipart/form-data when your form includes any <input type="file"> elements
  • otherwise you can use multipart/form-data or application/x-www-form-urlencoded but application/x-www-form-urlencoded will be more efficient

When you are writing server-side code:

  • Use a prewritten form handling library

Most (such as Perl's CGI->param or the one exposed by PHP's $_POST superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.

Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).


If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.

application/x-www-form-urlencoded is more or less the same as a query string on the end of the URL.

multipart/form-data is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.

text/plain is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).

Spring Data JPA - "No Property Found for Type" Exception

I ran into this same issue and found the solution here: https://dzone.com/articles/persistence-layer-spring-data

I had renamed an entity property. But with Springs Automatic Custom Queries there was an interface defined for the old property name.

public interface IFooDAO extends JpaRepository< Foo, Long >{
     Foo findByOldPropName( final String name );
}

The error indicated that it could no longer find "OldPropName" and threw the exception.

To quote the article on DZone:

When Spring Data creates a new Repository implementation, it analyzes all the methods defined by the interfaces and tries to automatically generate queries from the method name. While this has limitations, it is a very powerful and elegant way of defining new custom access methods with very little effort. For example, if the managed entity has a name field (and the Java Bean standard getter and setter for that field), defining the findByName method in the DAO interface will automatically generate the correct query:

public interface IFooDAO extends JpaRepository< Foo, Long >{
     Foo findByName( final String name );
}

This is a relatively simple example; a much larger set of keywords is supported by query creation mechanism.

In the case that the parser cannot match the property with the domain object field, the following exception is thrown:

java.lang.IllegalArgumentException: No property nam found for type class org.rest.model.Foo

When do I use super()?

The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.

Disable the postback on an <ASP:LinkButton>

I think you should investigate using a HyperLink control. It's a server-side control (so you can manipulate visibility and such from code), but it omits a regular ol' anchor tag and doesn't cause a postback.

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

Override default Spring-Boot application.properties settings in Junit Test

If you're using Spring 5.2.5 and Spring Boot 2.2.6 and want to override just a few properties instead of the whole file. You can use the new annotation: @DynamicPropertySource

@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {

    @Container
    static Neo4jContainer<?> neo4j = new Neo4jContainer<>();

    @DynamicPropertySource
    static void neo4jProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
    }
}

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

How do I run a single test using Jest?

If you have jest running as a script command, something like npm test, you need to use the following command to make it work:

npm test -- -t "fix order test"

Have a reloadData for a UITableView animate when changing

Have more freedom using CATransition class.

It isn't limited to fading, but can do movements as well..


For example:

(don't forget to import QuartzCore)

CATransition *transition = [CATransition animation];
transition.type = kCATransitionPush;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.fillMode = kCAFillModeForwards;
transition.duration = 0.5;
transition.subtype = kCATransitionFromBottom;

[[self.tableView layer] addAnimation:transition forKey:@"UITableViewReloadDataAnimationKey"];

Change the type to match your needs, like kCATransitionFade etc.

Implementation in Swift:

let transition = CATransition()
transition.type = kCATransitionPush
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.fillMode = kCAFillModeForwards
transition.duration = 0.5
transition.subtype = kCATransitionFromTop
self.tableView.layer.addAnimation(transition, forKey: "UITableViewReloadDataAnimationKey")
// Update your data source here
self.tableView.reloadData()

Reference for CATransition

Swift 5:

let transition = CATransition()
transition.type = CATransitionType.push
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transition.fillMode = CAMediaTimingFillMode.forwards
transition.duration = 0.5
transition.subtype = CATransitionSubtype.fromTop
self.tableView.layer.add(transition, forKey: "UITableViewReloadDataAnimationKey")
// Update your data source here
self.tableView.reloadData()

Why does foo = filter(...) return a <filter object>, not a list?

Have a look at the python documentation for filter(function, iterable) (from here):

Construct an iterator from those elements of iterable for which function returns true.

So in order to get a list back you have to use list class:

shesaid = list(filter(greetings(), ["hello", "goodbye"]))

But this probably isn't what you wanted, because it tries to call the result of greetings(), which is "hello", on the values of your input list, and this won't work. Here also the iterator type comes into play, because the results aren't generated until you use them (for example by calling list() on it). So at first you won't get an error, but when you try to do something with shesaid it will stop working:

>>> print(list(shesaid))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

If you want to check which elements in your list are equal to "hello" you have to use something like this:

shesaid = list(filter(lambda x: x == "hello", ["hello", "goodbye"]))

(I put your function into a lambda, see Randy C's answer for a "normal" function)

Log4j: How to configure simplest possible file logging?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="fileAppender" /> 
  </root> 

</log4j:configuration>

Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.

Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.

Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.

So what this file is saying is:

  1. Create a fileAppender that logs to file sample.log
  2. Attach that appender to the root logger.
  3. The root logger will respond to any events at least as detailed as 'debug' level
  4. The appender is configured to only log events that are at least as detailed as 'info'

The net out is that if you have a logger.debug("blah blah") in your code it will get ignored. A logger.info("Blah blah"); will output to sample.log.

The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root> but would limit the all logging events from the package org.springframework to those logged at level info or above.

  <!-- Example Package level Logger -->
    <logger name="org.springframework">
        <level value="info"/>
    </logger>   

Assembly Language - How to do Modulo?

An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.

https://godbolt.org/z/64zKGr

Loop structure inside gnuplot?

Here is the alternative command:

gnuplot -p -e 'plot for [file in system("find . -name \\*.txt -depth 1")] file using 1:2 title file with lines'

How can I find the last element in a List<>?

If you just want to access the last item in the list you can do

if(integerList.Count>0)
{
   var item = integerList[integerList.Count - 1];
}

to get the total number of items in the list you can use the Count property

var itemCount = integerList.Count;

How to find sitemap.xml path on websites?

I don't think there's a standard as to the location of the sitemap. That's the reason why you should specify an arbitrary URL to your sitemap when you're adding one using Google's Webmaster Tools.

ExecutorService that interrupts tasks after a timeout

It seems problem is not in JDK bug 6602600 ( it was solved at 2010-05-22), but in incorrect call of sleep(10) in circle. Addition note, that the main Thread must give directly CHANCE to other threads to realize thier tasks by invoke SLEEP(0) in EVERY branch of outer circle. It is better, I think, to use Thread.yield() instead of Thread.sleep(0)

The result corrected part of previous problem code is such like this:

.......................
........................
Thread.yield();         

if (i % 1000== 0) {
System.out.println(i + "/" + counter.get()+ "/"+service.toString());
}

//                
//                while (i > counter.get()) {
//                    Thread.sleep(10);
//                } 

It works correctly with amount of outer counter up to 150 000 000 tested circles.

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

Probably this information will help. I was on Ubuntu 18.04 and when I tried to install Krita, using the ppa method, I got this error:

This application failed to start because it could not find or load the Qt platform plugin "xcb" in "".

Available platform plugins are: linuxfb, minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.

Reinstalling the application may fix this problem.

Aborted

I tried all the solutions that I found in this thread and other webs without any success.

Finally, I found a post where the author mention that is possible to activate the debugging tool of qt5 using this simple command:

export QT_DEBUG_PLUGINS=1

After adding this command I run again krita I got the same error, however this time I knew the cause of that error.

libxcb-xinerama.so.0: cannot open shared object file: No such file or directory.

This error prevents to the "xcb" to load properly. So, the solution will be install the `libxcb-xinerama.so.0" right? However, when I run the command:

sudo apt install libxcb-xinerama

The lib was already installed. Now what Teo? Well, then I used an old trick :) Yeah, that one --reinstall

sudo apt install --reinstall libxcb-xinerama

TLDR: This last command solved my problem.

How to get client's IP address using JavaScript?

There are two interpretations to this question. Most folks interpreted "Client IP" to mean the Public IP Address that Web server's see outside the LAN and out on the Internet. This is not the IP address of the client computer in most cases, though

I needed the real IP address of the computer that is running the browser that is hosting my JavaScript software (which is almost always a local IP address on a LAN that is behind something that NAT layer).

Mido posted a FANTASTIC answer, above, that seems to be the only answer that really provided the IP address of the client.

Thanks for that, Mido!

However, the function presented runs asynchronously. I need to actually USE the IP address in my code, and with an asynchronous solution, I might try to use the IP address before it is retrieved/learned/stored. I had to be able to wait on the results to arrive before using them.

Here is a "Waitable" version of Mido's function. I hope it helps someone else:

_x000D_
_x000D_
function findIP(onNewIP) { //  onNewIp - your listener function for new IPs_x000D_
    var promise = new Promise(function (resolve, reject) {_x000D_
        try {_x000D_
            var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome_x000D_
            var pc = new myPeerConnection({ iceServers: [] }),_x000D_
                noop = function () { },_x000D_
                localIPs = {},_x000D_
                ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
                key;_x000D_
            function ipIterate(ip) {_x000D_
                if (!localIPs[ip]) onNewIP(ip);_x000D_
                localIPs[ip] = true;_x000D_
            }_x000D_
            pc.createDataChannel(""); //create a bogus data channel_x000D_
            pc.createOffer(function (sdp) {_x000D_
                sdp.sdp.split('\n').forEach(function (line) {_x000D_
                    if (line.indexOf('candidate') < 0) return;_x000D_
                    line.match(ipRegex).forEach(ipIterate);_x000D_
                });_x000D_
                pc.setLocalDescription(sdp, noop, noop);_x000D_
            }, noop); // create offer and set local description_x000D_
_x000D_
            pc.onicecandidate = function (ice) { //listen for candidate events_x000D_
                if (ice && ice.candidate && ice.candidate.candidate && ice.candidate.candidate.match(ipRegex)) {_x000D_
                    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);_x000D_
                }_x000D_
                resolve("FindIPsDone");_x000D_
                return;_x000D_
            };_x000D_
        }_x000D_
        catch (ex) {_x000D_
            reject(Error(ex));_x000D_
        }_x000D_
    });// New Promise(...{ ... });_x000D_
    return promise;_x000D_
};_x000D_
_x000D_
//This is the callback that gets run for each IP address found_x000D_
function foundNewIP(ip) {_x000D_
    if (typeof window.ipAddress === 'undefined')_x000D_
    {_x000D_
        window.ipAddress = ip;_x000D_
    }_x000D_
    else_x000D_
    {_x000D_
        window.ipAddress += " - " + ip;_x000D_
    }_x000D_
}_x000D_
_x000D_
//This is How to use the Waitable findIP function, and react to the_x000D_
//results arriving_x000D_
var ipWaitObject = findIP(foundNewIP);        // Puts found IP(s) in window.ipAddress_x000D_
ipWaitObject.then(_x000D_
    function (result) {_x000D_
        alert ("IP(s) Found.  Result: '" + result + "'. You can use them now: " + window.ipAddress)_x000D_
    },_x000D_
    function (err) {_x000D_
        alert ("IP(s) NOT Found.  FAILED!  " + err)_x000D_
    }_x000D_
);_x000D_
_x000D_
_x000D_
 _x000D_
_x000D_
   
_x000D_
<h1>Demo "Waitable" Client IP Retrieval using WebRTC </h1>
_x000D_
_x000D_
_x000D_

VB.NET Switch Statement GoTo Case

Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

How do I change the default library path for R packages

After a couple of hours of trying to solve the issue in several ways, some of which are described here, for me (on Win 10) the option of creating a Renviron file worked, but a little different from what was written here above. The task is to change the value of the variable R_LIBS_USER. To do this two steps needed:

  1. Create the file named Renviron (without dot) in the folder \Program\etc\ (Programm is the directory where the R installed, for example for me it was c:\Program Files\R\R-4.0.0\etc)
  2. Insert a line in Renviron with new path: R_LIBS_USER=c:/R/Library

It's been working for a few days already.

Installing a pip package from within a Jupyter Notebook not working

Alternative option : you can also create a bash cell in jupyter using bash kernel and then pip install geocoder. That should work

CSS root directory

This problem that the "../" means step up (parent folder) link "../images/img.png" will not work because when you are using ajax like data passing to the web site from the server.

What you have to do is point the image location to root with "./" then the second folder (in this case the second folder is "images")

url("./images/img.png")

if you have folders like this

root -> content -> images

then you use url("./content/images/img.png"), remember your image will not visible in the editor window but when it passed to the browser using ajax it will display.

Extending from two classes

it is possible

public class ParallaxViewController<T extends View & Parallaxor> extends ParallaxController<T> implements AbsListView.OnScrollListener {

//blah
}

Function to check if a string is a date

I use this function as a parameter to the PHP filter_var function.

  • It checks for dates in yyyy-mm-dd hh:mm:ss format
  • It rejects dates that match the pattern but still invalid (e.g. Apr 31)

function filter_mydate($s) {
    if (preg_match('@^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$@', $s, $m) == false) {
        return false;
    }
    if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
        return false;
    }
    return $s;
}

Why is PHP session_destroy() not working?

Actually, it works, but you also need to do $_SESSION = array(); after the session_destroy to get rid of $_SESSION variables. However, avoid doing unset($_SESSION) because that makes sessions useless.

Could not resolve placeholder in string value

You can also try default values. spring-value-annotation

Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

If the same property is defined as a system property and in the properties file, then the system property would be applied.

phpexcel to download

$excel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');

// Do your stuff here

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

// This line will force the file to download
$writer->save('php://output');

XSL substring and indexOf

It's not clear exactly what you want to do with the index of a substring [update: it is clearer now - thanks] but you may be able to use the function substring-after or substring-before:

substring-before('My name is Fred', 'Fred')

returns 'My name is '.

If you need more detailed control, the substring() function can take two or three arguments: string, starting-index, length. Omit length to get the whole rest of the string.

There is no index-of() function for strings in XPath (only for sequences, in XPath 2.0). You can use string-length(substring-before($string, $substring))+1 if you specifically need the position.

There is also contains($string, $substring). These are all documented here. In XPath 2.0 you can use regular expression matching.

(XSLT mostly uses XPath for selecting nodes and processing values, so this is actually more of an XPath question. I tagged it thus.)

Variable name as a string in Javascript

No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

What is the difference between IQueryable<T> and IEnumerable<T>?

In simple words other major difference is that IEnumerable execute select query on server side, load data in-memory on client side and then filter data while IQueryable execute select query on server side with all filters.

How to measure time taken between lines of code in python?

I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:

from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken) 

output:

Time:  0:00:00.000019

What is the meaning of "this" in Java?

It refers to the current instance of a particular object, so you could write something like

public Object getMe() {
    return this;
}

A common use-case of this is to prevent shadowing. Take the following example:

public class Person {
    private final String name;

    public Person(String name) {
        // how would we initialize the field using parameter?
        // we can't do: name = name;
    }
}

In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.

public class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }
}

How to suspend/resume a process in Windows?

PsSuspend, as mentioned by Vadzim, even suspends/resumes a process by its name, not only by pid.

I use both PsSuspend and PsList (another tool from the PsTools suite) in a simple toggle script for the OneDrive process: if I need more bandwidth, I suspend the OneDrive sync, afterwards I resume the process by issuing the same mini script:

PsList -d onedrive|find/i "suspend" && PsSuspend -r onedrive || PsSuspend onedrive

PsSuspend command line utility from SysInternals suite. It suspends / resumes a process by its id.

Function or sub to add new row and data to table

Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
        table.ListRows.Add Position:=1
        Set lastRow = table.ListRows(1).Range
    Else
        Set lastRow = table.ListRows(table.ListRows.Count).Range
    End If
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

Use different Python version with virtualenv

End of 2020:

The most seamless experience for using virtualenv (added benefit: with any possible python version) would be to use pyenv and its (bundled) pyenv-virtualenv plugin (cf https://realpython.com/intro-to-pyenv/#virtual-environments-and-pyenv)

Usage: pyenv virtualenv <python_version> <environment_name>

Installation:

cf https://github.com/pyenv/pyenv-installer

That being said, nowadays the best possible alternative instead of using virtualenv (and pip) would be Poetry (along with pyenv indicated above, to handle different python versions).

Another option, because it's supported directly by the PyPA (the org behind pip and the PyPI) and has restarted releasing since the end of May (didn't release since late 2018 prior to that...) would be Pipenv

How to zip a file using cmd line?

You can use the following command:

zip -r nameoffile.zip directory

Hope this helps.

How to iterate object in JavaScript?

for(index in dictionary) {
 for(var index in dictionary[]){
    // do something
  }
}

MySQL: When is Flush Privileges in MySQL really needed?

2 points in addition to all other good answers:

1:

what are the Grant Tables?

from dev.mysql.com

The MySQL system database includes several grant tables that contain information about user accounts and the privileges held by them.

clari?cation: in MySQL, there are some inbuilt databases , one of them is "mysql" , all the tables on "mysql" database have been called as grant tables

2:

note that if you perform:

UPDATE a_grant_table SET password=PASSWORD('1234') WHERE test_col = 'test_val';

and refresh phpMyAdmin , you'll realize that your password has been changed on that table but even now if you perform:

mysql -u someuser -p

your access will be denied by your new password until you perform :

FLUSH PRIVILEGES;

Getting time and date from timestamp with php

$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));

Is there a need for range(len(a))?

I have an use case I don't believe any of your examples cover.

boxes = [b1, b2, b3]
items = [i1, i2, i3, i4, i5]
for j in range(len(boxes)):
    boxes[j].putitemin(items[j])

I'm relatively new to python though so happy to learn a more elegant approach.

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

Difference between return and exit in Bash functions

Adding an actionable aspect to a few of the other answers:

Both can give exit codes - default or defined by the function, and the only 'default' is zero for success for both exit and return. Any status can have a custom number 0-255, including for success.

Return is used often for interactive scripts that run in the current shell, called with . script.sh for example, and just returns you to your calling shell. The return code is then accessible to the calling shell - $? gives you the defined return status. Exit in this case also closes your shell (including SSH connections, if that's how you're working).

Exit is necessary if the script is executable and called from another script or shell and runs in a subshell. The exit codes then are accessible to the calling shell - return would give an error in this case.

sorting a List of Map<String, String>

if you want to make use of lamdas and make it a bit easier to read

  List<Map<String,String>> results;

  Comparator<Map<String,String>> sortByName = Comparator.comparing(x -> x.get("Name"));

  public void doSomething(){
    results.sort(sortByName)
  }

How to check null objects in jQuery

Check the jQuery FAQ...

You can use the length property of the jQuery collection returned by your selector:

if ( $('#myDiv').length ){}

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

to pass many options you can pass a object to a @Input decorator with custom data in a single line.

In the template

<li *ngFor = 'let opt of currentQuestion.options' 
                [selectable] = 'opt'
                [myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
                (selectedOption) = 'onOptionSelection($event)' >
     {{opt.option}}
</li>

so in Directive class

@Directive({
  selector: '[selectable]'
})

export class SelectableDirective{
  private el: HTMLElement;
  @Input('selectable') option:any;
  @Input('myOptions') data;

  //do something with data.first
  ...
  // do something with data.second
}

What is the correct way to restore a deleted file from SVN?

If you're using Tortoise SVN, you should be able to revert changes from just that revision into your working copy (effectively performing a reverse-merge), then do another commit to re-add the file. Steps to follow are:

  1. Browse to folder in working copy where you deleted the file.
  2. Go to repo-browser.
  3. Browse to revision where you deleted the file.
  4. In the change list, find the file you deleted.
  5. Right click on the file and go to "Revert changes from this revision".
  6. This will restore the file to your working copy, keeping history.
  7. Commit the file to add it back into your repository.

How do I push amended commit to the remote Git repository?

Here is a very simple and clean way to push your changes after you have already made a git add "your files" and git commit --amend:

git push origin master -f

or:

git push origin master --force

How to use and style new AlertDialog from appCompat 22.1 and above

If you're like me you just want to modify some of the colors in AppCompat, and the only color you need to uniquely change in the dialog is the background. Then all you need to do is set a color for colorBackgroundFloating.

Here's my basic theme that simply modifies some colors with no nested themes:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/theme_colorPrimary</item>
        <item name="colorPrimaryDark">@color/theme_colorPrimaryDark</item>
        <item name="colorAccent">@color/theme_colorAccent</item>
        <item name="colorControlActivated">@color/theme_colorControlActivated</item>
        <item name="android:windowBackground">@color/theme_bg</item>
        <item name="colorBackgroundFloating">@color/theme_dialog_bg</item><!-- Dialog background color -->
        <item name="colorButtonNormal">@color/theme_colorPrimary</item>
        <item name="colorControlHighlight">@color/theme_colorAccent</item>
    </style>

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

jQuery add required to input fields

$("input").prop('required',true);

DEMO FIDDLE

What is the purpose of the single underscore "_" variable in Python?

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

Django set field value after a form is initialized

Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial keyword.

form = CustomForm(initial={'Email': GetEmailString()})

See the Django Form docs for more explanation.

If you are trying to change a value after the form was submitted, you can use something like:

if form.is_valid():
    form.cleaned_data['Email'] = GetEmailString()

Check the referenced docs above for more on using cleaned_data

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

List all virtualenv

You can use the lsvirtualenv, in which you have two options "long" or "brief":

"long" option is the default one, it searches for any hook you may have around this command and executes it, which takes more time.

"brief" just take the virtualenvs names and prints it.

brief usage:

$ lsvirtualenv -b

long usage:

$ lsvirtualenv -l

if you don't have any hooks, or don't even know what i'm talking about, just use "brief".

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

How can I change the Y-axis figures into percentages in a barplot?

ggplot2 and scales packages can do that:

y <- c(12, 20)/100
x <- c(1, 2)

library(ggplot2)
library(scales)
myplot <- qplot(as.factor(x), y, geom="bar")
myplot + scale_y_continuous(labels=percent)

It seems like the stat() option has been taken off, causing the error message. Try this:

library(scales)

myplot <- ggplot(mtcars, aes(factor(cyl))) + 
          geom_bar(aes(y = (..count..)/sum(..count..))) + 
          scale_y_continuous(labels=percent)

myplot

SVN Commit specific files

Sure. Just list the files:

$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png

I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:

$ svn ci -m "No longer sets printer on fire" printer-driver/*.c

You can also have the svn command read the list of files to commit from a file:

$ svn ci -m "Now works" --targets fix4711.txt

Matplotlib 2 Subplots, 1 Colorbar

To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow instead of pcolormesh because of the 1:1 aspect ratio imposed by imshow.

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
    im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.flat)
plt.show()

enter image description here

How can I get the baseurl of site?

This is a much more fool proof method.

VirtualPathUtility.ToAbsolute("~/");

jQuery append() - return appended elements

There's a simpler way to do this:

$(newHtml).appendTo('#myDiv').effects(...);

This turns things around by first creating newHtml with jQuery(html [, ownerDocument ]), and then using appendTo(target) (note the "To" bit) to add that it to the end of #mydiv.

Because you now start with $(newHtml) the end result of appendTo('#myDiv') is that new bit of html, and the .effects(...) call will be on that new bit of html too.

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;

ptr+100,10

to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

Angular 2 - innerHTML styling

We pull in content frequently from our CMS as [innerHTML]="content.title". We place the necessary classes in the application's root styles.scss file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}} in the template will not render html from the content.

How do you copy and paste into Git Bash

It's not really a function of git, msys, or bash; every windows console program is stuck using the same cumbersome copy/paste mechanism for historical reasons. Turning on QuickEdit mode can help -- or you can install a nice alternative console like this one, and change your git bash shortcut to use it instead.

Save modifications in place with awk

@sudo_O has the right answer.

This can't work:

someprocess < file > file

The shell performs the redirections before handing control over to someprocess (redirections). The > redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Nodejs - Redirect url

The logic of determining a "wrong" url is specific to your application. It could be a simple file not found error or something else if you are doing a RESTful app. Once you've figured that out, sending a redirect is as simple as:

response.writeHead(302, {
  'Location': 'your/404/path.html'
  //add other headers here...
});
response.end();

Safest way to get last record ID from a table

Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.

Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.

How to access the local Django webserver from outside world

Pick one or more from:

  • Your application isn't successfully listening on the intended IP:PORT
    • Because you haven't configured it successfully
    • Because the user doesn't have permission to
  • Your application is listening successfully on the intended IP:PORT, but clients can't reach it because
    • The server local iptables prevents it.
    • A firewall prevents it.

So, you can check that your application is listening successfully by running lsof -i as root on the machine and look for a python entry with the corresponding port you've specified.

Non-root users generally cannot bind to ports < 1024.

You'll need to look at iptables -nvL to see if there's a rule that would prevent access to the ip:port that you are trying to bind your application to.

If there is an upstream firewall and you don't know much about it, you'll need to talk to your network administrators.

The specified child already has a parent. You must call removeView() on the child's parent first

if you are adding the same view repeatedly in a for loop .. if this is the case then try creating the View object of the layout inside the for loop . and add the view in side the for loop

To avoid such issues

How to use componentWillMount() in React Hooks?

useComponentWillMount hook

export const useComponentWillMount = (func) => {
    const willMount = useRef(true)

    if (willMount.current) func()

    willMount.current = false
}

// or
export const useComponentWillMount = (func) => {
    useMemo(func, [])
}

Discussion

In class components componentWillMount is considered legacy (source 1, source2). However, this shouldn't apply to functional components and a hook based solution. Class component componentWillMount is deprecated since it might run more than once, and there is an alternative - using the constructor. Those considerations aren't relevant for a functional component.

My experience is that such a hook could be a saver when timing/sequence is critical. I'm interested to know what is your use case - comments are welcome.

useComponentDidMount hook

Alternatively, use componentDidMount hook.

const useComponentDidMount = func => useEffect(func, []);

It will run only once, after component has mounted(initial render to the dom).

Demo

const Component = (props) => {
  useComponentWillMount(() => console.log("Runs only once before component mounts"));
  useComponentDidMount(() => console.log("Runs only once after component mounts"));
  ...

  return (
    <div>{...}</div>
  );
}

Full Demo

How to make an autocomplete address field with google maps api?

I really doubt it--google maps API is great for geocoding known addresses, but it generally return data that is suitable for autocomplete-style operations. Nevermind the challenge of not hitting the API in such a way as to eat up your geocoding query limit very quickly.

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

Eclipse java debugging: source not found

I had the problem that my Eclipse was not debugging the source code of my project. I was getting a blank page with "Source code node found".

Please click the Attach source code button. Then delete the "default" folder then click add and go to your project location and attach. This worked for me

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

Return a "NULL" object if search result not found

If you want a NULL return value you need to use pointers instead of references.

References can't themselves be NULL.

(Note to the future comment posters: Yes you can have the address of a reference be NULL if you really really try to).

See my answer here for a list of differences between references and pointers.

PHP - Modify current object in foreach loop

There are 2 ways of doing this

foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}

This way you save the key, so you can update it again in the main $questions variable

or

foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per the PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Format number to 2 decimal places

This is how I used this is as an example:

CAST(vAvgMaterialUnitCost.`avgUnitCost` AS DECIMAL(11,2)) * woMaterials.`qtyUsed` AS materialCost

In C#, why is String a reference type that behaves like a value type?

Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...

(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

How to get VM arguments from inside of Java application?

If you want the entire command line of your java process, you can use: JvmArguments.java (uses a combination of JNA + /proc to cover most unix implementations)

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

How can I read a whole file into a string variable

This is how I did it:

package main

import (
  "fmt"
  "os"
  "bytes"
  "log"
)

func main() {
   filerc, err := os.Open("filename")
   if err != nil{
     log.Fatal(err)
   }
   defer filerc.Close()

   buf := new(bytes.Buffer)
   buf.ReadFrom(filerc)
   contents := buf.String()

   fmt.Print(contents) 

}    

Check if inputs form are empty jQuery

$(document).ready(function () {
  $('input[type="text"]').blur(function () {
    if (!$(this).val()) {
      $(this).addClass('error');
    } else {
      $(this).removeClass('error');
    }
  });
});


<style>
 .error {
   border: 1px solid #ff0000;
 }
</style>

Easiest way to toggle 2 classes in jQuery

The easiest solution is to toggleClass() both classes individually.

Let's say you have an icon:

    <i id="target" class="fa fa-angle-down"></i>

To toggle between fa-angle-down and fa-angle-up do the following:

    $('.sometrigger').click(function(){
        $('#target').toggleClass('fa-angle-down');
        $('#target').toggleClass('fa-angle-up');
    });

Since we had fa-angle-down at the beginning without fa-angle-up each time you toggle both, one leaves for the other to appear.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Neither of the first two answers worked for me with multiple elements that can open dialogs that point to different pages.

This feels like the cleanest solution, only creates the dialog object once on load and then uses the events to open/close/display appropriately:

$(function () {
      var ajaxDialog = $('<div id="ajax-dialog" style="display:hidden"></div>').appendTo('body');
      ajaxDialog.dialog({autoOpen: false});
      $('a.ajax-dialog-opener').live('click', function() {
          // load remote content
          ajaxDialog.load(this.href);
          ajaxDialog.dialog("open");
          //prevent the browser from following the link
          return false;
      });
}); 

adding 30 minutes to datetime php/mysql

MySQL has a function called ADDTIME for adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).

Something like (untested):

SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

Setting default permissions for newly created files and sub-directories under a directory in Linux?

To get the right ownership, you can set the group setuid bit on the directory with

chmod g+rwxs dirname

This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default.

I don't know of a way to force the permissions you want if the user's umask is too strong.

Getting values from query string in an url using AngularJS $location

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub