Programs & Examples On #Backspace

The backspace key on the keyboard (deletes the previous character)

Javascript: How to remove the last character from a div or a string?

var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);

http://jsfiddle.net/d72ML/

The "backspace" escape character '\b': unexpected behavior?

Not too hard to explain... This is like typing hello worl, hitting the left-arrow key twice, typing d, and hitting the down-arrow key.

At least, that is how I infer your terminal is interpeting the \b and \n codes.

Redirect the output to a file and I bet you get something else entirely. Although you may have to look at the file's bytes to see the difference.

[edit]

To elaborate a bit, this printf emits a sequence of bytes: hello worl^H^Hd^J, where ^H is ASCII character #8 and ^J is ASCII character #10. What you see on your screen depends on how your terminal interprets those control codes.

jQuery: keyPress Backspace won't fire?

Use keyup instead of keypress. This gets all the key codes when the user presses something

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

rejected master -> master (non-fast-forward)

As the error message says: git pull before you try to git push. Apparently your local branch is out of sync with your tracking branch.

Depending on project rules and your workflow you might also want to use git pull --rebase.

python: create list of tuples from lists

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

How to copy directories with spaces in the name

When you specify the last Directory on the path remove the last .

for example "\server\directory with space\directory with space".

that should do it.

echo key and value of an array without and with loop

array_walk($v, function(&$value, $key) {
   echo $key . '--'. $value;
 });

Learn more about array_walk

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

You need to make sure the file (ex. /etc/init.d/mongodb) has execute permissions.

chmod +x /etc/init.d/mongodb

How do I find an element position in std::vector?

First of all, do you really need to store indices like this? Have you looked into std::map, enabling you to store key => value pairs?

Secondly, if you used iterators instead, you would be able to return std::vector.end() to indicate an invalid result. To convert an iterator to an index you simply use

size_t i = it - myvector.begin();

Python CSV error: line contains NULL byte

Why are you doing this?

 reader = csv.reader(open(filepath, "rU"))

The docs are pretty clear that you must do this:

with open(filepath, "rb") as src:
    reader= csv.reader( src )

The mode must be "rb" to read.

http://docs.python.org/library/csv.html#csv.reader

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

HTML form with side by side input fields

You could use the {display: inline-flex;} this would produce this: inline-flex

How to override toString() properly in Java?

Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?

@Override
    public String toString() {
        return "ContractDTO{" +
                "contractId='" + contractId + '\'' +
                ", contractTemplateId='" + contractTemplateId + '\'' +
                '}';
    }

Loop through all nested dictionary values?

Here's a modified version of Fred Foo's answer for Python 2. In the original response, only the deepest level of nesting is output. If you output the keys as lists, you can keep the keys for all levels, although to reference them you need to reference a list of lists.

Here's the function:

def NestIter(nested):
    for key, value in nested.iteritems():
        if isinstance(value, collections.Mapping):
            for inner_key, inner_value in NestIter(value):
                yield [key, inner_key], inner_value
        else:
            yield [key],value

To reference the keys:

for keys, vals in mynested: 
    print(mynested[keys[0]][keys[1][0]][keys[1][1][0]])

for a three-level dictionary.

You need to know the number of levels before to access multiple keys and the number of levels should be constant (it may be possible to add a small bit of script to check the number of nesting levels when iterating through values, but I haven't yet looked at this).

How to overlay density plots in R?

Just to provide a complete set, here's a version of Chase's answer using lattice:

dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
                   , lines = rep(c("a", "b"), each = 100))

densityplot(~dens,data=dat,groups = lines,
            plot.points = FALSE, ref = TRUE, 
            auto.key = list(space = "right"))

which produces a plot like this: enter image description here

How to pass arguments to a Button command in Tkinter?

I am extremely late, but here is a very simple way of accomplishing it.

import tkinter as tk
def function1(param1, param2):
    print(str(param1) + str(param2))

var1 = "Hello "
var2 = "World!"
def function2():
    function1(var1, var2)

root = tk.Tk()

myButton = tk.Button(root, text="Button", command=function2)
root.mainloop()

You simply wrap the function you want to use in another function and call the second function on the button press.

package javax.mail and javax.mail.internet do not exist

Had the same issue. Obviously these .jars were included with Java <= v8.x out of the box, but are not anymore. Thus one has to separately download them and place them in the appropriate classpath as highlighted by several folks above. I understand that the new Java is modularized and thus potentially more light-weight (which is certainly a good thing, since the old setup was a monster). On the other hand this - as we can see - breaks lots of old build setups. Since the time to fix these isn't chargeable to Oracle I guess this made their decision easy...

Importing JSON into an Eclipse project

on linux pip install library_that_you_need Also on Help/Eclipse MarketPlace, i add PyDev IDE for Eclipse 7, so when i start a new project i create file/New Project/Pydev Project

Finding what branch a Git commit came from

Update December 2013:

sschuberth comments

git-what-branch (Perl script, see below) does not seem to be maintained anymore. git-when-merged is an alternative written in Python that's working very well for me.

It is based on "Find merge commit which include a specific commit".

git when-merged [OPTIONS] COMMIT [BRANCH...]

Find when a commit was merged into one or more branches.
Find the merge commit that brought COMMIT into the specified BRANCH(es).

Specifically, look for the oldest commit on the first-parent history of BRANCH that contains the COMMIT as an ancestor.


Original answer September 2010:

Sebastien Douche just twitted (16 minutes before this SO answer):

git-what-branch: Discover what branch a commit is on, or how it got to a named branch

This is a Perl script from Seth Robertson that seems very interesting:

SYNOPSIS

git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...

OVERVIEW

Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch. If a commit was made directly on a named branch, that obviously is the earliest path.

By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless --topo-order is specified).

PERFORMANCE

If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular --reference-branch --reference tag to examine will be hundreds of times faster (if you have hundreds of candidate branches).

EXAMPLES

 # git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
   v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May  5 08:59:37 2005)
   v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May  3 18:27:24 2005)
   v2.6.12-rc3-461-g84e48b6 is on master
   v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
   [...]

This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.

File Upload In Angular?

Thanks to @Eswar. This code worked perfectly for me. I want to add certain things to the solution :

I was getting error : java.io.IOException: RESTEASY007550: Unable to get boundary for multipart

In order to solve this error, you should remove the "Content-Type" "multipart/form-data". It solved my problem.

Disable Proximity Sensor during call

Proximity Sensor Dial

*#*#7378423#*#*

1) Service Tests - (If present)

2) Proximity Switch

3) Test on sensor (Next to logo(top) of mobile)

4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery

OR

4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.

Technically, Its not any software solution, but hardware solution will work.

How to upgrade Python version to 3.7?

Try this if you are on ubuntu:

sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7

In case you don't have the repository and so it fires a not-found package you first have to install this:

sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/

ROW_NUMBER() in MySQL

This Work perfectly for me to create RowNumber when we have more than one column. In this case two column.

SELECT @row_num := IF(@prev_value= concat(`Fk_Business_Unit_Code`,`NetIQ_Job_Code`), @row_num+1, 1) AS RowNumber, 
    `Fk_Business_Unit_Code`,   
    `NetIQ_Job_Code`,  
    `Supervisor_Name`,  
    @prev_value := concat(`Fk_Business_Unit_Code`,`NetIQ_Job_Code`)  
FROM (SELECT DISTINCT `Fk_Business_Unit_Code`,`NetIQ_Job_Code`,`Supervisor_Name`         
      FROM Employee    
      ORDER BY `Fk_Business_Unit_Code`, `NetIQ_Job_Code`, `Supervisor_Name` DESC) z,  
(SELECT @row_num := 1) x,  
(SELECT @prev_value := '') y  
ORDER BY `Fk_Business_Unit_Code`, `NetIQ_Job_Code`,`Supervisor_Name` DESC

How to zip a whole folder using PHP

This will resolve your issue. Please try it.

$zip = new ZipArchive;
$zip->open('testPDFZip.zip', ZipArchive::CREATE);
foreach (glob(APPLICATION_PATH."pages/recruitment/uploads/test_pdf_folder/*") as $file) {
    $new_filename = end(explode("/",$file));
    $zip->addFile($file,"emp/".$new_filename);
}           
$zip->close();

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

Set order of columns in pandas dataframe

Just select the order yourself by typing in the column names. Note the double brackets:

frame = frame[['column I want first', 'column I want second'...etc.]]

What is the difference between the | and || or operators?

The single pipe, |, is one of the bitwise operators.

From Wikipedia:

In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes).

Should you use .htm or .html file extension? What is the difference, and which file is correct?

I have a site that is all .htm and was told by a computer "know it all" to change to .html because it would help google rank.. saved time and $

Integrating Dropzone.js into existing HTML form with other fields

I had the exact same problem and found that Varan Sinayee's answer was the only one that actually solved the original question. That answer can be simplified though, so here's a simpler version.

