Programs & Examples On #Directory listing

How do you get a list of the names of all files present in a directory in Node.js?

I usually use: FS-Extra.

const fileNameArray = Fse.readdir('/some/path');

Result:

[
  "b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
  "daeb1c5b-809f-4434-8fd9-410140789933.jpg"
]

Non-alphanumeric list order from os.listdir()

Per the documentation:

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Order cannot be relied upon and is an artifact of the filesystem.

To sort the result, use sorted(os.listdir(path)).

Recursive directory listing in DOS

You can use:

dir /s

If you need the list without all the header/footer information try this:

dir /s /b

(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)

Vbscript list all PDF files in folder and subfolders

(For those who stumble upon this from your search engine of choice)

This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.

Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)

Wscript.Echo "end."

WScript.Quit 0

Sub ShowSubFolders(fFolder)
    Set objFolder = objFSO.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
        If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
            Wscript.Echo objFile.Name
        End If
    Next

    For Each Subfolder in fFolder.SubFolders
        ShowSubFolders(Subfolder)
    Next
End Sub

Get a filtered list of files in a directory

import os

dir="/path/to/dir"
[x[0]+"/"+f for x in os.walk(dir) for f in x[2] if f.endswith(".jpg")]

This will give you a list of jpg files with their full path. You can replace x[0]+"/"+f with f for just filenames. You can also replace f.endswith(".jpg") with whatever string condition you wish.

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

How to get the list of files in a directory in a shell script?

for entry in "$search_dir"/* "$work_dir"/*
do
  if [ -f "$entry" ];then
    echo "$entry"
  fi
done

Finish all previous activities

i have same problem you can use IntentCompat , like this :

import android.support.v4.content.IntentCompat;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);

this code work for me .

Android api 17

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

Store multiple values in single key in json

{
    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"
        }
    }
};

Declaring abstract method in TypeScript

I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).

The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.

You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.

Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/

// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
    // encapsulates animal behaviors that must be implemented
    makeSound(input : string): string;
}

class BaseAnimal {
    constructor(public name) { }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
    constructor(name) { super(name); }
    makeSound(input : string): string {
        var utterance = "sssss"+input;
        alert(utterance);
        return utterance;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

var longMover = new Snake("windy man");

longMover.makeSound("...am I nothing?");
longMover.move();

var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);

I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920

Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:

export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {

    subMenuTitle = "Ontologies Rendered"; // overload or overshadow?

    constructor(
        public conceptGraph: ConceptGraph.ConceptGraph,
        graphView: PathToRoot.ConceptPathsToRoot,
        implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
        ){
        super(graphView);
        this.implementation = this;
    }
}

and

export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {

    public implementation: IFilterWidget<N, L>

    filterContainer: JQuery;

    public subMenuTitle : string; // Given value in children

    constructor(
        public graphView: GraphView.GraphView<N, L>
        ){

    }

    doStuff(node: N){
        this.implementation.generateStuff(thing);
    }

}

export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {

    generateStuff(node: N): string;

}

Correct way of getting Client's IP Addresses from http.Request

Looking at http.Request you can find the following member variables:

// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header

// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string

You can use RemoteAddr to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).

This is all you have for sure.

Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:

req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter

This is because internally http.Header.Get will normalise the key for you. (If you want to access header map directly, and not through Get, you would need to use http.CanonicalHeaderKey first.)

Finally, "X-Forwarded-For" is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:

// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
    fmt.Println(ip)
}

will produce:

10.0.0.1
10.0.0.2
10.0.0.3

Printing a char with printf

In C char gets promoted to int in expressions. That pretty much explains every question, if you think about it.

Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie

A must read if you want to learn C.

Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.

react-router scroll to top on every transition

Hooks are composable, and since React Router v5.1 we have a useHistory() hook. So based off @zurfyx's answer I've created a re-usable hook for this functionality:

// useScrollTop.ts
import { useHistory } from 'react-router-dom';
import { useEffect } from 'react';

/*
 * Registers a history listener on mount which
 * scrolls to the top of the page on route change
 */
export const useScrollTop = () => {
    const history = useHistory();
    useEffect(() => {
        const unlisten = history.listen(() => {
            window.scrollTo(0, 0);
        });
        return unlisten;
    }, [history]);
};

Search text in fields in every table of a MySQL database

MySQL Workbench

Here are some instructions.

Download and install MSQL Workbench.

https://www.mysql.com/products/workbench/

When installing, it might require you to install Visual Studio C++ Redistributable. You can get it here:

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

x64: vc_redist.x64.exe (for 64 bit Windows)

When you open MySQL Workbench, you will have to enter your host name, user and password.

There is a Schemas tab on the side menu bar, click on the Schemas tab, then double click on a database to select the database you want to search.

Then go to menu Database - Search Data, and enter the text you are searching for, click on Start Search.

enter image description here

HeidiSql

Download and install HeidiSql https://www.heidisql.com/download.php

Enter your hostname, user and password.

Hit Ctrl+Shift+F to search text.

enter image description here

Spring boot - Not a managed type

I had some problem while migrating from Spring boot 1.3.x to 1.5, I got it working after updating entity package at EntityManagerFactory bean

  @Bean(name="entityManagerFactoryDef")
  @Primary
  public LocalContainerEntityManagerFactoryBean defaultEntityManager() {
      Map map = new HashMap();
      map.put("hibernate.default_schema", env.getProperty("spring.datasource.username"));
      map.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
      LocalContainerEntityManagerFactoryBean em = createEntityManagerFactoryBuilder(jpaVendorProperties())
              .dataSource(primaryDataSource()).persistenceUnit("default").properties(map).build();
      em.setPackagesToScan("com.simple.entity");
      em.afterPropertiesSet();
      return em;
  }

This bean referred in Application class as below

@SpringBootApplication
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryDef")
public class SimpleApp {

}

Remove last 3 characters of string or number in javascript

Remove last 3 characters of a string

var str = '1437203995000';
str = str.substring(0, str.length-3);
// '1437203995'

Remove last 3 digits of a number

var a = 1437203995000;
a = (a-(a%1000))/1000;
// a = 1437203995

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I changed the memory limit from .htaccess and this problem got resolved.

I was trying to scan my website from one of the antivirus plugin and there I was getting this problem. I increased memory by pasting this in my .htaccess file in Wordpress folder:

php_value memory_limit 512M

After scan was over, I removed this line to make the size as it was before.

Why should C++ programmers minimize use of 'new'?

To a great extent, that's someone elevating their own weaknesses to a general rule. There's nothing wrong per se with creating objects using the new operator. What there is some argument for is that you have to do so with some discipline: if you create an object you need to make sure it's going to be destroyed.

The easiest way of doing that is to create the object in automatic storage, so C++ knows to destroy it when it goes out of scope:

 {
    File foo = File("foo.dat");

    // do things

 }

Now, observe that when you fall off that block after the end-brace, foo is out of scope. C++ will call its dtor automatically for you. Unlike Java, you don't need to wait for the GC to find it.

Had you written

 {
     File * foo = new File("foo.dat");

you would want to match it explicitly with

     delete foo;
  }

or even better, allocate your File * as a "smart pointer". If you aren't careful about that it can lead to leaks.