The steps are:

  1. Create a normal form (don't forget the method and enctype args since this is not handled by dropzone anymore).

  2. Put a div inside with the class="dropzone" (that's how Dropzone attaches to it) and id="yourDropzoneName" (used to change the options).

  3. Set Dropzone's options, to set the url where the form and files will be posted, deactivate autoProcessQueue (so it only happens when user presses 'submit') and allow multiple uploads (if you need it).

  4. Set the init function to use Dropzone instead of the default behavior when the submit button is clicked.

  5. Still in the init function, use the "sendingmultiple" event handler to send the form data along wih the files.

Voilà ! You can now retrieve the data like you would with a normal form, in $_POST and $_FILES (in the example this would happen in upload.php)

HTML

<form action="upload.php" enctype="multipart/form-data" method="POST">
    <input type="text" id ="firstname" name ="firstname" />
    <input type="text" id ="lastname" name ="lastname" />
    <div class="dropzone" id="myDropzone"></div>
    <button type="submit" id="submit-all"> upload </button>
</form>

JS

Dropzone.options.myDropzone= {
    url: 'upload.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 5,
    maxFiles: 5,
    maxFilesize: 1,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("firstname", jQuery("#firstname").val());
            formData.append("lastname", jQuery("#lastname").val());
        });
    }
}

Swift: Display HTML data in a label or textView

Here is a Swift 3 version:

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}

I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.

How much memory can a 32 bit process access on a 64 bit operating system?

2 GB by default. If the application is large address space aware (linked with /LARGEADDRESSAWARE), it gets 4 GB (not 3 GB, see http://msdn.microsoft.com/en-us/library/aa366778.aspx)

They're still limited to 2 GB since many application depends on the top bit of pointers to be zero.

Git On Custom SSH Port

Above answers are nice and great, but not clear for new git users like me. So after some investigation, i offer this new answer.

1 what's the problem with the ssh config file way?

When the config file does not exists, you can create one. Besides port the config file can include other ssh config option:user IdentityFile and so on, the config file looks like

Host mydomain.com
    User git
    Port 12345

If you are running linux, take care the config file must have strict permission: read/write for the user, and not accessible by others

2 what about the ssh url way?

It's cool, the only thing we should know is that there two syntaxes for ssh url in git

  • standard syntax ssh://[user@]host.xz[:port]/path/to/repo.git/
  • scp like syntax [user@]host.xz:path/to/repo.git/

By default Gitlab and Github will show the scp like syntax url, and we can not give the custom ssh port. So in order to change ssh port, we need use the standard syntax

How do I get the coordinate position after using jQuery drag and drop?

I would start with something like this. Then update that to use the position plugin and that should get you where you want to be.

How to run a cronjob every X minutes?

2 steps to check if a cronjob is working :

  1. Login on the server with the user that execute the cronjob
  2. Manually run php command :

    /usr/bin/php /mydomain.in/cromail.php

And check if any error is displayed

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

How can I switch my git repository to a particular commit

To create a new branch (locally):

  • With the commit hash (or part of it)

    git checkout -b new_branch 6e559cb
    
  • or to go back 4 commits from HEAD

    git checkout -b new_branch HEAD~4
    

Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch


For discarding the last three commits, see Lunaryorn's answer below.


For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

remove borders around html input

In my case I am using a CSS framework which adds box-shadow, so I had to also add

box-shadow: none;

So the complete snippet is:

border: none; 
border-width: 0; 
box-shadow: none;

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

How should we manage jdk8 stream for null values

An example how to avoid null e.g. use filter before groupingBy

Filter out the null instances before groupingBy.

Here is an example

MyObjectlist.stream()
            .filter(p -> p.getSomeInstance() != null)
            .collect(Collectors.groupingBy(MyObject::getSomeInstance));

How to set Java SDK path in AndroidStudio?

Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear. enter image description here

What is the best way to test for an empty string in Go?

Both styles are used within the Go's standard libraries.

if len(s) > 0 { ... }

can be found in the strconv package: http://golang.org/src/pkg/strconv/atoi.go

if s != "" { ... }

can be found in the encoding/json package: http://golang.org/src/pkg/encoding/json/encode.go

Both are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.

Russ Cox writes in a golang-nuts thread:

The one that makes the code clear.
If I'm about to look at element x I typically write
len(s) > x, even for x == 0, but if I care about
"is it this specific string" I tend to write s == "".

It's reasonable to assume that a mature compiler will compile
len(s) == 0 and s == "" into the same, efficient code.
...

Make the code clear.

As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

How can you remove all documents from a collection with Mongoose?

In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.

Source: Mongodb.

If you are using mongo sheel, just do:

db.Datetime.remove({})

In your case, you need:

You didn't show me the delete button, so this button is just an example:

<a class="button__delete"></a>

Change the controller to:

exports.destroy = function(req, res, next) {
    Datetime.remove({}, function(err) {
            if (err) {
                console.log(err)
            } else {
                res.end('success');
            }
        }
    );
};

Insert this ajax delete method in your client js file:

        $(document).ready(function(){
            $('.button__delete').click(function() {
                var dataId = $(this).attr('data-id');

                if (confirm("are u sure?")) {
                    $.ajax({
                        type: 'DELETE',
                        url: '/',
                        success: function(response) {
                            if (response == 'error') {
                                console.log('Err!');
                            }
                            else {
                                alert('Success');
                                location.reload();
                            }
                        }
                    });
                } else {
                    alert('Canceled!');
                }
            });
        });

How to execute multiple SQL statements from java

I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSets. The database may only return the last result set.

Multiple ResultSets

However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

Multiple SQL Statements

If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String of SQL. For example I have used something like this on Sybase

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

This will depend on the syntax supported by your database. In this example note the addtional spaces padding the statements so that there is white space between the staments.

How can I open Java .class files in a human-readable way?

There is no need to decompile Applet.class. The public Java API classes sourcecode comes with the JDK (if you choose to install it), and is better readable than decompiled bytecode. You can find compressed in src.zip (located in your JDK installation folder).

How to resolve compiler warning 'implicit declaration of function memset'

Try to add next define at start of your .c file:

#define _GNU_SOURCE

It helped me with pipe2 function.

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

bootstrap responsive table content wrapping

Fine then. You can use CSS word wrap property. Something like this :

td.test /* Give whatever class name you want */
{
width:11em; /* Give whatever width you want */
word-wrap:break-word;
}

What is the difference between an Instance and an Object?

Object:

It is a generice term basically it is a Software bundle that has state(variables) and behaviour(methods)

Class:

A blue print(template) for an object instance-it's a unique object thing for example you create a object two times what does that mean is yo have created two instances

Let me give an example

Class student()
{
   private string firstName;
  public student(string fname)
  {
    firstName=fname;
  }
  Public string GetFirstName()
  {
    return firstName;
  }
}

Object example:

Student s1=new student("Martin"); Student s2=new student("Kumar");

The s1,s2 are having object of class Student

Instance:

s1 and s2 are instances of object student the two are unique.

it can be called as reference also.

basically the s1 and s2 are variables that are assigned an object

How do I list / export private keys from a keystore?

For android development, to convert keystore created in eclipse ADT into public key and private key used in SignApk.jar:

export private key:

keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der
openssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem

edit private.rsa.pem and leave "-----BEGIN PRIVATE KEY-----" to "-----END PRIVATE KEY-----" paragraph, then:

openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der

export public key:

keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der

sign apk:

java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

Because pypy is not 100% compatible, takes 8 gigs of ram to compile, is a moving target, and highly experimental, where cpython is stable, the default target for module builders for 2 decades (including c extensions that don't work on pypy), and already widely deployed.

Pypy will likely never be the reference implementation, but it is a good tool to have.

How do I return a proper success/error message for JQuery .ajax() using PHP?

Server side:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

Disable nginx cache for JavaScript files

I know this question is a bit old but i would suggest to use some cachebraking hash in the url of the javascript. This works perfectly in production as well as during development because you can have both infinite cache times and intant updates when changes occur.

Lets assume you have a javascript file /js/script.min.js, but in the referencing html/php file you do not use the actual path but:

<script src="/js/script.<?php echo md5(filemtime('/js/script.min.js')); ?>.min.js"></script>

So everytime the file is changed, the browser gets a different url, which in turn means it cannot be cached, be it locally or on any proxy inbetween.

To make this work you need nginx to rewrite any request to /js/script.[0-9a-f]{32}.min.js to the original filename. In my case i use the following directive (for css also):

location ~* \.(css|js)$ {
                expires max;
                add_header Pragma public;
                etag off;
                add_header Cache-Control "public";
                add_header Last-Modified "";
                rewrite  "^/(.*)\/(style|script)\.min\.([\d\w]{32})\.(js|css)$" /$1/$2.min.$4 break;
        }

I would guess that the filemtime call does not even require disk access on the server as it should be in linux's file cache. If you have doubts or static html files you can also use a fixed random value (or incremental or content hash) that is updated when your javascript / css preprocessor has finished or let one of your git hooks change it.

In theory you could also use a cachebreaker as a dummy parameter (like /js/script.min.js?cachebreak=0123456789abcfef), but then the file is not cached at least by some proxies because of the "?".

Relative path to absolute path in C#?

string exactPath = Path.GetFullPath(yourRelativePath);

works

How to check if a user is logged in (how to properly use user.is_authenticated)?

If you want to check for authenticated users in your template then:

{% if user.is_authenticated %}
    <p>Authenticated user</p>
{% else %}
    <!-- Do something which you want to do with unauthenticated user -->
{% endif %}

Restart container within pod

Both pod and container are ephemeral, try to use the following command to stop the specific container and the k8s cluster will restart a new container.

kubectl exec -it [POD_NAME] -c [CONTAINER_NAME] -- /bin/sh -c "kill 1"

This will send a SIGTERM signal to process 1, which is the main process running in the container. All other processes will be children of process 1, and will be terminated after process 1 exits. See the kill manpage for other signals you can send.

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

How to send a POST request from node.js Express?

in your server side the code looks like:

var request = require('request');

app.post('/add', function(req, res){
  console.log(req.body);
  request.post(
    {
    url:'http://localhost:6001/add',
    json: {
      unit_name:req.body.unit_name,
      unit_price:req.body.unit_price
        },
    headers: {
        'Content-Type': 'application/json'
    }
    },
  function(error, response, body){
    // console.log(error);
    // console.log(response);
    console.log(body);
    res.send(body);
  });
  // res.send("body");
});

in receiving end server code looks like:

app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});

Schema is just two properties unit_name and unit_price.

Add an image in a WPF button

I also had the same issue. I've fixed it by using the following code.

        <Button Width="30" Margin="0,5" HorizontalAlignment="Stretch"  Click="OnSearch" >
            <DockPanel>
                <Image Source="../Resources/Back.jpg"/>
            </DockPanel>
        </Button>

Note: Make sure the build action of the image in the property window, should be Resource.

enter image description here

Convert.ToDateTime: how to set format

How about this:

    string test = "01-12-12";
    try{
         DateTime dateTime = DateTime.Parse(test);
         test = dateTime.ToString("dd/yyyy");
    }
    catch (FormatException exc)
    {
        MessageBox.Show(exc.Message);
    }

Where test will be equal to "12/2012"

Hope it helps!

Please read HERE.

SQL multiple columns in IN clause

In general you can easily write the Where-Condition like this:

select * from tab1
where (col1, col2) in (select col1, col2 from tab2)

Note
Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values):

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

I get the same question as you you can click here :

About the question in xcode5 "no matching provisioning profiles found"

(About xcode5 ?no matching provisioning profiles found )

When I was fitting with iOS7,I get the warning like this:no matching provisioning profiles found. the reason may be that your project is in other group.

Do like this:find the file named *.xcodeproj in your protect,show the content of it.

You will see three files:

  1. project.pbxproj
  2. project.xcworkspace
  3. xcuserdata

open the first, search the uuid and delete the row.

Python, how to check if a result set is empty?

Notice: This is for MySQLdb module in Python.

For a SELECT statement, there shouldn't be an exception for an empty recordset. Just an empty list ([]) for cursor.fetchall() and None for cursor.fetchone().

For any other statement, e.g. INSERT or UPDATE, that doesn't return a recordset, you can neither call fetchall() nor fetchone() on the cursor. Otherwise, an exception will be raised.

There's one way to distinguish between the above two types of cursors:

def yield_data(cursor):
    while True:
        if cursor.description is None:
            # No recordset for INSERT, UPDATE, CREATE, etc
            pass
        else:
            # Recordset for SELECT, yield data
            yield cursor.fetchall()
            # Or yield column names with
            # yield [col[0] for col in cursor.description]

        # Go to the next recordset
        if not cursor.nextset():
            # End of recordsets
            return

How to update a value in a json file and save it through node.js

Save data after task completion

fs.readFile("./sample.json", 'utf8', function readFileCallback(err, data) {
        if (err) {
          console.log(err);
        } else {
          fs.writeFile("./sample.json", JSON.stringify(result), 'utf8', err => {
            if (err) throw err;
            console.log('File has been saved!');
          });
        }
      });

Windows Batch: How to add Host-Entries?

I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.

@echo off

SET NEWLINE=^& echo.

FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

Closing WebSocket correctly (HTML5, Javascript)

The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF] protocol, and then there's the new version using Hybi formatted packets.

The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!

However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88 (better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.

no debugging symbols found when using gdb

The application has to be both compiled and linked with -g option. I.e. you need to put -g in both CPPFLAGS and LDFLAGS.

postgresql return 0 if returned value is null

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

UnicodeEncodeError: 'charmap' codec can't encode characters

While saving the response of get request, same error was thrown on Python 3.7 on window 10. The response received from the URL, encoding was UTF-8 so it is always recommended to check the encoding so same can be passed to avoid such trivial issue as it really kills lots of time in production

import requests
resp = requests.get('https://en.wikipedia.org/wiki/NIFTY_50')
print(resp.encoding)
with open ('NiftyList.txt', 'w') as f:
    f.write(resp.text)

When I added encoding="utf-8" with the open command it saved the file with the correct response

with open ('NiftyList.txt', 'w', encoding="utf-8") as f:
    f.write(resp.text)

cannot make a static reference to the non-static field

main is a static method. It cannot refer to balance, which is an attribute (non-static variable). balance has meaning only when it is referred through an object reference (such as myAccount.balance or yourAccount.balance). But it doesn't have any meaning when it is referred through class (such as Account.balance (whose balance is that?))

I made some changes to your code so that it compiles.

public static void main(String[] args) {
    Account account = new Account(1122, 20000, 4.5);
    account.withdraw(2500);
    account.deposit(3000);

and:

public void withdraw(double withdrawAmount) {
    balance -= withdrawAmount;
}

public void deposit(double depositAmount) {
    balance += depositAmount;
}   

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Formatting code in Notepad++

This isn't quite the answer you were looking for, but it's the solution I came to when I had the same question.

I'm a pretty serious Notepad++ user, so don't take this the wrong way. I have started using NetBeans 8 to develop websites in addition to Notepad++ because you can set it to autoformat on save for all your languages, and there are a ton of configuration options for how the formatting looks, down to the most minute detail. You might look into it and find it is a worthy tool to use in conjunction with notepad++. It's also open source, completely free, and has a bunch of plugins and other useful things like automatically compiling Sass if you use that too. It's definitely not as quick as NP++ so it's not great for small edits, but it can be nice for a long coding session.

How to get ID of clicked element with jQuery

You just need to remove the hash from the beginning:

$('a.pagerlink').click(function() { 
    var id = $(this).attr('id').substring(1);
    $container.cycle(id); 
    return false; 
}); 

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

Handling the window closing event with WPF / MVVM Light Toolkit

Here is an answer according to the MVVM-pattern if you don't want to know about the Window (or any of its event) in the ViewModel.

public interface IClosing
{
    /// <summary>
    /// Executes when window is closing
    /// </summary>
    /// <returns>Whether the windows should be closed by the caller</returns>
    bool OnClosing();
}

In the ViewModel add the interface and implementation

public bool OnClosing()
{
    bool close = true;

    //Ask whether to save changes och cancel etc
    //close = false; //If you want to cancel close

    return close;
}

In the Window I add the Closing event. This code behind doesn't break the MVVM pattern. The View can know about the viewmodel!

void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    IClosing context = DataContext as IClosing;
    if (context != null)
    {
        e.Cancel = !context.OnClosing();
    }
}

How to send a stacktrace to log4j?

Just because it happened to me and can be useful. If you do this

try {
   ...
} catch (Exception e) {
    log.error( "failed! {}", e );
}

you will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String. Do it without {} as skaffman said

Extracting specific columns in numpy array

Just:

>>> m = np.matrix(np.random.random((5, 5)))
>>> m
matrix([[0.91074101, 0.65999332, 0.69774588, 0.007355  , 0.33025395],
        [0.11078742, 0.67463754, 0.43158254, 0.95367876, 0.85926405],
        [0.98665185, 0.86431513, 0.12153138, 0.73006437, 0.13404811],
        [0.24602225, 0.66139215, 0.08400288, 0.56769924, 0.47974697],
        [0.25345299, 0.76385882, 0.11002419, 0.2509888 , 0.06312359]])
>>> m[:,[1, 2]]
matrix([[0.65999332, 0.69774588],
        [0.67463754, 0.43158254],
        [0.86431513, 0.12153138],
        [0.66139215, 0.08400288],
        [0.76385882, 0.11002419]])

The columns need not to be in order:

>>> m[:,[2, 1, 3]]
matrix([[0.69774588, 0.65999332, 0.007355  ],
        [0.43158254, 0.67463754, 0.95367876],
        [0.12153138, 0.86431513, 0.73006437],
        [0.08400288, 0.66139215, 0.56769924],
        [0.11002419, 0.76385882, 0.2509888 ]])

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date < DATEADD(Day, -1, date)

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

Since the verification is based on package's name, you can change the package name inside your config.xml or manifest file for another name you want.

When publishing your app don't forget to change back the name!

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?


function appendTaskOnStack(task, ms, loop) {
    window.nextTaskAfter = (window.nextTaskAfter || 0) + ms;

    if (!loop) {
        setTimeout(function() {
            appendTaskOnStack(task, ms, true);
        }, window.nextTaskAfter);
    } 
    else {
        if (task) 
            task.apply(Array(arguments).slice(3,));
        window.nextTaskAfter = 0;
    }
}

for (var n=0; n < 10; n++) {
    appendTaskOnStack(function(){
        console.log(n)
    }, 100);
}

Print: Entry, ":CFBundleIdentifier", Does Not Exist

For me it's due react-native compatibility issue with Xcode9.4. I resolved using the following steps. on my project /ROOT

  1. rm -rf node_modules
  2. react-native upgrade
  3. npm install
  4. react-native run-ios

SOLVES the issue, this thread helped me to understand the issue.

Sql Server equivalent of a COUNTIF aggregate function

How about

SELECT id, COUNT(IF status=42 THEN 1 ENDIF) AS cnt
FROM table
GROUP BY table

Shorter than CASE :)