The answer itself makes the mistaken assumption that if you don't use new you don't allocate on the heap; in fact, in C++ you don't know that. At most, you know that a small amout of memory, say one pointer, is certainly allocated on the stack. However, consider if the implementation of File is something like

  class File {
    private:
      FileImpl * fd;
    public:
      File(String fn){ fd = new FileImpl(fn);}

then FileImpl will still be allocated on the stack.

And yes, you'd better be sure to have

     ~File(){ delete fd ; }

in the class as well; without it, you'll leak memory from the heap even if you didn't apparently allocate on the heap at all.

Declaring variables inside loops, good practice or bad practice?

Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.

Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.

Cannot open local file - Chrome: Not allowed to load local resource

I've encounterd this problem, and here is my solution for Angular, I wrapped my Angular's asset folder in encodeURIComponent() function. It worked. But still, I'd like to know more about the risk of this solution if there's any:

```const URL = ${encodeURIComponent(/assets/office/file_2.pdf)} window.open(URL)

I used Angular 9, so this is my url when I clicked open local file:
```http://localhost:4200/%2Fassets%2Foffice%2Ffile_2.pdf```

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

could not access the package manager. is the system running while installing android application

The solution for me was to restart the IDE. I suspect that a slow emulator was hiding from view, blocking installation on my device.

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

UTC Date/Time String to Timezone

Assuming the UTC is not included in the string then:

date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00';  //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date;  //Should get '2011-01-01 10:00:00 EST' or something like that

Or you could use the DateTime object.

less than 10 add 0 to number

You can always do

('0' + deg).slice(-2)

See slice():

You can also use negative numbers to select from the end of an array

Hence

('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2)  // '04'

For ease of access, you could of course extract it to a function, or even extend Number with it:

Number.prototype.pad = function(n) {
    return new Array(n).join('0').slice((n || 2) * -1) + this;
}

Which will allow you to write:

c += deg.pad() + '° '; // "04° "

The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:

deg.pad(4) // "0045"

Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).

Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.

How to write macro for Notepad++?

My personal experience is that shortcuts.xml is overwritten with the initially loaded + later recorded macros and settings when Notepad++ exits. So you can't use Notepad++ itself for editing this file.

Close Notepad++, edit shortcuts.xml by another tool, save it and restart Notepad++.

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

If you trust the host, either add the valid certificate, specify --no-check-certificate or add:

check_certificate = off

into your ~/.wgetrc.

In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.

Creating a random string with A-Z and 0-9 in Java

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

how to refresh page in angular 2

Without a bit more code ... its hard to say what's going on.

But if your code looks something like this:

<li routerLinkActive="active">
  <a [routerLink]="/categories"><p>Products Categories</p></a>
</li>
...
<router-outlet></router-outlet>
<myComponentA></myComponentA>
<myComponentB></myComponentB>

Then clicking on the router link will route to the categories route and display its template in the router outlet.

Hiding and showing the child components don't affect what is displayed in the router outlet.

So if you click the link again, the categories route is already displayed in the router outlet and it won't display/re-initialize again.

If you could be a bit more specific about what you are trying to do, we could provide more specific suggestions for you. :-)

How to import a module given its name as string?

You can use exec:

exec("import myapp.commands.%s" % command)

What is the difference between screenX/Y, clientX/Y and pageX/Y?

Here's a picture explaining the difference between pageY and clientY.

pageY vs clientY

Same for pageX and clientX, respectively.


pageX/Y coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),

while clientX/Y coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.

See Demo

You'll probably never need screenX/Y

how can the textbox width be reduced?

rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.

http://htmldog.com/reference/htmltags/textarea/

Can't compare naive and aware datetime.now() <= challenge.datetime_end

One line of code solution

if timezone_aware_var <= datetime.datetime.now(timezone_aware_var.tzinfo):
    pass #some code

Explained version

# Timezone info of your timezone aware variable
timezone = your_timezone_aware_variable.tzinfo

# Current datetime for the timezone of your variable
now_in_timezone = datetime.datetime.now(timezone)

# Now you can do a fair comparison, both datetime variables have the same time zone
if your_timezone_aware_variable <= now_in_timezone:
    pass #some code

Summary

You must add the timezone info to your now() datetime.
However, you must add the same timezone of the reference variable; that is why I first read the tzinfo attribute.

Submit form using a button outside the <form> tag

Similar to another solution here, with minor modification:

<form method="METHOD" id="FORMID">
   <!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>

https://www.w3schools.com/tags/att_form.asp

How can I use std::maps with user-defined types as key?

You need to define operator < for the Class1.

Map needs to compare the values using operator < and hence you need to provide the same when user defined class are used as key.

class Class1
{
public:
    Class1(int id);

    bool operator <(const Class1& rhs) const
    {
        return id < rhs.id;
    }
private:
    int id;
};

Link to the issue number on GitHub within a commit message

Just as addition to the other answers: If you don't even want to write the commit message with the issue number and happen to use Eclipse for development, then you can install the eGit and Mylyn plugins as well as the GitHub connector for Mylyn. Eclipse can then automatically track which issue you are working on and automatically fill the commit message, including the issue number as shown in all the other answers.

For more details about that setup see http://wiki.eclipse.org/EGit/GitHub/UserGuide

CSS Input field text color of inputted text

I always do input prompts, like this:

    <input style="color: #C0C0C0;" value="[email protected]" 
    onfocus="this.value=''; this.style.color='#000000'">

Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:

    <script language = "text/Javascript"> 
    cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
    function clearField(t){                   //declaring the array outside of the
    if(! cleared[t.id]){                      // function makes it static and global
        cleared[t.id] = 1;  // you could use true and false, but that's more typing
        t.value='';         // with more chance of typos
        t.style.color='#000000';
        }
    }
    </script>

Your <input> field then looks like this:

    <input id = 0; style="color: #C0C0C0;" value="[email protected]" 
    onfocus=clearField(this)>

How to convert from java.sql.Timestamp to java.util.Date?

java.sql.ResultSet rs;
//fill rs somehow
java.sql.Timestamp timestamp = rs.getTimestamp(1); //get first column
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
java.util.Date date = return new java.util.Date(milliseconds);

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Django values_list vs values

The best place to understand the difference is at the official documentation on values / values_list. It has many useful examples and explains it very clearly. The django docs are very user freindly.

Here's a short snippet to keep SO reviewers happy:

values

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

And read the section which follows it:

value_list

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

Difference between JSON.stringify and JSON.parse

JSON.parse() is used to convert String to Object.
JSON.stringify() is used to convert Object to String.

You can refer this too...

<script type="text/javascript">

function ajax_get_json(){

    var hr = new XMLHttpRequest();
    hr.open("GET", "JSON/mylist.json", true);
    hr.setRequestHeader("Content-type", "application/json",true);
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
           /*  var return_data = hr.responseText; */

           var data=JSON.parse(hr.responseText);
           var status=document.getElementById("status");
           status.innerHTML = "";
           /* status.innerHTML=data.u1.country;  */
           for(var obj in data)
               {
               status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
               }

        }
    }
    hr.send(null);
    status.innerHTML = "requesting...";
}
</script>

Java Singleton and Synchronization

What is the best way to implement Singleton in Java, in a multithreaded environment?

Refer to this post for best way to implement Singleton.

What is an efficient way to implement a singleton pattern in Java?

What happens when multiple threads try to access getInstance() method at the same time?

It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.

Refer to this question for more details:

Why is volatile used in this example of double checked locking

Can we make singleton's getInstance() synchronized?

Is synchronization really needed, when using Singleton classes?

Not required if you implement the Singleton in below ways

  1. static intitalization
  2. enum
  3. LazyInitalaization with Initialization-on-demand_holder_idiom

Refer to this question fore more details

Java Singleton Design Pattern : Questions

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Making an svg image object clickable with onclick, avoiding absolute positioning

In case you're fine with wrapping the svg in another element (a for example) and putting onclick on the wrapper, svg {pointer-events: none;} CSS will do the trick.

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

So, I ran into this same issue. The problem I was having here was that my database wasn't properly synced. Simple problems always seem to cause the most angst...

To sync your django db, from within your app directory, within terminal, type:

$ python manage.py syncdb

Edit: Note that if you are using django-south, running the '$ python manage.py migrate' command may also resolve this issue.

Happy coding!

How to do logging in React Native?

There are several ways to achieve this, I am listing them and including cons in using them also. You can use:

  1. console.log and view logging statements on, without opting out for remote debugging option from dev tools, Android Studio and Xcode. or you can opt out for remote debugging option and view logging on chrome dev tools or vscode or any other editor that supports debugging, you have to be cautious as this will slow down the process as a whole.
  2. You can use console.warn but then your mobile screen would be flooded with those weird yellow boxes which might or might not be feasible according to your situation.
  3. Most effective method that I came across is to use a third party tool, Reactotron. A simple and easy to configure tool that enables you to see each logging statement of different levels (error, debug, warn, etc.). It provides you with the GUI tool that shows all the logging of your app without slowing down the performance.

Iterate through 2 dimensional array

 //This is The easiest I can Imagine . 
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns 
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

How do I draw a grid onto a plot in Python?