Works because COUNT() doesn't count null values, and IF/CASE return null when condition is not met and there is no ELSE.

I think it's better than using SUM().

Using python map and other functional tools

Would this do it?

foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]

def maptest2(bar):
  print bar

def maptest(foo):
  print foo
  map(maptest2, bars)

map(maptest, foos)

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

How to read the value of a private field from a different class in Java?

Reflection isn't the only way to resolve your issue (which is to access the private functionality/behaviour of a class/component)

An alternative solution is to extract the class from the .jar, decompile it using (say) Jode or Jad, change the field (or add an accessor), and recompile it against the original .jar. Then put the new .class ahead of the .jar in the classpath, or reinsert it in the .jar. (the jar utility allows you to extract and reinsert to an existing .jar)

As noted below, this resolves the wider issue of accessing/changing private state rather than simply accessing/changing a field.

This requires the .jar not to be signed, of course.

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

For some reason, this was not working

<p:column headerText="" width="25px" sortBy="#{row.key}">

But this worked:

<p:column headerText="" width="25" sortBy="#{row.key}">

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

How to get the first 2 letters of a string in Python?

It is as simple as string[:2]. A function can be easily written to do it, if you need.

Even this, is as simple as

def first2(s):
    return s[:2]

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

How to make div go behind another div?

One possible could be like this,

HTML

<div class="box-left-mini">
    <div class="front">this div is infront</div>
    <div class="behind">
        this div is behind
    </div>
</div>

CSS

.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.front{
    background-color:lightgreen;
}
.behind{
    background-color:grey;
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    z-index:-1;
}

http://jsfiddle.net/MgtWS/

But it really depends on the layout of your div elements i.e. if they are floating, or absolute positioned etc.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

Execute SQLite script

If you are using the windows CMD you can use this command to create a database using sqlite3

C:\sqlite3.exe DBNAME.db ".read DBSCRIPT.sql"

If you haven't a database with that name sqlite3 will create one, and if you already have one, it will run it anyways but with the "TABLENAME already exists" error, I think you can also use this command to change an already existing database (but im not sure)

Enzyme - How to access and set <input> value?

I use Wrapper's setValue[https://vue-test-utils.vuejs.org/api/wrapper/#setvalue-value] method to set value.

inputA = wrapper.findAll('input').at(0)
inputA.setValue('123456')

a page can have only one server-side form tag

It sounds like you have a form tag in a Master Page and in the Page that is throwing the error.

You can have only one.

Split a python list into other "sublists" i.e smaller lists

Actually I think using plain slices is the best solution in this case:

for i in range(0, len(data), 100):
    chunk = data[i:i + 100]
    ...

If you want to avoid copying the slices, you could use itertools.islice(), but it doesn't seem to be necessary here.

The itertools() documentation also contains the famous "grouper" pattern:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Relative imports - ModuleNotFoundError: No module named x

For me, simply adding the current directory worked.

Using the following structure:

+-- myproject
    +-- a.py
    +-- b.py

a.py:

from b import some_object
# returns ModuleNotFound error

from myproject.b import some_object
# works

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

Why can't I do <img src="C:/localfile.jpg">?

IE 9 : If you want that the user takes a look at image before he posts it to the server : The user should ADD the website to "trusted Website list".

How to compare two dates in Objective-C

Here buddy. This function will match your date with any specific date and will be able to tell whether they match or not. You can also modify the components to match your requirements.

- (BOOL)isSameDay:(NSDate*)date1 otherDay:(NSDate*)date2 {
NSCalendar* calendar = [NSCalendar currentCalendar];

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];

return [comp1 day]   == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year]  == [comp2 year];}

Regards, Naveed Butt

MVC 4 Edit modal form using Bootstrap

I prefer to avoid using Ajax.BeginForm helper and do an Ajax call with JQuery. In my experience it is easier to maintain code written like this. So below are the details:

Models

public class ManagePeopleModel
{
    public List<PersonModel> People { get; set; }
    ... any other properties
}

public class PersonModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    ... any other properties
}

Parent View

This view contains the following things:

  • records of people to iterate through
  • an empty div that will be populated with a modal when a Person needs to be edited
  • some JavaScript handling all ajax calls
@model ManagePeopleModel

<h1>Manage People</h1>

@using(var table = Html.Bootstrap().Begin(new Table()))
{
    foreach(var person in Model.People)
    {
        <tr>
            <td>@person.Id</td>
            <td>@Person.Name</td>
            <td>@person.Age</td>
            <td>@html.Bootstrap().Button().Text("Edit Person").Data(new { @id = person.Id }).Class("btn-trigger-modal")</td>
        </tr>
    }
}

@using (var m = Html.Bootstrap().Begin(new Modal().Id("modal-person")))
{

}

@section Scripts
{
    <script type="text/javascript">
        // Handle "Edit Person" button click.
        // This will make an ajax call, get information for person,
        // put it all in the modal and display it
        $(document).on('click', '.btn-trigger-modal', function(){
            var personId = $(this).data('id');
            $.ajax({
                url: '/[WhateverControllerName]/GetPersonInfo',
                type: 'GET',
                data: { id: personId },
                success: function(data){
                    var m = $('#modal-person');
                    m.find('.modal-content').html(data);
                    m.modal('show');
                }
            });
        });

        // Handle submitting of new information for Person.
        // This will attempt to save new info
        // If save was successful, it will close the Modal and reload page to see updated info
        // Otherwise it will only reload contents of the Modal
        $(document).on('click', '#btn-person-submit', function() {
            var self = $(this);
            $.ajax({
                url: '/[WhateverControllerName]/UpdatePersonInfo',
                type: 'POST',
                data: self.closest('form').serialize(),
                success: function(data) {
                    if(data.success == true) {
                        $('#modal-person').modal('hide');
                        location.reload(false)
                    } else {
                        $('#modal-person').html(data);
                    }
                }
            });
        });
    </script>
}

Partial View

This view contains a modal that will be populated with information about person.

@model PersonModel
@{
    // get modal helper
    var modal = Html.Bootstrap().Misc().GetBuilderFor(new Modal());
}

@modal.Header("Edit Person")
@using (var f = Html.Bootstrap.Begin(new Form()))
{
    using (modal.BeginBody())
    {
        @Html.HiddenFor(x => x.Id)
        @f.ControlGroup().TextBoxFor(x => x.Name)
        @f.ControlGroup().TextBoxFor(x => x.Age)
    }
    using (modal.BeginFooter())
    {
        // if needed, add here @Html.Bootstrap().ValidationSummary()
        @:@Html.Bootstrap().Button().Text("Save").Id("btn-person-submit")
        @Html.Bootstrap().Button().Text("Close").Data(new { dismiss = "modal" })
    }
}

Controller Actions

public ActionResult GetPersonInfo(int id)
{
    var model = db.GetPerson(id); // get your person however you need
    return PartialView("[Partial View Name]", model)
}

public ActionResult UpdatePersonInfo(PersonModel model)
{
    if(ModelState.IsValid)
    {
        db.UpdatePerson(model); // update person however you need
        return Json(new { success = true });
    }
    // else
    return PartialView("[Partial View Name]", model);
}

How to create a fix size list in python?

Note also that when you used arrays in C++ you might have had somewhat different needs, which are solved in different ways in Python:

  1. You might have needed just a collection of items; Python lists deal with this usecase just perfectly.
  2. You might have needed a proper array of homogenous items. Python lists are not a good way to store arrays.

Python solves the need in arrays by NumPy, which, among other neat things, has a way to create an array of known size:

from numpy import *

l = zeros(10)

How to use subList()

You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

Using :after to clear floating elements

This will work as well:

.clearfix:before,
.clearfix:after {
    content: "";
    display: table;
} 

.clearfix:after {
    clear: both;
}

/* IE 6 & 7 */
.clearfix {
    zoom: 1;
}

Give the class clearfix to the parent element, for example your ul element.

Sources here and here.

Xcode : Adding a project as a build dependency

  1. Select your project in the navigator on left.
  2. Open up the drawer in the middle pane and select your target.
  3. Select Build Phases
  4. Target Dependencies is an option at that point.

Send a ping to each IP on a subnet

In Bash shell:

#!/bin/sh

COUNTER=1

while [ $COUNTER -lt 254 ]
do
   ping 192.168.1.$COUNTER -c 1
   COUNTER=$(( $COUNTER + 1 ))
done

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Can you have multiline HTML5 placeholder text in a <textarea>?

in php with function chr(13) :

echo '<textarea class="form-control" rows="5" style="width:100%;" name="responsable" placeholder="NOM prénom du responsable légal'.chr(13).'Adresse'.chr(13).'CP VILLE'.chr(13).'Téléphone'.chr(13).'Adresse de messagerie" id="responsable"></textarea>';

The ASCII character code 13 chr(13) is called a Carriage Return or CR

How do I remove objects from an array in Java?

It depends on what you mean by "remove"? An array is a fixed size construct - you can't change the number of elements in it. So you can either a) create a new, shorter, array without the elements you don't want or b) assign the entries you don't want to something that indicates their 'empty' status; usually null if you are not working with primitives.

In the first case create a List from the array, remove the elements, and create a new array from the list. If performance is important iterate over the array assigning any elements that shouldn't be removed to a list, and then create a new array from the list. In the second case simply go through and assign null to the array entries.

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You can use

Trace.WriteLine()

to write to the Output window when debugging a unit test.

How to find rows in one table that have no corresponding row in another table

select parentTable.id from parentTable
left outer join childTable on (parentTable.id = childTable.parentTableID) 
where childTable.id is null

How to get year and month from a date - PHP

Probably not the most efficient code, but here it goes:

$dateElements = explode('-', $dateValue);
$year = $dateElements[0];

echo $year;    //2012

switch ($dateElements[1]) {

   case '01'    :  $mo = "January";
                   break;

   case '02'    :  $mo = "February";
                   break;

   case '03'    :  $mo = "March";
                   break;

     .
     .
     .

   case '12'    :  $mo = "December";
                   break;


}

echo $mo;      //January

How to get data from Magento System Configuration

Magento 1.x

(magento 2 example provided below)

sectionName, groupName and fieldName are present in etc/system.xml file of the module.

PHP Syntax:

Mage::getStoreConfig('sectionName/groupName/fieldName');

From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.

{{config path="sectionName/groupName/fieldName"}}

For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:

<?php
    $example = Mage::getModel('identifier/name')->load(1);
    $filter  = Mage::getModel('cms/template_filter');
    echo $filter->filter($example->getData('field'));
?>

Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.

Magento 2.x

From any Block class that extends \Magento\Framework\View\Element\AbstractBlock

$this->_scopeConfig->getValue('sectionName/groupName/fieldName');

Any other PHP class:

If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface via the constructor, you'll have to add it to your class.

// ... Remaining class definition above...

/**
 * @var \Magento\Framework\App\Config\ScopeConfigInterface
 */
protected $_scopeConfig;