You want to use pyplot.grid:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()

ax.xaxis.grid and ax.yaxis.grid can control grid lines properties.

Enter image description here

What does LINQ return when the results are empty

You can also check the .Any() method:

if (!YourResult.Any())

Just a note that .Any will still retrieve the records from the database; doing a .FirstOrDefault()/.Where() will be just as much overhead but you would then be able to catch the object(s) returned from the query

Use .htaccess to redirect HTTP to HTTPs

Redirect from http to https://www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

This will work for sure!

How do I print a double value with full precision using cout?

How do I print a double value with full precision using cout?

Use hexfloat or
use scientific and set the precision

std::cout.precision(std::numeric_limits<double>::max_digits10 - 1);
std::cout << std::scientific <<  1.0/7.0 << '\n';

// C++11 Typical output
1.4285714285714285e-01

Too many answers address only one of 1) base 2) fixed/scientific layout or 3) precision. Too many answers with precision do not provide the proper value needed. Hence this answer to a old question.

  1. What base?

A double is certainly encoded using base 2. A direct approach with C++11 is to print using std::hexfloat.
If a non-decimal output is acceptable, we are done.

std::cout << "hexfloat: " << std::hexfloat << exp (-100) << '\n';
std::cout << "hexfloat: " << std::hexfloat << exp (+100) << '\n';
// output
hexfloat: 0x1.a8c1f14e2af5dp-145
hexfloat: 0x1.3494a9b171bf5p+144

  1. Otherwise: fixed or scientific?

A double is a floating point type, not fixed point.

Do not use std::fixed as that fails to print small double as anything but 0.000...000. For large double, it prints many digits, perhaps hundreds of questionable informativeness.

std::cout << "std::fixed: " << std::fixed << exp (-100) << '\n';
std::cout << "std::fixed: " << std::fixed << exp (+100) << '\n';
// output
std::fixed: 0.000000
std::fixed: 26881171418161356094253400435962903554686976.000000 

To print with full precision, first use std::scientific which will "write floating-point values in scientific notation". Notice the default of 6 digits after the decimal point, an insufficient amount, is handled in the next point.

std::cout << "std::scientific: " << std::scientific << exp (-100) << '\n';  
std::cout << "std::scientific: " << std::scientific << exp (+100) << '\n';
// output
std::scientific: 3.720076e-44
std::scientific: 2.688117e+43

  1. How much precision (how many total digits)?

A double encoded using the binary base 2 encodes the same precision between various powers of 2. This is often 53 bits.

[1.0...2.0) there are 253 different double,
[2.0...4.0) there are 253 different double,
[4.0...8.0) there are 253 different double,
[8.0...10.0) there are 2/8 * 253 different double.

Yet if code prints in decimal with N significant digits, the number of combinations [1.0...10.0) is 9/10 * 10N.

Whatever N (precision) is chosen, there will not be a one-to-one mapping between double and decimal text. If a fixed N is chosen, sometimes it will be slightly more or less than truly needed for certain double values. We could error on too few (a) below) or too many (b) below).

3 candidate N:

a) Use an N so when converting from text-double-text we arrive at the same text for all double.

std::cout << dbl::digits10 << '\n';
// Typical output
15

b) Use an N so when converting from double-text-double we arrive at the same double for all double.

// C++11
std::cout << dbl::max_digits10 << '\n';
// Typical output
17

When max_digits10 is not available, note that due to base 2 and base 10 attributes, digits10 + 2 <= max_digits10 <= digits10 + 3, we can use digits10 + 3 to insure enough decimal digits are printed.

c) Use an N that varies with the value.

This can be useful when code wants to display minimal text (N == 1) or the exact value of a double (N == 1000-ish in the case of denorm_min). Yet since this is "work" and not likely OP's goal, it will be set aside.


It is usually b) that is used to "print a double value with full precision". Some applications may prefer a) to error on not providing too much information.

With .scientific, .precision() sets the number of digits to print after the decimal point, so 1 + .precision() digits are printed. Code needs max_digits10 total digits so .precision() is called with a max_digits10 - 1.

typedef std::numeric_limits< double > dbl;
std::cout.precision(dbl::max_digits10 - 1);
std::cout << std::scientific <<  exp (-100) << '\n';
std::cout << std::scientific <<  exp (+100) << '\n';
// Typical output
3.7200759760208361e-44
2.6881171418161356e+43
//1234567890123456  17 total digits

Similar C question

The apk must be signed with the same certificates as the previous version

I had faced this issue recently, after trying different ways to sign in like enable V1 Or V2, signed in by changing alias name and last come to know that I am using wrong key store file

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

GenyMotion Unable to start the Genymotion virtual device

Please download new Virtual Box and Install it.

For Download Virtual Box use below link:

https://www.virtualbox.org/wiki/Downloads

These works for me.

Is there a way to iterate over a dictionary?

The block approach avoids running the lookup algorithm for every key:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
  NSLog(@"%@ => %@", key, value);
}];

Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

My measurements show that for a dictionary d of numbers ...

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
  NSNumber* value = @(i);
  dict[value.stringValue] = value;
}

... summing up the numbers with the block approach ...

__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
  sum += value.intValue;
}];

... rather than the loop approach ...

int sum = 0;
for (NSString* key in dict)
  sum += [dict[key] intValue];

... is about 40% faster.

EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

MassAssignmentException in Laravel

Read this section of Laravel doc : http://laravel.com/docs/eloquent#mass-assignment

Laravel provides by default a protection against mass assignment security issues. That's why you have to manually define which fields could be "mass assigned" :

class User extends Model
{
    protected $fillable = ['username', 'email', 'password'];
}

Warning : be careful when you allow the mass assignment of critical fields like password or role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

jQuery ajax call to REST service

I think there is no need to specify

'http://localhost:8080`" 

in the URI part.. because. if you specify it, You'll have to change it manually for every environment.

Only

"/restws/json/product/get" also works

SQL: set existing column as Primary Key in MySQL

Either run in SQL:

ALTER TABLE tableName
  ADD PRIMARY KEY (id)           ---or Drugid, whichever you want it to be PK

or use the PHPMyAdmin interface (Table Structure)

jQuery selector to get form by name

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

How do I Search/Find and Replace in a standard string?

My templatized inline in-place find-and-replace:

template<class T>
int inline findAndReplace(T& source, const T& find, const T& replace)
{
    int num=0;
    typename T::size_t fLen = find.size();
    typename T::size_t rLen = replace.size();
    for (T::size_t pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
        num++;
        source.replace(pos, fLen, replace);
    }
    return num;
}

It returns a count of the number of items substituted (for use if you want to successively run this, etc). To use it:

std::string str = "one two three";
int n = findAndReplace(str, "one", "1");

How can I get a specific number child using CSS?

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

Is it possible to insert HTML content in XML document?

The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.

What are NR and FNR and what does "NR==FNR" imply?

In awk, FNR refers to the record number (typically the line number) in the current file and NR refers to the total record number. The operator == is a comparison operator, which returns true when the two surrounding operands are equal.

This means that the condition NR==FNR is only true for the first file, as FNR resets back to 1 for the first line of each file but NR keeps on increasing.

This pattern is typically used to perform actions on only the first file. The next inside the block means any further commands are skipped, so they are only run on files other than the first.

The condition FNR==NR compares the same two operands as NR==FNR, so it behaves in the same way.

Write variable to a file in Ansible

An important comment from tmoschou:

As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.

For more details see this and an explanation


Original answer:

You could use the copy module, with the content parameter:

- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file

The docs here: copy module

Subset data to contain only columns whose names match a condition

Just in case for data.table users, the following works for me:

df[, grep("ABC", names(df)), with = FALSE]

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

Redis command to get all available keys?

Take a look at following Redis Cheat Sheet. To get a subset of redis keys with the redis-cli i use the command

KEYS "prefix:*"

Simulating ENTER keypress in bash script

Here is sample usage using expect:

#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }

Check: man expect for further information.

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

Setting the height of a DIV dynamically

If I understand what you're asking, this should do the trick:

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use 
// window.innerWidth and window.innerHeight

var windowHeight;

if (typeof window.innerWidth != 'undefined')
{
    windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first 
// line in the document)
else if (typeof document.documentElement != 'undefined'
        && typeof document.documentElement.clientWidth != 'undefined' 
        && document.documentElement.clientWidth != 0)
{
    windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
    windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}

document.getElementById("yourDiv").height = windowHeight - 300 + "px";

Correctly determine if date string is a valid date in that format

Accordling with cl-sah's answer, but this sound better, shorter...

function checkmydate($date) {
  $tempDate = explode('-', $date);
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false

Get Enum from Description attribute

rather than extension methods, just try a couple of static methods

public static class Utility
{
    public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

    public static T GetEnumValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields
                        .SelectMany(f => f.GetCustomAttributes(
                            typeof(DescriptionAttribute), false), (
                                f, a) => new { Field = f, Att = a })
                        .Where(a => ((DescriptionAttribute)a.Att)
                            .Description == description).SingleOrDefault();
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }
}

and use here

var result1 = Utility.GetDescriptionFromEnumValue(
    Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
    "Lesser Spotted Anteater");

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

grep a file, but show several surrounding lines?

Grep has an option called Context Line Control, you can use the --context in that, simply,

| grep -C 5

or

| grep -5

Should do the trick

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

MySQL: Enable LOAD DATA LOCAL INFILE

In case if Mysql 5.7 you can use "show global variables like "local_infile" ;" which will give the local infile status ,You can turn it on using "set global local_infile=ON ; ".

Checking if a website is up via Python

If by up, you simply mean "the server is serving", then you could use cURL, and if you get a response than it's up.

I can't give you specific advice because I'm not a python programmer, however here is a link to pycurl http://pycurl.sourceforge.net/.

Get keys of a Typescript interface as array of strings

This should work

var IMyTable: Array<keyof IMyTable> = ["id", "title", "createdAt", "isDeleted"];

or

var IMyTable: (keyof IMyTable)[] = ["id", "title", "createdAt", "isDeleted"];

How to set UITextField height?

CGRect frameRect = textField.frame;
frameRect.size.height = 100; // <-- Specify the height you want here.
textField.frame = frameRect;

How to unzip a file in Powershell?

ForEach Loop processes each ZIP file located within the $filepath variable

    foreach($file in $filepath)
    {
        $zip = $shell.NameSpace($file.FullName)
        foreach($item in $zip.items())
        {
            $shell.Namespace($file.DirectoryName).copyhere($item)
        }
        Remove-Item $file.FullName
    }

Hover and Active only when not disabled

If you are using LESS or Sass, You can try this:

.btn {
  &[disabled] {
    opacity: 0.6;
  }
  &:hover, &:active {
    &:not([disabled]) {
      background-color: darken($orange, 15);
    }
  }
}

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

sys.argv[1] meaning in script

sys.argv[1] contains the first command line argument passed to your script.

For example, if your script is named hello.py and you issue:

$ python3.1 hello.py foo

or:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

Your script will print:

Hello there foo

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Not going to be everyone's fix, but it was for me:

So, i ran across this exact issue. The problem I seemed to have was when my DataTable didnt have an ID column, but the target destination had one with a primary key.

When i adapted my DataTable to have an id, the copy worked perfectly.

In my scenario, the Id column isnt very important to have the primary key so i deleted this column from the target destination table and the SqlBulkCopy is working without issue.

How to change package name in flutter?

For Android App Name

Change the label name in your AndroidManifest.xml file:

 <application
    android:name="io.flutter.app.FlutterApplication"
    android:label="TheNameOfYourApp"   

For Package Name

Change the package name in your AndroidManifest.xml (in 3 of them, folders: main, debug and profile, according what environment you want to deploy) file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.package.name">

Also in your build.gradle file inside app folder

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Finally, change the package in your MainActivity.java class (if the MainActivity.java is not available, check the MainActivity.kt)

    package your.package.name;

    import android.os.Bundle;
    import io.flutter.app.FlutterActivity;
    import io.flutter.plugins.GeneratedPluginRegistrant;
    public class MainActivity extends FlutterActivity {

Change the directory name:

From:

  android\app\src\main\java\com\example\name

To:

  android\app\src\main\java\your\package\name
  

EDITED : 27-Dec-18

for package name just change in build build.gradle only

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

For iOS

Change the bundle identifier from your Info.plist file inside your ios/Runner directory.

<key>CFBundleIdentifier</key>
<string>com.your.packagename</string>

UPDATE

To avoid renaming the package and bundle identifier, you can start your project using this command in your terminal:

flutter create --org com.yourdomain appname

How do I implement basic "Long Polling"?

It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).

Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)

msgsrv.php

<?php
if(rand(1,3) == 1){
    /* Fake an error */
    header("HTTP/1.0 404 Not Found");
    die();
}

/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>

Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)

Then, in Javascript, you request the above file (msg_srv.php), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)

What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php file.. If it succeeds, we append the message to the #messages div, then after 1 second we call the waitForMsg function again, which triggers the wait.

The 1 second setTimeout() is a really basic rate-limiter, it works fine without this, but if msgsrv.php always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.

If the page errors, it appends the error to the #messages div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)

The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required

Anyway, the long_poller.htm code, using the jQuery framework:

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>

    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>

How to extract base URL from a string in JavaScript?

If you're using jQuery, this is a kinda cool way to manipulate elements in javascript without adding them to the DOM:

var myAnchor = $("<a />");

//set href    
myAnchor.attr('href', 'http://example.com/path/to/myfile')

//your link's features
var hostname = myAnchor.attr('hostname'); // http://example.com
var pathname = myAnchor.attr('pathname'); // /path/to/my/file
//...etc

Visual Studio Copy Project

After trying above solutions & creating copy for MVC projects

For MVC projects please update the port numbers in .csproj file, you can take help of iis applicationhost.config to check the port numbers. Same port numbers will cause assembly loading issue in IIS.

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

Error message: "'chromedriver' executable needs to be available in the path"

In my case, this error disappears when I have copied chromedriver file to c:\Windows folder. Its because windows directory is in the path which python script check for chromedriver availability.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

How can I give the Intellij compiler more heap space?

In my case the error was caused by the insufficient memory allocated to the "test" lifecycle of maven. It was fixed by adding <argLine>-Xms3512m -Xmx3512m</argLine> to:

<pluginManagement>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
            <argLine>-Xms3512m -Xmx3512m</argLine>

Thanks @crazycoder for pointing this out (and also that it is not related to IntelliJ; in this case).

If your tests are forked, they run in a new JVM that doesn't inherit Maven JVM options. Custom memory options must be provided via the test runner in pom.xml, refer to Maven documentation for details, it has very little to do with the IDE.

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

Popup window in PHP?

PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.

So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.

How to install pywin32 module in windows 7

You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:

pip install pypiwin32

Currently I think this is "the easiest" way to get in working :) Hope this helps.

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

'<option value=''.$key.'">'

should be

'<option value="'.$key.'">'

How do I run git log to see changes only for a specific branch?

Assuming that your branch was created off of master, then while in the branch (that is, you have the branch checked out):

git cherry -v master

or

git log master..

If you are not in the branch, then you can add the branch name to the "git log" command, like this:

git log master..branchname

If your branch was made off of origin/master, then say origin/master instead of master.

Stop setInterval

we can easily stop the set interval by calling clear interval

var count = 0 , i = 5;
var vary = function intervalFunc() {
  count++;
      console.log(count);
    console.log('hello boy');  
    if (count == 10) {
      clearInterval(this);
    }
}

  setInterval(vary, 1500);

How to get the current date and time of your timezone in Java?

I couldn't get it to work using Calendar. You have to use DateFormat

//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());

//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());

//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());

How to print float to n decimal places including trailing 0s?

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

How to pass ArrayList<CustomeObject> from one activity to another?

Use this code to pass arraylist<customobj> to anthother Activity

firstly serialize our contact bean

public class ContactBean implements Serializable {
      //do intialization here
}

Now pass your arraylist

 Intent intent = new Intent(this,name of activity.class);
 contactBean=(ConactBean)_arraylist.get(position);
 intent.putExtra("contactBeanObj",conactBean);
 _activity.startActivity(intent);

How to handle change of checkbox using jQuery?