/**
 * Constructor
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    // ...any other injected classes the class depends on...
) {
  $this->_scopeConfig = $scopeConfig;
  // Remaining constructor logic...
}

// ...remaining class definition below...

Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.

Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation & var/di

Excel Formula to SUMIF date falls in particular month

Try this instead:

  =SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))

It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.

Here's how the formula works.

  1. MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
    {1, 1, 1, 2, 2}.
  2. Then the comparison {1, 1, 1, 2, 2}= 1 produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}, which comprises the condition for the IF statement.
  3. The IF statement then returns an array of values, with {430, 96, 400.. for the values of the sum ranges where the month value equals 1 and ..0,0} where the month value does not equal 1.
  4. That array {430, 96, 400, 0, 0} is then summed to get the answer you are looking for.

This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.

It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)--also works.

Heads up: This does not work in Google Spreadsheets

Zero an array in C code

int arr[20] = {0} would be easiest if it only needs to be done once.

SQL statement to get column type

For SQL Server, this system stored procedure will return all table information, including column datatypes:

exec sp_help YOURTABLENAME

Get today date in google appScript

Google Apps Script is JavaScript, the date object is initiated with new Date() and all JavaScript methods apply, see doc here

Rename a file in C#

Take a look at System.IO.File.Move, "move" the file to a new name.

System.IO.File.Move("oldfilename", "newfilename");

PYTHONPATH vs. sys.path

Along with the many other reasons mentioned already, you could also point outh that hard-coding

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.

How to make scipy.interpolate give an extrapolated result beyond the input range?

What about scipy.interpolate.splrep (with degree 1 and no smoothing):

>> tck = scipy.interpolate.splrep([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], k=1, s=0)
>> scipy.interpolate.splev(6, tck)
34.0

It seems to do what you want, since 34 = 25 + (25 - 16).

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

I face the same issue. I am using docker version:17.09.0-ce.

I follow below steps:

  1. Create Dockerfile and added commands for creating docker image
  2. Go to directory where we have created Dockfile
  3. execute below command $ sudo docker build -t ubuntu-test:latest .

It resolved issue and image created successsfully.

Note: build command depend on docker version as well as which build option we are using. :)

Swift 3: Display Image from URL

The easiest way according to me will be using SDWebImage

Add this to your pod file

  pod 'SDWebImage', '~> 4.0'

Run pod install

Now import SDWebImage

      import SDWebImage

Now for setting image from url

    imageView.sd_setImage(with: URL(string: "http://www.domain/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

It will show placeholder image but when image is downloaded it will show the image from url .Your app will never crash

This are the main feature of SDWebImage

Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management

An asynchronous image downloader

An asynchronous memory + disk image caching with automatic cache expiration handling

A background image decompression

A guarantee that the same URL won't be downloaded several times

A guarantee that bogus URLs won't be retried again and again

A guarantee that main thread will never be blocked Performances!

Use GCD and ARC

To know more https://github.com/rs/SDWebImage

Branch from a previous commit using Git

Simply run :

git checkout -b branch-name <commit>

For example :

git checkout -b import/january-2019 1d0fa4fa9ea961182114b63976482e634a8067b8

The checkout command with the parameter -b will create a new branch AND it will switch you over to it

Bootstrap 3 - How to load content in modal body via AJAX?

This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false" to disable the deprecated Bootstrap load function.

JavaScript:

// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
    var link = $(e.relatedTarget);
    $(this).find(".modal-body").load(link.attr("href"));
});

Html (based on the official example):

<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
    Launch Modal
</a>

<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Try it yourself: https://jsfiddle.net/ednon5d1/

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.

There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.

Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.

How to debug a bash script?

Some trick to debug scripts:

Using set -[nvx]

In addition to

set -x

and

set +x

for stopping dump.

I would like to speak about set -v wich dump as smaller as less developped output.

bash <<<$'set -x\nfor i in {0..9};do\n\techo $i\n\tdone\nset +x' 2>&1 >/dev/null|wc -l
21

for arg in x v n nx nv nvx;do echo "- opts: $arg"
    bash 2> >(wc -l|sed s/^/stderr:/) > >(wc -l|sed s/^/stdout:/) <<eof
        set -$arg
        for i in {0..9};do
            echo $i
          done
        set +$arg
        echo Done.
eof
    sleep .02
  done
- opts: x
stdout:11
stderr:21
- opts: v
stdout:11
stderr:4
- opts: n
stdout:0
stderr:0
- opts: nx
stdout:0
stderr:0
- opts: nv
stdout:0
stderr:5
- opts: nvx
stdout:0
stderr:5

Dump variables or tracing on the fly

For testing some variables, I use sometime this:

bash <(sed '18ideclare >&2 -p var1 var2' myscript.sh) args

for adding:

declare >&2 -p var1 var2

at line 18 and running resulting script (with args), without having to edit them.

of course, this could be used for adding set [+-][nvx]:

bash <(sed '18s/$/\ndeclare -p v1 v2 >\&2/;22s/^/set -x\n/;26s/^/set +x\n/' myscript) args

will add declare -p v1 v2 >&2 after line 18, set -x before line 22 and set +x before line 26.

little sample:

bash <(sed '2,3s/$/\ndeclare -p LINENO i v2 >\&2/;5s/^/set -x\n/;7s/^/set +x\n/' <(
        seq -f 'echo $@, $((i=%g))' 1 8)) arg1 arg2
arg1 arg2, 1
arg1 arg2, 2
declare -i LINENO="3"
declare -- i="2"
/dev/fd/63: line 3: declare: v2: not found
arg1 arg2, 3
declare -i LINENO="5"
declare -- i="3"
/dev/fd/63: line 5: declare: v2: not found
arg1 arg2, 4
+ echo arg1 arg2, 5
arg1 arg2, 5
+ echo arg1 arg2, 6
arg1 arg2, 6
+ set +x
arg1 arg2, 7
arg1 arg2, 8

Note: Care about $LINENO will be affected by on-the-fly modifications!

( To see resulting script whithout executing, simply drop bash <( and ) arg1 arg2 )

Step by step, execution time

Have a look at my answer about how to profile bash scripts

What is the difference between null=True and blank=True in Django?

Here is an example of the field with blank= True and null=True

description = models.TextField(blank=True, null= True)

In this case: blank = True: tells our form that it is ok to leave the description field blank

and

null = True: tells our database that it is ok to record a null value in our db field and not give an error.

How to trap on UIViewAlertForUnsatisfiableConstraints?

This post helped me A LOT!

I added UIViewAlertForUnsatisfiableConstraints symbolic breakpoint with suggested action:

Obj-C project

po [[UIWindow keyWindow] _autolayoutTrace]

Symbolic breakpoint with custom action in Objective-C project

Swift project

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

Symbolic breakpoint with custom action

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

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

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

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

Obj-C

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

Swift 3.0

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

... and the result It was awesome!

Hinted View

Simply amazing! Hope It helps.

Credit card expiration dates - Inclusive or exclusive?

In my experience, it has expired at the end of that month. That is based on the fact that I can use it during that month, and that month is when my bank sends a new one.

invalid target release: 1.7

You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:

  • "C:\Program Files\Java\jdk1.7.0_40"

or on OS X:

  • /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

Fastest way to get the first object from a queryset in django?

If you plan to get first element often - you can extend QuerySet in this direction:

class FirstQuerySet(models.query.QuerySet):
    def first(self):
        return self[0]


class ManagerWithFirstQuery(models.Manager):
    def get_query_set(self):
        return FirstQuerySet(self.model)

Define model like this:

class MyModel(models.Model):
    objects = ManagerWithFirstQuery()

And use it like this:

 first_object = MyModel.objects.filter(x=100).first()

API vs. Webservice

API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

.gitignore after commit

I had to remove .idea and target folders and after reading all comments this worked for me:

git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'

and then push to master

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

Extract from the oficial docs:

Requires that the parent form is validated, that is, $( "form" ).validate() is called first

more about... rules

How to remove a directory from git repository?

Remove directory from git and local

You could checkout 'master' with both directories;

git rm -r one-of-the-directories // This deletes from filesystem
git commit . -m "Remove duplicated directory"
git push origin <your-git-branch> (typically 'master', but not always)

Remove directory from git but NOT local

As mentioned in the comments, what you usually want to do is remove this directory from git but not delete it entirely from the filesystem (local)

In that case use:

git rm -r --cached myFolder

How to create a drop shadow only on one side of an element?

update on someone else his answer transparant sides instead of white so it works on other color backgrounds too.

_x000D_
_x000D_
body {_x000D_
  background: url(http://s1.picswalls.com/wallpapers/2016/03/29/beautiful-nature-backgrounds_042320876_304.jpg)_x000D_
}_x000D_
_x000D_
div {_x000D_
  background: url(https://www.w3schools.com/w3css/img_avatar3.png) center center;_x000D_
  background-size: contain;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  margin: 50px;_x000D_
  border: 5px solid white;_x000D_
  box-shadow: 0px 0 rgba(0, 0, 0, 0), 0px 0 rgba(0, 0, 0, 0), 0 7px 7px -5px black;_x000D_
}
_x000D_
<div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to redirect siteA to siteB with A or CNAME records

You can only make DNS name pont to a different IP address, so if You you are using virtual hosts redirecting with DNS won't work.

When you enter subdomain.hostone.com in your browser it will use DNS to get it's IP address (if it's a CNAME it will continue trying until it gets IP from A record) then it will connect to that IP and send a http request with

Host: subdomain.hostone.com 

somewhere in the http headers.

Best Practices for Custom Helpers in Laravel 5

Here's a bash shell script I created to make Laravel 5 facades very quickly.

Run this in your Laravel 5 installation directory.

Call it like this:

make_facade.sh -f <facade_name> -n '<namespace_prefix>'

Example:

make_facade.sh -f helper -n 'App\MyApp'

If you run that example, it will create the directories Facades and Providers under 'your_laravel_installation_dir/app/MyApp'.

It will create the following 3 files and will also output them to the screen:

./app/MyApp/Facades/Helper.php
./app/MyApp/Facades/HelperFacade.php
./app/MyApp/Providers/HelperServiceProvider.php

After it is done, it will display a message similar to the following:

===========================
    Finished
===========================

Add these lines to config/app.php:
----------------------------------
Providers: App\MyApp\Providers\HelperServiceProvider,
Alias: 'Helper' => 'App\MyApp\Facades\HelperFacade',

So update the Providers and Alias list in 'config/app.php'

Run composer -o dumpautoload

The "./app/MyApp/Facades/Helper.php" will originally look like this:

<?php

namespace App\MyApp\Facades;


class Helper
{
    //
}

Now just add your methods in "./app/MyApp/Facades/Helper.php".

Here is what "./app/MyApp/Facades/Helper.php" looks like after I added a Helper function.

<?php

namespace App\MyApp\Facades;

use Request;

class Helper
{
    public function isActive($pattern = null, $include_class = false)
    {
        return ((Request::is($pattern)) ? (($include_class) ? 'class="active"' : 'active' ) : '');
    }
}

This is how it would be called:
===============================

{!!  Helper::isActive('help', true) !!}

This function expects a pattern and can accept an optional second boolean argument.

If the current URL matches the pattern passed to it, it will output 'active' (or 'class="active"' if you add 'true' as a second argument to the function call).

I use it to highlight the menu that is active.

Below is the source code for my script. I hope you find it useful and please let me know if you have any problems with it.

#!/bin/bash

display_syntax(){
    echo ""
    echo "  The Syntax is like this:"
    echo "  ========================"
    echo "      "$(basename $0)" -f <facade_name> -n '<namespace_prefix>'"
    echo ""
    echo "  Example:"
    echo "  ========"
    echo "      "$(basename $0) -f test -n "'App\MyAppDirectory'"
    echo ""
}


if [ $# -ne 4 ]
then
    echo ""
    display_syntax
    exit
else
# Use > 0 to consume one or more arguments per pass in the loop (e.g.
# some arguments don't have a corresponding value to go with it such
# as in the --default example).
    while [[ $# > 0 ]]
    do
        key="$1"
            case $key in
            -n|--namespace_prefix)
            namespace_prefix_in="$2"
            echo ""
            shift # past argument
            ;;
            -f|--facade)
            facade_name_in="$2"
            shift # past argument
            ;;
            *)
                    # unknown option
            ;;
        esac
        shift # past argument or value
    done
fi
echo Facade Name = ${facade_name_in}
echo Namespace Prefix = $(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
echo ""
}


function display_start_banner(){

    echo '**********************************************************'
    echo '*          STARTING LARAVEL MAKE FACADE SCRIPT'
    echo '**********************************************************'
}

#  Init the Vars that I can in the beginning
function init_and_export_vars(){
    echo
    echo "INIT and EXPORT VARS"
    echo "===================="
    #   Substitution Tokens:
    #
    #   Tokens:
    #   {namespace_prefix}
    #   {namespace_prefix_lowerfirstchar}
    #   {facade_name_upcase}
    #   {facade_name_lowercase}
    #


    namespace_prefix=$(echo ${namespace_prefix_in} | sed -e 's#\\#\\\\#')
    namespace_prefix_lowerfirstchar=$(echo ${namespace_prefix_in} | sed -e 's#\\#/#g' -e 's/^\(.\)/\l\1/g')
    facade_name_upcase=$(echo ${facade_name_in} | sed -e 's/\b\(.\)/\u\1/')
    facade_name_lowercase=$(echo ${facade_name_in} | awk '{print tolower($0)}')


#   Filename: {facade_name_upcase}.php  -  SOURCE TEMPLATE
source_template='<?php

namespace {namespace_prefix}\Facades;

class {facade_name_upcase}
{
    //
}
'


#  Filename: {facade_name_upcase}ServiceProvider.php    -   SERVICE PROVIDER TEMPLATE
serviceProvider_template='<?php

namespace {namespace_prefix}\Providers;

use Illuminate\Support\ServiceProvider;
use App;


class {facade_name_upcase}ServiceProvider extends ServiceProvider {

    public function boot()
    {
        //
    }

    public function register()
    {
        App::bind("{facade_name_lowercase}", function()
        {
            return new \{namespace_prefix}\Facades\{facade_name_upcase};
        });
    }

}
'

#  {facade_name_upcase}Facade.php   -   FACADE TEMPLATE
facade_template='<?php

namespace {namespace_prefix}\Facades;

use Illuminate\Support\Facades\Facade;

class {facade_name_upcase}Facade extends Facade {

    protected static function getFacadeAccessor() { return "{facade_name_lowercase}"; }
}
'
}


function checkDirectoryExists(){
    if [ ! -d ${namespace_prefix_lowerfirstchar} ]
    then
        echo ""
        echo "Can't find the namespace: "${namespace_prefix_in}
        echo ""
        echo "*** NOTE:"
        echo "           Make sure the namspace directory exists and"
        echo "           you use quotes around the namespace_prefix."
        echo ""
        display_syntax
        exit
    fi
}

function makeDirectories(){
    echo "Make Directories"
    echo "================"
    mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
    mkdir -p ${namespace_prefix_lowerfirstchar}/Providers
    mkdir -p ${namespace_prefix_lowerfirstchar}/Facades
}

function createSourceTemplate(){
    source_template=$(echo "${source_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create Source Template:"
    echo "======================="
    echo "${source_template}"
    echo ""
    echo "${source_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}.php
}

function createServiceProviderTemplate(){
    serviceProvider_template=$(echo "${serviceProvider_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create ServiceProvider Template:"
    echo "================================"
    echo "${serviceProvider_template}"
    echo ""
    echo "${serviceProvider_template}" > ./${namespace_prefix_lowerfirstchar}/Providers/${facade_name_upcase}ServiceProvider.php
}

function createFacadeTemplate(){
    facade_template=$(echo "${facade_template}" | sed -e 's/{namespace_prefix}/'${namespace_prefix}'/g' -e 's/{facade_name_upcase}/'${facade_name_upcase}'/g' -e 's/{facade_name_lowercase}/'${facade_name_lowercase}'/g')
    echo "Create Facade Template:"
    echo "======================="
    echo "${facade_template}"
    echo ""
    echo "${facade_template}" > ./${namespace_prefix_lowerfirstchar}/Facades/${facade_name_upcase}Facade.php
}


function serviceProviderPrompt(){
    echo "Providers: ${namespace_prefix_in}\Providers\\${facade_name_upcase}ServiceProvider,"
}

function aliasPrompt(){
    echo "Alias: '"${facade_name_upcase}"' => '"${namespace_prefix_in}"\Facades\\${facade_name_upcase}Facade'," 
}

#
#   END FUNCTION DECLARATIONS
#


###########################
## START RUNNING SCRIPT  ##
###########################

display_start_banner

init_and_export_vars
makeDirectories 
checkDirectoryExists
echo ""

createSourceTemplate
createServiceProviderTemplate
createFacadeTemplate
echo ""
echo "==========================="
echo "  Finished TEST"
echo "==========================="
echo ""
echo "Add these lines to config/app.php:"
echo "----------------------------------"
serviceProviderPrompt
aliasPrompt
echo ""

Access a global variable in a PHP function

PHP can be frustrating for this reason. The answers above using global did not work for me, and it took me awhile to figure out the proper use of use.

This is correct:

$functionName = function($stuff) use ($globalVar) {
 //do stuff
}
$output = $functionName($stuff);
$otherOutput = $functionName($otherStuff);

This is incorrect:

function functionName($stuff) use ($globalVar) {
 //do stuff
}
$output = functionName($stuff);
$otherOutput = functionName($otherStuff);

Using your specific example:

    $data = 'My data';

    $menugen = function() use ($data) {
        echo "[" . $data . "]";
    }

    $menugen();

How to redirect the output of a PowerShell to a file during its execution

You might want to take a look at the cmdlet Tee-Object. You can pipe output to Tee and it will write to the pipeline and also to a file

SQLite Query in Android to count rows

how to get count column

final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;

int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);

This is the most concise and precise alternative. No need to handle cursors and their closing.

How to compare only date in moment.js

In my case i did following code for compare 2 dates may it will help you ...

_x000D_
_x000D_
var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
 console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
 console.log('date2 is Less than date1');_x000D_
}else{_x000D_
 console.log('Both date are same');_x000D_
}
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Display last git commit comment

git log -1 branch_name will show you the last message from the specified branch (i.e. not necessarily the branch you're currently on).

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

Is there an auto increment in sqlite?

As of today — June 2018


Here is what official SQLite documentation has to say on the subject (bold & italic are mine):

  1. The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.

  2. In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed integer.

  3. On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.

  4. If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that changes the automatic ROWID assignment algorithm to prevent the reuse of ROWIDs over the lifetime of the database. In other words, the purpose of AUTOINCREMENT is to prevent the reuse of ROWIDs from previously deleted rows.

Python Save to file

You need to open the file again using open(), but this time passing 'w' to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open('Failed.txt', 'w') as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:
        f.write(ip)

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open('today','r') as myFile:
    for line in myFile:
        parts = line.split(' ')
        if parts[1] == 'Failure':
            if parts[0] in ips:
                ips[pars[0]] += 1
            else:
                ips[parts[0]] = 0

Iterate through Nested JavaScript Objects

modify from Peter Olson's answer: https://stackoverflow.com/a/8085118

  1. can avoid string value !obj || (typeof obj === 'string'
  2. can custom your key

var findObjectByKeyVal= function (obj, key, val) {
  if (!obj || (typeof obj === 'string')) {
    return null
  }
  if (obj[key] === val) {
    return obj
  }

  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      var found = findObjectByKeyVal(obj[i], key, val)
      if (found) {
        return found
      }
    }
  }
  return null
}

SQLAlchemy default DateTime

DateTime doesn't have a default key as an input. The default key should be an input to the Column function. Try this:

import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'

    id = Column(Integer, primary_key=True)
    created_date = Column(DateTime, default=datetime.datetime.utcnow)

Mocking member variables of a class using Mockito

If you want an alternative to ReflectionTestUtils from Spring in mockito, use

Whitebox.setInternalState(first, "second", sec);

DROP IF EXISTS VS DROP?

It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

From SQL Server 2016+ you can use

DROP TABLE IF EXISTS dbo.Table

For SQL Server <2016 what I do is the following for a permanent table

IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL 
  DROP TABLE dbo.Table; 

Or this, for a temporary table

IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
  DROP TABLE #T; 

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in my case just

const myReducers = combineReducers({
  user: UserReducer
});

const store: any = createStore(
  myReducers,
  applyMiddleware(thunk)
);

shallow(<Login />, { context: { store } });

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.

The issue is when you have e.g. a controller;

angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
  // your code
})

The minification changes $scope and $q into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:

angular.module("MyApp")
  .controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
  // your code
}])

That should fix your problem.

Just to re-iterate, everything I've said is at the link the error message provides to you.

WooCommerce return product object by id

Alright, I deserve to be throttled. definitely an RTM but not for WooCommerce, for Wordpress. Solution found due to a JOLT cola (all hail JOLT cola).

TASK: Field named 'related_product_ids' added to a custom post type. So when that post is displayed mini product displays can be displayed with it.

PROBLEM: Was having a problem getting the multiple ids returned via WP_Query.

SOLUTION:

$related_id_list          = get_post_custom_values('related_product_ids');
    // Get comma delimited list from current post
$related_product_ids      = explode(",", trim($related_id_list[0],','));
    // Return an array of the IDs ensure no empty array elements from extra commas
$related_product_post_ids = array( 'post_type' => 'product', 
                                   'post__in'  => $related_product_ids,
                                   'meta_query'=> array( 
                                        array( 'key'    => '_visibility',
                                               'value'  => array('catalog', 'visible'),'compare' => 'IN'
                                        )
                            ) 
);      
    // Query to get all product posts matching given IDs provided it is a published post
$loop = new WP_Query( $related_posts );
    // Execute query
while ( $loop->have_posts() ) : $loop->the_post(); $_product = get_product( $loop->post->ID );
    // Do stuff here to display your products 
endwhile;

Thank you for anyone who may have spent some time on this.

Tim

Difference between clustered and nonclustered index

A comparison of a non-clustered index with a clustered index with an example

As an example of a non-clustered index, let’s say that we have a non-clustered index on the EmployeeID column. A non-clustered index will store both the value of the

EmployeeID

AND a pointer to the row in the Employee table where that value is actually stored. But a clustered index, on the other hand, will actually store the row data for a particular EmployeeID – so if you are running a query that looks for an EmployeeID of 15, the data from other columns in the table like

EmployeeName, EmployeeAddress, etc

. will all actually be stored in the leaf node of the clustered index itself.

This means that with a non-clustered index extra work is required to follow that pointer to the row in the table to retrieve any other desired values, as opposed to a clustered index which can just access the row directly since it is being stored in the same order as the clustered index itself. So, reading from a clustered index is generally faster than reading from a non-clustered index.

What is a daemon thread in Java?

Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.

Simple way to query connected USB devices info in Python?

If you are working on windows, you can use pywin32 (old link: see update below).

I found an example here:

import win32com.client

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    print usb.DeviceID

Update Apr 2020:

'pywin32' release versions from 218 and up can be found here at github. Current version 227.

Multidimensional Lists in C#

If for some reason you don't want to define a Person class and use List<Person> as advised, you can use a tuple, such as (C# 7):

var people = new List<(string Name, string Email)>
{
  ("Joe Bloggs", "[email protected]"),
  ("George Forman", "[email protected]"),
  ("Peter Pan", "[email protected]")
};

var georgeEmail = people[1].Email;

The Name and Email member names are optional, you can omit them and access them using Item1 and Item2 respectively.

There are defined tuples for up to 8 members.

For earlier versions of C#, you can still use a List<Tuple<string, string>> (or preferably ValueTuple using this NuGet package), but you won't benefit from customized member names.

UnicodeDecodeError, invalid continuation byte

It is invalid UTF-8. That character is the e-acute character in ISO-Latin1, which is why it succeeds with that codeset.

If you don't know the codeset you're receiving strings in, you're in a bit of trouble. It would be best if a single codeset (hopefully UTF-8) would be chosen for your protocol/application and then you'd just reject ones that didn't decode.

If you can't do that, you'll need heuristics.

Android: Remove all the previous activities from the back stack

In API level 11 or greater, use FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK flag on Intent to clear all the activity stack.

Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |  Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i);

Removing duplicates from a String in Java

import java.util.LinkedHashMap;
import java.util.Map.Entry;

public class Sol {

    public static void main(String[] args) {
        char[] str = "bananas".toCharArray();
        LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
        StringBuffer s = new StringBuffer();

        for(Character c : str){
            if(map.containsKey(c))
                map.put(c, map.get(c)+1);
            else
                map.put(c, 1);
        }

        for(Entry<Character,Integer> entry : map.entrySet()){
            s.append(entry.getKey());
        }

        System.out.println(s);
    }

}

Adding machineKey to web.config on web-farm sites

If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.

  1. Open IIS manager.
  2. If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
  3. Double-click the Machine Key icon in ASP.NET settings in the middle pane:
  4. MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
  5. Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.

Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

Since the syntaxes are equivalent (in MySQL anyhow), I prefer the INSERT INTO table SET x=1, y=2 syntax, since it is easier to modify and easier to catch errors in the statement, especially when inserting lots of columns. If you have to insert 10 or 15 or more columns, it's really easy to mix something up using the (x, y) VALUES (1,2) syntax, in my opinion.

If portability between different SQL standards is an issue, then maybe INSERT INTO table (x, y) VALUES (1,2) would be preferred.

And if you want to insert multiple records in a single query, it doesn't seem like the INSERT INTO ... SET syntax will work, whereas the other one will. But in most practical cases, you're looping through a set of records to do inserts anyhow, though there could be some cases where maybe constructing one large query to insert a bunch of rows into a table in one query, vs. a query for each row, might have a performance improvement. Really don't know.

Instagram API - How can I retrieve the list of people a user is following on Instagram

I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.

You need to use browser console from instagram.com tab to make it works.

let username = 'USERNAME'
let followers = [], followings = []
try {
  let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)

  res = await res.json()
  let userId = res.graphql.user.id

  let after = null, has_next = true
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_followed_by.page_info.has_next_page
      after = res.data.user.edge_followed_by.page_info.end_cursor
      followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followers', followers)

  has_next = true
  after = null
  while (has_next) {
    await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next = res.data.user.edge_follow.page_info.has_next_page
      after = res.data.user.edge_follow.page_info.end_cursor
      followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
        }
      }))
    })
  }
  console.log('Followings', followings)
} catch (err) {
  console.log('Invalid username')
}

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

How to add url parameter to the current url?

In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:

<script>
function addUrlParameter(name, value) {
  var searchParams = new URLSearchParams(window.location.search)
  searchParams.set(name, value)
  window.location.search = searchParams.toString()
}
</script>

<body>
...
  <a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>

How can I show and hide elements based on selected option with jQuery?

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

How to save and load numpy.array() data properly?

The most reliable way I have found to do this is to use np.savetxt with np.loadtxt and not np.fromfile which is better suited to binary files written with tofile. The np.fromfile and np.tofile methods write and read binary files whereas np.savetxt writes a text file. So, for example:

a = np.array([1, 2, 3, 4])
np.savetxt('test1.txt', a, fmt='%d')
b = np.loadtxt('test1.txt', dtype=int)
a == b
# array([ True,  True,  True,  True], dtype=bool)

Or:

a.tofile('test2.dat')
c = np.fromfile('test2.dat', dtype=int)
c == a
# array([ True,  True,  True,  True], dtype=bool)

I use the former method even if it is slower and creates bigger files (sometimes): the binary format can be platform dependent (for example, the file format depends on the endianness of your system).

There is a platform independent format for NumPy arrays, which can be saved and read with np.save and np.load:

np.save('test3.npy', a)    # .npy extension is added if not given
d = np.load('test3.npy')
a == d
# array([ True,  True,  True,  True], dtype=bool)

PHP array delete by value (not key)

Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)

array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)

function array_reject_value(array &$arrayToFilter, $deleteValue) {
    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if ($value !== $deleteValue) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)

function array_reject(array &$arrayToFilter, callable $rejectCallback) {

    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if (!$rejectCallback($value, $key)) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

So in our current example we can use the above functions as follows:

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

or even better: (as this give us a better syntax to use like the array_filter one)

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
    return $value === 401;
});

The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:

$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
    return $value >= $greaterOrEqualThan;
});

Border Radius of Table is not working

It works, this is a problem with the tool used: normalized CSS by jsFiddle is causing the problem by hiding you the default of browsers...
See http://jsfiddle.net/XvdX9/5/

EDIT:
normalize.css stylesheet from jsFiddle adds the instruction border-collapse: collapse to all tables and it renders them completely differently in CSS2.1:

Differences between the 2 models can be seen in this other fiddle: http://jsfiddle.net/XvdX9/11/ (with some transparencies on cells and an enormous border-radius on the top-left one, in order to see what happens on table vs its cells)

In the same CSS2.1 page about HTML tables, there are also explanations about what browsers should/could do with empty-cells in the separated borders model, the difference between border-style: none and border-style: hidden in the collapsing borders model, how width is calculated and which border should display if both table, row and cell elements define 3 different styles on the same border.

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

Solve error javax.mail.AuthenticationFailedException

2 possible reasons:

  • Your username may require the entire email id '[email protected]'
  • Most obvious: The password is wrong. Debug to see if the password being used is correct.

How to fix IndexError: invalid index to scalar variable

In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

Where to change the value of lower_case_table_names=2 on windows xampp

On linux I cannot set lower_case_table_names to 2 (it reverts to 0), but I can set it to 1.

Before changing this setting, do a complete dump of all databases, and drop all databases. You won't be able to drop them after setting lower_case_table_names to 1, because any uppercase characters in database or table names will prevent them from being referenced.

Then set lower_case_table_names to 1, restart MySQL, and re-load your data, which will convert everything to lowercase, including any subsequent queries made.

allowing only alphabets in text box using java script

From kosare comments, i have create an demo http://jsbin.com/aTUMeMAV/2/

HTML

      <form name="f" onsubmit="return onlyAlphabets()">
         <input type="text" name="nm">
         <div id="notification"></div>
         <input type="submit">
      </form>

javascript

  function onlyAlphabets() {

  var regex = /^[a-zA-Z]*$/;
  if (regex.test(document.f.nm.value)) {

      //document.getElementById("notification").innerHTML = "Watching.. Everything is Alphabet now";
      return true;
  } else {
      document.getElementById("notification").innerHTML = "Alphabets Only";
      return false;
  }


}

How do you delete all text above a certain line

Providing you know these vim commands:

1G -> go to first line in file
G -> go to last line in file

then, the following make more sense, are more unitary and easier to remember IMHO:

d1G -> delete starting from the line you are on, to the first line of file
dG -> delete starting from the line you are on, to the last line of file

Cheers.

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

My version is like this:

php on my server:

<?php
    header('content-type: application/json; charset=utf-8');

    $data = json_encode($_SERVER['REMOTE_ADDR']);


    $callback = filter_input(INPUT_GET, 
                 'callback',
                 FILTER_SANITIZE_STRING, 
                 FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW);
    echo $callback . '(' . $data . ');';
?>

jQuery on the page:

var self = this;
$.ajax({
    url: this.url + "getip.php",
    data: null,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp'

}).done( function( json ) {

    self.ip = json;

});

It works cross domain. It could use a status check. Working on that.

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

How do I properly escape quotes inside HTML attributes?

You really should only allow untrusted data into a whitelist of good attributes like: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width

You really want to keep untrusted data out of javascript handlers as well as id or name attributes (they can clobber other elements in the DOM).

Also, if you are putting untrusted data into a SRC or HREF attribute, then its really a untrusted URL so you should validate the URL, make sure its NOT a javascript: URL, and then HTML entity encode.

More details on all of there here: https://www.owasp.org/index.php/Abridged_XSS_Prevention_Cheat_Sheet

Invert "if" statement to reduce nesting

Avoiding multiple exit points can lead to performance gains. I am not sure about C# but in C++ the Named Return Value Optimization (Copy Elision, ISO C++ '03 12.8/15) depends on having a single exit point. This optimization avoids copy constructing your return value (in your specific example it doesn't matter). This could lead to considerable gains in performance in tight loops, as you are saving a constructor and a destructor each time the function is invoked.

But for 99% of the cases saving the additional constructor and destructor calls is not worth the loss of readability nested if blocks introduce (as others have pointed out).

ORA-30926: unable to get a stable set of rows in the source tables

I was not able to resolve this after several hours. Eventually I just did a select with the two tables joined, created an extract and created individual SQL update statements for the 500 rows in the table. Ugly but beats spending hours trying to get a query to work.

How do I update the GUI from another thread?

Even if the operation is time-consuming (thread.sleep in my example) - This code will NOT lock your UI:

 private void button1_Click(object sender, EventArgs e)
 {

      Thread t = new Thread(new ThreadStart(ThreadJob));
      t.IsBackground = true;
      t.Start();         
 }

 private void ThreadJob()
 {
     string newValue= "Hi";
     Thread.Sleep(2000); 

     this.Invoke((MethodInvoker)delegate
     {
         label1.Text = newValue; 
     });
 }

PostgreSQL psql terminal command

Use \x Example from postgres manual:

    postgres=# \x
    postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
    -[ RECORD 1 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
    calls      | 3000
    total_time | 20.716706
    rows       | 3000
    -[ RECORD 2 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
    calls      | 3000
    total_time | 17.1107649999999
    rows       | 3000
    -[ RECORD 3 ]------------------------------------------------------------
    userid     | 10
    dbid       | 63781
    query      | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
    calls      | 3000
    total_time | 0.645601
    rows       | 3000

Visual Studio keyboard shortcut to display IntelliSense

If you have arrived at this question because IntelliSense has stopped working properly and you are hoping to force it to show you what you need, then most likely none of these solutions are going to work.

Closing and restarting Visual Studio should fix the problem.

Sass Variable in CSS calc() function

Interpolate:

body
    height: calc(100% - #{$body_padding})

For this case, border-box would also suffice:

body
    box-sizing: border-box
    height: 100%
    padding-top: $body_padding

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How to change value of object which is inside an array using JavaScript or jQuery?

We can also use Array's map function to modify object of an array using Javascript.

function changeDesc(value, desc){
   projects.map((project) => project.value == value ? project.desc = desc : null)
}

changeDesc('jquery', 'new description')

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Your service must answer an OPTIONS request with headers like these:

Access-Control-Allow-Origin: [the same origin from the request]
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: [the same ACCESS-CONTROL-REQUEST-HEADERS from request]

Here is a good doc: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server