Hope, this would be of some help.

$('input[type=checkbox]').change(function () {
    if ($(this).prop("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

Create dataframe from a matrix

You can use stack from the base package. But, you need first to coerce your matrix to a data.frame and to reorder the columns once the data is stacked.

mat <- as.data.frame(mat)
res <- data.frame(time= mat$time,stack(mat,select=-time))
res[,c(3,1,2)]

  ind time values
1 C_0  0.0    0.1
2 C_0  0.5    0.2
3 C_0  1.0    0.3
4 C_1  0.0    0.3
5 C_1  0.5    0.4
6 C_1  1.0    0.5

Note that stack is generally more efficient than the reshape2 package.

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

If you are looking for Swift 3, Follow the steps to achieve this:

func viewDidLoad() {

    //Define Layout here
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    //Get device width
    let width = UIScreen.main.bounds.width

    //set section inset as per your requirement.
    layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

    //set cell item size here 
    layout.itemSize = CGSize(width: width / 2, height: width / 2)

    //set Minimum spacing between 2 items
    layout.minimumInteritemSpacing = 0

    //set minimum vertical line spacing here between two lines in collectionview
    layout.minimumLineSpacing = 0

    //apply defined layout to collectionview
    collectionView!.collectionViewLayout = layout

}

This is verified on Xcode 8.0 with Swift 3.

openssl s_client using a proxy

for anyone coming here as of post-May 2015: there's a new "-proxy" option that will be included in the next release of openssl: https://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

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

you can also use jquery for this

  var phoneNumber = 8882070980;
            var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;

            if (filter.test(phoneNumber)) {
              if(phoneNumber.length==10){
                   var validate = true;
              } else {
                  alert('Please put 10  digit mobile number');
                  var validate = false;
              }
            }
            else {
              alert('Not a valid number');
              var validate = false;
            }

         if(validate){
          //number is equal to 10 digit or number is not string 
          enter code here...
        }

How to hide a <option> in a <select> menu with CSS?

// Simplest way

var originalContent = $('select').html();

$('select').change(function() {
    $('select').html(originalContent); //Restore Original Content
    $('select option[myfilter=1]').remove(); // Filter my options
});

How to determine whether a substring is in a different string

Can also use this method

if substring in string:
    print(string + '\n Yes located at:'.format(string.find(substring)))

How to convert java.lang.Object to ArrayList?

The conversion fails (java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList) because you have surely some objects that are not ArrayList. verify the types of your different objects.

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

Disable same origin policy in Chrome

For Windows:

(using windows 8.1, chrome 44.0)

First, close google chrome.

Then, open command prompt and go to the folder where 'chrome.exe' is.

( for me: 'chrome.exe' is here "C:\Program Files (x86)\Google\Chrome\Application".

So I type: cd C:\Program Files (x86)\Google\Chrome\Application )

now type: chrome.exe --disable-web-security

a new window of chrome will open.

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

MAX function in where clause mysql

You are using word 'max' as an alias for your column. Try to:

MAX(id) as mymax ... WHERE ID - mymax

Serialize object to query string in JavaScript/jQuery

Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

For example:

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

Use string.Contains() with switch()

Stegmenn nalied it for me but I had one change for when you have an IEnumerbale instead of a string = message like in his example.

private static string GetRoles(IEnumerable<External.Role> roles)
    {
            string[] switchStrings = { "Staff", "Board Member" };
            switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
            {
                case
                    "Staff":
                    roleNameValues += "Staff,";
                    break;
                case
                    "Board Member":
                    roleNameValues += "Director,";
                    break;
                default:
                    break;
            }

Exporting data In SQL Server as INSERT INTO

Just updating screenshots to help others as I am using a newer v18, circa 2019.

Right click DB: Tasks > Generate Scripts

Here you can select certain tables or go with the default of all.

Here you can select certain tables or go with the default of all. For my own needs I'm indicating just the one table.

Next, there's the "Scripting Options" where you can choose output file, etc. As in multiple answers above (again, I'm just dusting off old answers for newer, v18.4 SQL Server Management Studio) what we're really wanting is under the "Advanced" button. For my own purposes, I need just the data.

General output options, including output to file. Advanced options including data!

Finally, there's a review summary before execution. After executing a report of operations' status is shown. Review summary.

Integrating CSS star rating into an HTML form

CSS:

.rate-container > i {
    float: right;
}

.rate-container > i:HOVER,
.rate-container > i:HOVER ~ i {
    color: gold;
}

HTML:

<div class="rate-container">
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
</div>

jQuery get the location of an element relative to window

Initially, Grab the .offset position of the element and calculate its relative position with respect to window

Refer :
1. offset
2. scroll
3. scrollTop

You can give it a try at this fiddle

Following few lines of code explains how this can be solved

when .scroll event is performed, we calculate the relative position of the element with respect to window object

$(window).scroll(function () {
    console.log(eTop - $(window).scrollTop());
});

when scroll is performed in browser, we call the above event handler function

code snippet


_x000D_
_x000D_
function log(txt) {_x000D_
  $("#log").html("location : <b>" + txt + "</b> px")_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  var eTop = $('#element').offset().top; //get the offset top of the element_x000D_
  log(eTop - $(window).scrollTop()); //position of the ele w.r.t window_x000D_
_x000D_
  $(window).scroll(function() { //when window is scrolled_x000D_
    log(eTop - $(window).scrollTop());_x000D_
  });_x000D_
});
_x000D_
#element {_x000D_
  margin: 140px;_x000D_
  text-align: center;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  border: 1px solid #0099f9;_x000D_
  border-radius: 3px;_x000D_
  background: #444;_x000D_
  color: #0099d9;_x000D_
  opacity: 0.6;_x000D_
}_x000D_
#log {_x000D_
  position: fixed;_x000D_
  top: 40px;_x000D_
  left: 40px;_x000D_
  color: #333;_x000D_
}_x000D_
#scroll {_x000D_
  position: fixed;_x000D_
  bottom: 10px;_x000D_
  right: 10px;_x000D_
  border: 1px solid #000;_x000D_
  border-radius: 2px;_x000D_
  padding: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="log"></div>_x000D_
_x000D_
<div id="element">Hello_x000D_
  <hr>World</div>_x000D_
<div id="scroll">Scroll Down</div>
_x000D_
_x000D_
_x000D_

How to pass extra variables in URL with WordPress

One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.

See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.

What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.

add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );

function add_custom_setcookie_rewrite_endpoints() {
    //add ?c=123 endpoint with
    //EP_ALL so endpoint is present across all places
    //no effect on the query vars
    add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}

This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.

Remember to flush your rewrite rules after adding/modifying this.

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

Check if a Bash array contains a value

for i in "${array[@]}"
do
    if [ "$i" -eq "$yourValue" ] ; then
        echo "Found"
    fi
done

For strings:

for i in "${array[@]}"
do
    if [ "$i" == "$yourValue" ] ; then
        echo "Found"
    fi
done

How to style the option of an html "select" element?

You can add a class and gives font-weight:700; in option. But by using this all the text will become bold.

Flutter Countdown Timer

Countdown timer in one line

CountdownTimer(Duration(seconds: 5), Duration(seconds: 1)).listen((data){
})..onData((data){
  print('data $data');
})..onDone((){
  print('onDone.........');
});

How to disable button in React.js

Using refs is not best practice because it reads the DOM directly, it's better to use React's state instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.

You can use setState together with an onChange event listener to render the component again every time the input field changes:

// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />

// Button is disabled when input state is empty.
<button disabled={!this.state.value} />

Here's a working example:

_x000D_
_x000D_
class AddItem extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { value: '' };_x000D_
    this.onChange = this.onChange.bind(this);_x000D_
    this.add = this.add.bind(this);_x000D_
  }_x000D_
_x000D_
  add() {_x000D_
    this.props.onButtonClick(this.state.value);_x000D_
    this.setState({ value: '' });_x000D_
  }_x000D_
_x000D_
  onChange(e) {_x000D_
    this.setState({ value: e.target.value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="add-item">_x000D_
        <input_x000D_
          type="text"_x000D_
          className="add-item__input"_x000D_
          value={this.state.value}_x000D_
          onChange={this.onChange}_x000D_
          placeholder={this.props.placeholder}_x000D_
        />_x000D_
        <button_x000D_
          disabled={!this.state.value}_x000D_
          className="add-item__button"_x000D_
          onClick={this.add}_x000D_
        >_x000D_
          Add_x000D_
        </button>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,_x000D_
  document.getElementById('View')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id='View'></div>
_x000D_
_x000D_
_x000D_

Is there an embeddable Webkit component for Windows / C# development?

Haven't tried yet but found WebKit.NET on SourceForge. It was moved to GitHub.

Warning: Not maintained anymore, last commits are from early 2013

Best Way to Refresh Adapter/ListView on Android

If you are using LoaderManager try with this statement:

getLoaderManager().restartLoader(0, null, this);

How do I display a MySQL error in PHP for a long query that depends on the user input?

Use this:

mysqli_query($this->db_link, $query) or die(mysqli_error($this->db_link)); 
# mysqli_query($link,$query) returns 0 if there's an error.
# mysqli_error($link) returns a string with the last error message

You can also use this to print the error code.

echo mysqli_errno($this->db_link);

Take a look here and here

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

Sqlite in chrome

I'm not quite sure if you mean 'can i use sqlite (websql) in chrome' or 'can i use sqlite (websql) in firefox', so I'll answer both:

Note that WebSQL is not a full-access pipe into an .sqlite database. It's WebSQL. You will not be able to run some specific queries like VACUUM

It's awesome for Create / Read / Update / Delete though. I made a little library that helps with all the annoying nitty gritty like creating tables and querying and a provides a little ORM/ActiveRecord pattern with relations and all and a huge stack of examples that should get you started in no-time, you can check that here

Also, be aware that if you want to build a FireFox extension: Their extension format is about to change. Make sure you want to invest the time twice.

While the WebSQL spec has been deprecated for years, even now in 2017 still does not look like it will be be removed from Chrome for the foreseeable time. They are tracking usage statistics and there are still a large number of chrome extensions and websites out there in the real world implementing the spec.

What is the difference between single and double quotes in SQL?

The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.

When you want to use an alias that has space in between then you can use double quotes to refer to that alias.

For example

(select account_id,count(*) "count of" from orders group by 1)sub 

Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.

Now let's write an outer query to display the rows where "count of" is greater than 20.

select "count of" from 
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;

You can apply the same case to Common Table expressions also.

Resize image in the wiki of GitHub using Markdown

GitHub Pages now uses kramdown as its markdown engine so you can use the following syntax:

Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.

http://kramdown.gettalong.org/syntax.html#images

I haven't tested it on GitHub wiki though.

PHP Session timeout

    session_cache_expire( 20 );
    session_start(); // NEVER FORGET TO START THE SESSION!!!
    $inactive = 1200; //20 minutes *60
    if(isset($_SESSION['start']) ) {
$session_life = time() - $_SESSION['start'];
if($session_life > $inactive){
    header("Location: user_logout.php");
}
    }
    $_SESSION['start'] = time();

    if($_SESSION['valid_user'] != true){
    header('Location: ../....php');
    }else{  

source: http://www.daniweb.com/web-development/php/threads/124500

Getting value of select (dropdown) before change

There are several ways to achieve your desired result, this my humble way of doing it:

Let the element hold its previous value, so add an attribute 'previousValue'.

<select id="mySelect" previousValue=""></select>

Once initialized, 'previousValue' could now be used as an attribute. In JS, to access the previousValue of this select:

$("#mySelect").change(function() {console.log($(this).attr('previousValue'));.....; $(this).attr('previousValue', this.value);}

After you are done using 'previousValue', update the attribute to current value.

how to write an array to a file Java

private static void saveArrayToFile(String fileName, int[] array) throws IOException {
    Files.write( // write to file
        Paths.get(fileName), // get path from file
        Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
        Charset.forName("UTF-8") // formatting
    );
}

How to prettyprint a JSON file?

It's far from perfect, but it does the job.

data = data.replace(',"',',\n"')

you can improve it, add indenting and so on, but if you just want to be able to read a cleaner json, this is the way to go.

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes lists and tuples are always ordered while dictionaries are not

How to include !important in jquery

var tabsHeight = 650;

$("tabs").attr('style', 'height: '+ tabsHeight +'px !important');

OR

#CSS
.myclass{height:650px !important;}

then

$("tabs").addClass("myclass");

How to convert hex string to Java string?

Using Hex in Apache Commons:

String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";    
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));

How to "log in" to a website using Python's Requests module?

I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:

Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.

Once you've got that, you can use a requests.Session() instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.

Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.

Example

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'inUserName': 'username',
    'inUserPass': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post('LOGIN_URL', data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    r = s.get('A protected web page url')
    print r.text
        # etc...

Getting the Username from the HKEY_USERS values

for /f "tokens=8 delims=\" %a in ('reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist" ^| find "UsrClass.dat"') do echo %a

What's the difference between equal?, eql?, ===, and ==?

I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.

Side note: if you want to try these out for yourself on different objects, use something like this:

class Object
  def all_equals(o)
    ops = [:==, :===, :eql?, :equal?]
    Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })]
  end
end

"a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}

== — generic "equality"

At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.

=== — case equality

For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

This is incredibly useful. Examples of things which have interesting === implementations:

  • Range
  • Regex
  • Proc (in Ruby 1.9)

So you can do things like:

case some_object
when /a regex/
  # The regex matches
when 2..4
  # some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
  # the lambda returned true
end

See my answer here for a neat example of how case+Regex can make code a lot cleaner. And of course, by providing your own === implementation, you can get custom case semantics.

eql?Hash equality

The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

So you're free to override this for your own uses, or you can override == and use alias :eql? :== so the two methods behave the same way.

equal? — identity comparison

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

This is effectively pointer comparison.

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

You are using prettyfaces too? Then set dispatcher to FORWARD:

<filter-mapping>
   <filter-name>PrimeFaces FileUpload Filter</filter-name>
   <servlet-name>Faces Servlet</servlet-name>
   <dispatcher>FORWARD</dispatcher>
</filter-mapping>

How do I create an Android Spinner as a popup?

You can use an alert dialog

    AlertDialog.Builder b = new Builder(this);
    b.setTitle("Example");
    String[] types = {"By Zip", "By Category"};
    b.setItems(types, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
            switch(which){
            case 0:
                onZipRequested();
                break;
            case 1:
                onCategoryRequested();
                break;
            }
        }

    });

    b.show();

This will close the dialog when one of them is pressed like you are wanting. Hope this helps!

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

I also had the same problem with bson.

trying a newer mongoose version

npm install [email protected]

solved the issue.

Massimo.

How to detect the currently pressed key?

if ((Control.ModifierKeys & Keys.Shift) != 0) 

This will also be true if Ctrl+Shift is down. If you want to check whether Shift alone is pressed,

if (Control.ModifierKeys == Keys.Shift)

If you're in a class that inherits Control (such as a form), you can remove the Control.

Maven: Failed to read artifact descriptor

I solved this issue by deleting in the repository folders where this error was shown everything except the .jar and .pom files.

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

Can we call the function written in one JavaScript in another JS file?

Well, I came across another sweet solution.

window['functioName'](params);

form with no action and where enter does not reload page

Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:

onKeyPress="if (event.which == 13) return false;"

For example:

<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>

'cl' is not recognized as an internal or external command,

I had the same problem and I solved it by switching to MinGW from MSVC2010.

Select the Project Tab from your left pane. Then select the "Target". From there change Qt version to MinGW instead of VC++.

How to place div side by side

There are many ways to do what you're asking for:

  1. Using CSS float property:

_x000D_
_x000D_
 <div style="width: 100%; overflow: hidden;">
     <div style="width: 600px; float: left;"> Left </div>
     <div style="margin-left: 620px;"> Right </div>
</div>
_x000D_
_x000D_
_x000D_

  1. Using CSS display property - which can be used to make divs act like a table:

_x000D_
_x000D_
<div style="width: 100%; display: table;">
    <div style="display: table-row">
        <div style="width: 600px; display: table-cell;"> Left </div>
        <div style="display: table-cell;"> Right </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

There are more methods, but those two are the most popular.

How to modify existing, unpushed commit messages?

If you have to change an old commit message over multiple branches (i.e., the commit with the erroneous message is present in multiple branches) you might want to use:

git filter-branch -f --msg-filter \
'sed "s/<old message>/<new message>/g"' -- --all

Git will create a temporary directory for rewriting and additionally backup old references in refs/original/.

  • -f will enforce the execution of the operation. This is necessary if the temporary directory is already present or if there are already references stored under refs/original. If that is not the case, you can drop this flag.

  • -- separates filter-branch options from revision options.

  • --all will make sure that all branches and tags are rewritten.

Due to the backup of your old references, you can easily go back to the state before executing the command.

Say, you want to recover your master and access it in branch old_master:

git checkout -b old_master refs/original/refs/heads/master

Determine the type of an object?

While the questions is pretty old, I stumbled across this while finding out a proper way myself, and I think it still needs clarifying, at least for Python 2.x (did not check on Python 3, but since the issue arises with classic classes which are gone on such version, it probably doesn't matter).

Here I'm trying to answer the title's question: how can I determine the type of an arbitrary object? Other suggestions about using or not using isinstance are fine in many comments and answers, but I'm not addressing those concerns.

The main issue with the type() approach is that it doesn't work properly with old-style instances:

class One:
    pass

class Two:
    pass


o = One()
t = Two()

o_type = type(o)
t_type = type(t)

print "Are o and t instances of the same class?", o_type is t_type

Executing this snippet would yield:

Are o and t instances of the same class? True

Which, I argue, is not what most people would expect.

The __class__ approach is the most close to correctness, but it won't work in one crucial case: when the passed-in object is an old-style class (not an instance!), since those objects lack such attribute.

This is the smallest snippet of code I could think of that satisfies such legitimate question in a consistent fashion:

#!/usr/bin/env python
from types import ClassType
#we adopt the null object pattern in the (unlikely) case
#that __class__ is None for some strange reason
_NO_CLASS=object()
def get_object_type(obj):
    obj_type = getattr(obj, "__class__", _NO_CLASS)
    if obj_type is not _NO_CLASS:
        return obj_type
    # AFAIK the only situation where this happens is an old-style class
    obj_type = type(obj)
    if obj_type is not ClassType:
        raise ValueError("Could not determine object '{}' type.".format(obj_type))
    return obj_type

How to run multiple Python versions on Windows

cp c:\python27\bin\python.exe as python2.7.exe

cp c:\python34\bin\python.exe as python3.4.exe

they are all in the system path, choose the version you want to run

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

Passing data to a bootstrap modal

This is so easy with jquery:

If below is your anchor link:

<a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>

In the show event of your modal you can access to the anchor tag like below

//triggered when modal is shown
$('#modal_id').on('shown.bs.modal', function(event) {

    // The reference tag is your anchor tag here
    var reference_tag = $(event.relatedTarget); 
    var id = reference_tag.data('id')
    // ...
    // ...
})


How to set the title text color of UIButton?

Swift UI solution

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))

Swift 3, Swift 4, Swift 5

to improve comments. This should work:

button.setTitleColor(.red, for: .normal)

Sort a two dimensional array based on one column

Using Lambdas since java 8:

final String[][] data = new String[][] { new String[] { "2009.07.25 20:24", "Message A" },
        new String[] { "2009.07.25 20:17", "Message G" }, new String[] { "2009.07.25 20:25", "Message B" },
        new String[] { "2009.07.25 20:30", "Message D" }, new String[] { "2009.07.25 20:01", "Message F" },
        new String[] { "2009.07.25 21:08", "Message E" }, new String[] { "2009.07.25 19:54", "Message R" } };
String[][] out = Arrays.stream(data).sorted(Comparator.comparing(x -> x[1])).toArray(String[][]::new);

System.out.println(Arrays.deepToString(out));
    

Output:

[[2009.07.25 20:24, Message A], [2009.07.25 20:25, Message B], [2009.07.25 20:30, Message D], [2009.07.25 21:08, Message E], [2009.07.25 20:01, Message F], [2009.07.25 20:17, Message G], [2009.07.25 19:54, Message R]]

How to set the margin or padding as percentage of height of parent container?

An answer to a slightly different question: You can use vh units to pad elements to the center of the viewport:

.centerme {
    margin-top: 50vh;
    background: red;
}

<div class="centerme">middle</div>

BEGIN - END block atomic transactions in PL/SQL

BEGIN-END blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN-END blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.

If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.

However, you cannot declare this pragma for nested blocks. You can only declare this for:

  • Top-level (not nested) anonymous PL/SQL blocks
  • List item
  • Local, standalone, and packaged functions and procedures
  • Methods of a SQL object type
  • Database triggers

Reference: Oracle

Could not connect to React Native development server on Android

Make sure NPM server is running. Else run it again. It will solve the issue.

How to change button text or link text in JavaScript?

document.getElementById(button_id).innerHTML = 'Lock';

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths

From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).

More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.

Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.

Submit form on pressing Enter with AngularJS

Use ng-submit and just wrap both inputs in separate form tags:

<div ng-controller="mycontroller">

  <form ng-submit="myFunc()">
    <input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
  </form>

  <br />

  <form ng-submit="myFunc()">
    <input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
  </form>

</div>

Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.

How can I issue a single command from the command line through sql plus?

I'm able to run an SQL query by piping it to SQL*Plus:

@echo select count(*) from table; | sqlplus username/password@database

Give

@echo execute some_procedure | sqlplus username/password@databasename

a try.

TreeMap sort by value

import java.util.*;

public class Main {

public static void main(String[] args) {
    TreeMap<String, Integer> initTree = new TreeMap();
    initTree.put("D", 0);
    initTree.put("C", -3);
    initTree.put("A", 43);
    initTree.put("B", 32);
    System.out.println("Sorted by keys:");
    System.out.println(initTree);
    List list = new ArrayList(initTree.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override
        public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
            return e1.getValue().compareTo(e2.getValue());
        }
    });
    System.out.println("Sorted by values:");
    System.out.println(list);
}
}

How to execute a JavaScript function when I have its name as a string

Depending on where you are you can also use:

this["funcname"]();
self["funcname"]();
window["funcname"]();
top["funcname"]();
globalThis["funcname"]();

or, in nodejs

global["funcname"]()

Early exit from function?

function myfunction() {
     if(a == 'stop') 
         return false;
}

return false; is much better than just return;

How to compute the sum and average of elements in an array?

Here is a quick addition to the “Math” object in javascript to add a “average” command to it!!

Math.average = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output/input.length;
}

Then i have this addition to the “Math” object for getting the sum!

Math.sum = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output;
}

So then all you do is

alert(Math.sum([5,5,5])); //alerts “15”
alert(Math.average([10,0,5])); //alerts “5”

And where i put the placeholder array just pass in your variable (The input if they are numbers can be a string because of it parsing to a number!)

How to call multiple JavaScript functions in onclick event?

You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.

<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>

or you can put the composition as a seperate function in js file and call it

const newFunction = R.compose(fn1,fn2,fn3);


<a href="#" onclick="newFunction()">Click me To fire some functions</a>

Get text from DataGridView selected cells

Private Sub DataGridView1_CellClick(ByVal sender As System.Object, _
                                    ByVal e As DataGridViewCellEventArgs) _
                                    Handles DataGridView1.CellClick
    MsgBox(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
End Sub

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

You can access this by

Right click on instance (IE SQLServer2008)
Select "Properties"
Select "Security" option
Change "Server authentication" to "SQL Server and Windows Authentication mode"
Restart the SQLServer service
    Right click on instance
    Click "Restart"

Just for anyone else reading this: This worked for me on 2012 SQL Server too. Thanks

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.

Getting the last n elements of a vector. Is there a better way than using the length() function?

The disapproval of tail here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n, the number of elements you want to subset out:

x <- 1:10
tail(x, 20)
# [1]  1  2  3  4  5  6  7  8  9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] : 
#  only 0's may be mixed with negative subscripts

Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.

Why is the GETDATE() an invalid identifier

I think you want SYSDATE, not GETDATE(). Try it:

UPDATE TableName SET LastModifiedDate = (SELECT SYSDATE FROM DUAL);

How to suppress "unused parameter" warnings in C?

A gcc/g++ specific way to suppress the unused parameter warning for a block of source code is to enclose it with the following pragma statements:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
<code with unused parameters here>
#pragma GCC diagnostic pop

Can't concatenate 2 arrays in PHP

This works for non-associative arrays:

while(($item = array_shift($array2)) !== null && array_push($array1, $item));

Change private static final field using Java reflection

In case of presence of a Security Manager, one can make use of AccessController.doPrivileged

Taking the same example from accepted answer above:

import java.lang.reflect.*;

public class EverythingIsTrue {
    static void setFinalStatic(Field field, Object newValue) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");

        // wrapping setAccessible 
        AccessController.doPrivileged(new PrivilegedAction() {
            @Override
            public Object run() {
                modifiersField.setAccessible(true);
                return null;
            }
        });

        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, newValue);
    }

    public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);
      System.out.format("Everything is %s", false); // "Everything is true"
    }
}

In lambda expression, AccessController.doPrivileged, can be simplified to:

AccessController.doPrivileged((PrivilegedAction) () -> {
    modifiersField.setAccessible(true);
    return null;
});

subtract time from date - moment js

Moment.subtract does not support an argument of type Moment - documentation:

moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);

The simplest solution is to specify the time delta as an object:

// Assumes string is hh:mm:ss
var myString = "03:15:00",
    myStringParts = myString.split(':'),
    hourDelta: +myStringParts[0],
    minuteDelta: +myStringParts[1];


date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

WHERE MyColumn = COALESCE(@value,MyColumn) 
  • If @value is NULL, it will compare MyColumn to itself, ignoring @value = no where clause.

  • IF @value has a value (NOT NULL) it will compare MyColumn to @value.

Reference: COALESCE (Transact-SQL).

how to split the ng-repeat data with three columns using bootstrap

Here's an easy-hacky way of doing it. It's more manual and ends up with messy markup. I do not recommend this, but there are situations where this might be useful.

Here's a fiddle link http://jsfiddle.net/m0nk3y/9wcbpydq/

HTML:

<div ng-controller="myController">
    <div class="row">
        <div class="col-sm-4">
            <div class="well">
                <div ng-repeat="person in people = data | limitTo:Math.ceil(data.length/3)">
                {{ person.name }}
                </div>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="well">
                <div ng-repeat="person in people = data | limitTo:Math.ceil(data.length/3):Math.ceil(data.length/3)">
                {{ person.name }}
                </div>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="well">
                <div ng-repeat="person in people = data | limitTo:Math.ceil(data.length/3):Math.ceil(data.length/3)*2">
                {{ person.name }}
                </div>
            </div>
        </div>
    </div>
</div>

JS:

var app = angular.module('myApp', []);

app.controller('myController', function($scope) {

    $scope.Math = Math;
    $scope.data = [
        {"name":"Person A"},
        ...
    ];
});

This setup requires us to use some Math on the markup :/, so you'll need to inject Math by adding this line: $scope.Math = Math;

Can a background image be larger than the div itself?

Not really - the background image is bounded by the element it's applied to, and the overflow properties only apply to the content (i.e. markup) within an element.

You can add another div into your footer div and apply the background image to that, though, and have that overflow instead.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

The problem arose because you added the following code as request header in your front-end :

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Those headers belong to response, not request. So remove them, including the line :

headers.append('GET', 'POST', 'OPTIONS');

Your request had 'Content-Type: application/json', hence triggered what is called CORS preflight. This caused the browser sent the request with OPTIONS method. See CORS preflight for detailed information.

Therefore in your back-end, you have to handle this preflighted request by returning the response headers which include :

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, OPTIONS
Access-Control-Allow-Headers : Origin, Content-Type, Accept

Of course, the actual syntax depends on the programming language you use for your back-end.

In your front-end, it should be like so :

function performSignIn() {
    let headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic ' + base64.encode(username + ":" +  password));
    headers.append('Origin','http://localhost:3000');

    fetch(sign_in, {
        mode: 'cors',
        credentials: 'include',
        method: 'POST',
        headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

$.focus() not working

I tested code from Chrome's DevTool Console and the focus part not worked. I found out later the issue is only present if i run it from DevTool and if i implement the code to the website it works fine. Actually, the element got focused but the DevTool removed it immediately.

How to fix "containing working copy admin area is missing" in SVN?

According to this: http://www.devcha.com/2008/03/svn-directory-svn-containing-working.html

Check-out the folder "blabla" to a different location and then copy its .svn folder back into the original "blabla".

Ripple effect on Android Lollipop CardView

  android:foreground="?android:attr/selectableItemBackgroundBorderless"
   android:clickable="true"
   android:focusable="true"

Only working api 21 and use this not use this list row card view

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Hope this helps but please let me know if you need more details.

Real mouse position in canvas

The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:

canvas.addEventListener('click', event =>
{
    let bound = canvas.getBoundingClientRect();

    let x = event.clientX - bound.left - canvas.clientLeft;
    let y = event.clientY - bound.top - canvas.clientTop;

    context.fillRect(x, y, 16, 16);
});

If the canvas has padding-left or padding-top, subtract x and y via:

x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));

Java: How to convert a File object to a String object in java?

With Java 7, it's as simple as:

final String EoL = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(fileName),
        Charset.defaultCharset());

StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append(line).append(EoL);
}
final String content = sb.toString();

However, it does havea few minor caveats (like handling files that does not fit into the memory).

I would suggest taking a look on corresponding section in the official Java tutorial (that's also the case if you have a prior Java).

As others pointed out, you might find sime 3rd party libraries useful (like Apache commons I/O or Guava).

Use of the MANIFEST.MF file in Java

Manifest.MF contains information about the files contained in the JAR file.

Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:

Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)

These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.

Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,

Main-Class: {fully qualified classname}

The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.

Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,

Class-Path: {jar1-name jar2-name directory-name/jar3-name}

This header can be used to specify the external JAR files on the same local network and not inside the current JAR.

Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:

Headers in a manifest
Header                  | Definition
-------------------------------------------------------------------
Name                    | The name of the specification.
Specification-Title     | The title of the specification.
Specification-Version   | The version of the specification.
Specification-Vendor    | The vendor of the specification.
Implementation-Title    | The title of the implementation.
Implementation-Version  | The build number of the implementation.
Implementation-Vendor   | The vendor of the implementation.

Package sealing related headers:

We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,

Name: {package/some-package/} Sealed:true

Here, the package name must end with ‘/’.

Enhancing security with manifest files:

We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.

META-INF folder:

This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.

Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

Get program path in VB.NET?

For a console application you can use System.Reflection.Assembly.GetExecutingAssembly().Location as long as the call is made within the code of the console app itself, if you call this from within another dll or plugin this will return the location of that DLL and not the executable.

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Make sure that you are building your web app as "Any CPU". Right click your web project --> Properties --> Build --> and look for the "Platform Target". Choose "Any CPU" or play around with it.

Hope this helps!

Hashing a file in Python

For the correct and efficient computation of the hash value of a file (in Python 3):

  • Open the file in binary mode (i.e. add 'b' to the filemode) to avoid character encoding and line-ending conversion issues.
  • Don't read the complete file into memory, since that is a waste of memory. Instead, sequentially read it block by block and update the hash for each block.
  • Eliminate double buffering, i.e. don't use buffered IO, because we already use an optimal block size.
  • Use readinto() to avoid buffer churning.

Example:

import hashlib

def sha256sum(filename):
    h  = hashlib.sha256()
    b  = bytearray(128*1024)
    mv = memoryview(b)
    with open(filename, 'rb', buffering=0) as f:
        for n in iter(lambda : f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

How to convert string to binary?

In Python version 3.6 and above you can use f-string to format result.

str = "hello world"
print(" ".join(f"{ord(i):08b}" for i in str))

01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100
  • The left side of the colon, ord(i), is the actual object whose value will be formatted and inserted into the output. Using ord() gives you the base-10 code point for a single str character.

  • The right hand side of the colon is the format specifier. 08 means width 8, 0 padded, and the b functions as a sign to output the resulting number in base 2 (binary).