Programs & Examples On #Findname

Accessing a resource via codebehind in WPF

I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below

{DefaultNamespace}.Properties.Resources.{ResourceName}

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

In my case, there was no string on which i was calling appendChild, the object i was passing on appendChild argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0]) instead of divel.appendChild(childel) and it worked. Hope it help someone.

how to avoid extra blank page at end while printing?

First, emulate the print stylesheet via your browser's devtools. Instructions can be found here.

Then you'll want to look for extra padding, margin, borders, etc that could be extending the dimensions of your pages beyond the 8.5in x 11in. Pay special attention to whitespace as this will be impossible to detect via the print preview dialog. If there is whitespace that shouldn't be there, right-clicking and inspecting the element under the cursor should highlight the issue (unless it's a margin causing it).

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

I was encountering the same problem. I had a Tooltip component that was receiving showTooltip prop, that I was updating on Parent component based on an if condition, it was getting updated in Parent component but Tooltip component was not rendering.

const Parent = () => {
   let showTooltip = false;
   if(....){ showTooltip = true; }
   return(
      <Tooltip showTooltip={showTooltip}></Tooltip>
   )
}

The mistake I was doing is to declare showTooltip as a let.

I realized what I was doing wrong I was violating the principles of how rendering works, Replacing it with hooks did the job.

const [showTooltip, setShowTooltip] =  React.useState<boolean>(false);

Functions are not valid as a React child. This may happen if you return a Component instead of from render

it also happens when you call a function from jsx directly rather than in an event. like

it will show the error if you write like

<h1>{this.myFunc}<h2>

it will go if you write:

<h1 onClick={this.myFunc}>Hit Me</h1>

Replace all spaces in a string with '+'

Do this recursively:

public String replaceSpace(String s){
    if (s.length() < 2) {
        if(s.equals(" "))
            return "+";
        else
            return s;
    }
    if (s.charAt(0) == ' ')
        return "+" + replaceSpace(s.substring(1));
    else
        return s.substring(0, 1) + replaceSpace(s.substring(1));
}

Count work days between two dates

For workdays, Monday to Friday, you can do it with a single SELECT, like this:

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'


SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate) * 2)
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
  -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)

If you want to include holidays, you have to work it out a bit...

How to replace all dots in a string using JavaScript

Simplest way

"Mr.".split('.').join("");

..............

Console

enter image description here

Create comma separated strings C#?

You can use the string.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...).

edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.

Profiling code (of course run in release without debug symbols):

class Program
{
    static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        string r;
        int iter = 10000;

        string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringJoin(",", values);
        sw.Stop();
        Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringBuilderAppend(",", values);
        sw.Stop();
        Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
        Console.ReadLine();
    }

    static string StringJoin(string seperator, params string[] values)
    {
        return string.Join(seperator, values);
    }

    static string StringBuilderAppend(string seperator, params string[] values)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(values[0]);
        for (int i = 1; i < values.Length; i++)
        {
            builder.Append(seperator);
            builder.Append(values[i]);
        }
        return builder.ToString();
    }
}

string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.

remove white space from the end of line in linux

sed -i 's/[[:blank:]]\{1,\}$//' YourFile

[:blank:] is for space, tab mainly and {1,} to exclude 'no space at the end' of the substitution process (no big significant impact if line are short and file are small)

C# Sort and OrderBy comparison

I think it's important to note another difference between Sort and OrderBy:

Suppose there exists a Person.CalculateSalary() method, which takes a lot of time; possibly more than even the operation of sorting a large list.

Compare

// Option 1
persons.Sort((p1, p2) => Compare(p1.CalculateSalary(), p2.CalculateSalary()));
// Option 2
var query = persons.OrderBy(p => p.CalculateSalary()); 

Option 2 may have superior performance, because it only calls the CalculateSalary method n times, whereas the Sort option might call CalculateSalary up to 2n log(n) times, depending on the sort algorithm's success.

Delete first character of a string in Javascript

var test = '0test';
test = test.replace(/0(.*)/, '$1');

How do I run Java .class files?

You need to set the classpath to find your compiled class:

java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2

How do I put variable values into a text string in MATLAB?

As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.


With respect to getting ans = 3 as an output, it is probably because you are not assigning the output from answer to a variable. If you want to get all of the output values, you will have to call answer in the following way:

[out1,out2,out3] = answer(1,2);

This will place the value d in out1, the value e in out2, and the value f in out3. When you do the following:

answer(1,2)

MATLAB will automatically assign the first output d (which has the value 3 in this case) to the default workspace variable ans.


With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.

How can I make a div not larger than its contents?

You can try fit-content (CSS3):

div {
  width: fit-content; 
  /* To adjust the height as well */ 
  height: fit-content;
}

Is there an auto increment in sqlite?

Yes, this is possible. According to the SQLite FAQ:

A column declared INTEGER PRIMARY KEY will autoincrement.

How to randomize (or permute) a dataframe rowwise and columnwise?

This is another way to shuffle the data.frame using package dplyr:

row-wise:

df2 <- slice(df1, sample(1:n()))

or

df2 <- sample_frac(df1, 1L)

column-wise:

df2 <- select(df1, one_of(sample(names(df1)))) 

How to get all selected values of a multiple select box?

Check this:

HTML:

<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>

Javascript one line code

Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

How to remove items from a list while iterating?

Your best approach for such an example would be a list comprehension

somelist = [tup for tup in somelist if determine(tup)]

In cases where you're doing something more complex than calling a determine function, I prefer constructing a new list and simply appending to it as I go. For example

newlist = []
for tup in somelist:
    # lots of code here, possibly setting things up for calling determine
    if determine(tup):
        newlist.append(tup)
somelist = newlist

Copying the list using remove might make your code look a little cleaner, as described in one of the answers below. You should definitely not do this for extremely large lists, since this involves first copying the entire list, and also performing an O(n) remove operation for each element being removed, making this an O(n^2) algorithm.

for tup in somelist[:]:
    # lots of code here, possibly setting things up for calling determine
    if determine(tup):
        newlist.append(tup)

git push: permission denied (public key)

I was facing same problem, here is what I did that worked for me.

Use ssh instead of http. Remove origin if its http.

git remote rm origin

Add ssh url

git remote add origin [email protected]:<username>/<repo>.git

Generate ssh key inside .ssh/ folder. It will ask for path and passphrase where you can just press enter and proceed.

cd ~/.ssh
ssh-keygen

Copy the key. You can view your key using. If you hadn't specified a different path then this is the default one.

cat ~/.ssh/id_rsa.pub

Add this key to your github account. Next do

ssh -T [email protected]

You will get a welcome message in your console.

cd into to your project folder. git push -u origin master now works!

Good ways to manage a changelog using git?

Since creating a tag per version is the best practice, you may want to partition your changelog per version. In that case, this command could help you:

git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B

Pytorch reshape tensor dimension

Assume the following code:

import torch
import numpy as np
a = torch.tensor([1, 2, 3, 4, 5])

The following three calls have the exact same effect:

res_1 = a.unsqueeze(0)
res_2 = a.view(1, 5)
res_3 = a[np.newaxis,:]
res_1.shape == res_2.shape == res_3.shape == (1,5)  # Returns true

Notice that for any of the resulting tensors, if you modify the data in them, you are also modifying the data in a, because they don't have a copy of the data, but reference the original data in a.

res_1[0,0] = 2
a[0] == res_1[0,0] == 2  # Returns true

The other way of doing it would be using the resize_ in place operation:

a.shape == res_1.shape  # Returns false
a.reshape_((1, 5))
a.shape == res_1.shape # Returns true

Be careful of using resize_ or other in-place operation with autograd. See the following discussion: https://pytorch.org/docs/stable/notes/autograd.html#in-place-operations-with-autograd

SQL JOIN vs IN performance?

A interesting writeup on the logical differences: SQL Server: JOIN vs IN vs EXISTS - the logical difference

I am pretty sure that assuming that the relations and indexes are maintained a Join will perform better overall (more effort goes into working with that operation then others). If you think about it conceptually then its the difference between 2 queries and 1 query.

You need to hook it up to the Query Analyzer and try it and see the difference. Also look at the Query Execution Plan and try to minimize steps.

How do I import an SQL file using the command line in MySQL?

You can use:

mysql -u<user> -p<pass> <db> < db.sql

Example:

mysql -uroot -proot db < db.sql

How to upgrade docker-compose to latest version

The easiest way to have a permanent and sustainable solution for the Docker Compose installation and the way to upgrade it, is to just use the package manager pip with:

pip install docker-compose

I was searching for a good solution for the ugly "how to upgrade to the latest version number"-problem, which appeared after you´ve read the official docs - and just found it occasionally - just have a look at the docker-compose pip package - it should reflect (mostly) the current number of the latest released Docker Compose version.

A package manager is always the best solution if it comes to managing software installations! So you just abstract from handling the versions on your own.

How to list all the files in android phone by using adb shell?

This command will show also if the file is hidden adb shell ls -laR | grep filename

How to get docker-compose to always re-create containers from fresh images?

By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:

docker-compose down

Then if you have new changes on your images or Dockerfiles use:

docker-compose build --no-cache

Finally:docker-compose up

In one command: docker-compose down && docker-compose build --no-cache && docker-compose up

How to avoid page refresh after button click event in asp.net

html

 "input type ="text" id="txtnothing" runat ="server" "

javacript

var txt = document.getElementById("txtnothing");
        txt.value =  Date.now();

code

 If Not (Session("txtnothing") Is Nothing OrElse String.IsNullOrEmpty(Session("txtnothing"))) Then
            If Session("txtnothing") = txtnothing.Value Then
                lblMsg.Text = "Please try again not a valid request"
                Exit Sub
            End If
        End If
        Session("txtnothing") = txtnothing.Value

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

New solution:

The node module can't handle : in a password properly. Even url encoded, like it would work normally, it does not work.

Don't use typicalspecial characters from an URL in the password!

Like one of the following: : . ? + %


Original, wrong answer:

The error message clearly complains about using PLAIN, it does not mean the crendentials are wrong, it means you must use encrypted data delivery (TLS) instead of plaintext.

Changing amqp:// in the connection string to amqps:// (note the s) solves this.

How can I pad a value with leading zeros?

Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!

function zerofill(number, length) {
    // Setup
    var result = number.toString();
    var pad = length - result.length;

    while(pad > 0) {
        result = '0' + result;
        pad--;
    }

    return result;
}

Object of class stdClass could not be converted to string - laravel

Try this simple in one line of code:-

$data= json_decode( json_encode($data), true);

Hope it helps :)

Calling startActivity() from outside of an Activity context

Either

  • cache the Context object via constructor in your adapter, or
  • get it from your view.

Or as a last resort,

  • add - FLAG_ACTIVITY_NEW_TASK flag to your intent:

_

myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.

How to save Excel Workbook to Desktop regardless of user?

I think this is the most reliable way to get the desktop path which isn't always the same as the username.

MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

Invoking modal window in AngularJS Bootstrap UI using JavaScript

To make angular ui $modal work with bootstrap 3 you need to overwrite the styles

.modal {
    display: block;
}
.modal-body:before,
.modal-body:after {
    display: table;
    content: " ";
}
.modal-header:before,
.modal-header:after {
    display: table;
    content: " ";
}

(The last ones are necessary if you use custom directives) and encapsulate the html with

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">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><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

How to get error message when ifstream open fails

Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno) would return.

std::ifstream f;

// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);

try {
    f.open(fileName);
} catch (std::system_error& e) {
    std::cerr << e.code().message() << std::endl;
}

This prints No such file or directory. if fileName doesn't exist.

Convert an image to grayscale in HTML/CSS

One terrible but workable solution: render the image using a Flash object, which then gives you all the transformations possible in Flash.

If your users are using bleeding-edge browsers and if Firefox 3.5 and Safari 4 support it (I don't know that either do/will), you could adjust the CSS color-profile attribute of the image, setting it to a grayscale ICC profile URL. But that's a lot of if's!

setState() inside of componentDidUpdate()

If you use setState inside componentDidUpdate it updates the component, resulting in a call to componentDidUpdate which subsequently calls setState again resulting in the infinite loop. You should conditionally call setState and ensure that the condition violating the call occurs eventually e.g:

componentDidUpdate: function() {
    if (condition) {
        this.setState({..})
    } else {
        //do something else
    }
}

In case you are only updating the component by sending props to it(it is not being updated by setState, except for the case inside componentDidUpdate), you can call setState inside componentWillReceiveProps instead of componentDidUpdate.

fs.writeFile in a promise, asynchronous-synchronous stuff

say

const util = require('util')
const fs_writeFile = util.promisify(fs.writeFile)

https://nodejs.org/api/util.html#util_util_promisify_original

this is less prone to bugs than the top-voted answer

How to get the insert ID in JDBC?

  1. Create Generated Column

    String generatedColumns[] = { "ID" };
    
  2. Pass this geneated Column to your statement

    PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
    
  3. Use ResultSet object to fetch the GeneratedKeys on Statement

    ResultSet rs = stmtInsert.getGeneratedKeys();
    
    if (rs.next()) {
        long id = rs.getLong(1);
        System.out.println("Inserted ID -" + id); // display inserted record
    }
    

How to find event listeners on a DOM node when debugging or from the JavaScript code?

I am trying to do that in jQuery 2.1, and with the "$().click() -> $(element).data("events").click;" method it doesn't work.

I realized that only the $._data() functions works in my case :

_x000D_
_x000D_
 $(document).ready(function(){_x000D_
_x000D_
  var node = $('body');_x000D_
  _x000D_
        // Bind 3 events to body click_x000D_
  node.click(function(e) { alert('hello');  })_x000D_
   .click(function(e) { alert('bye');  })_x000D_
   .click(fun_1);_x000D_
_x000D_
        // Inspect the events of body_x000D_
  var events = $._data(node[0], "events").click;_x000D_
  var ev1 = events[0].handler // -> function(e) { alert('hello')_x000D_
  var ev2 = events[1].handler // -> function(e) { alert('bye')_x000D_
  var ev3 = events[2].handler // -> function fun_1()_x000D_
        _x000D_
  $('body')_x000D_
   .append('<p> Event1 = ' + eval(ev1).toString() + '</p>')_x000D_
   .append('<p> Event2 = ' + eval(ev2).toString() + '</p>')_x000D_
   .append('<p> Event3 = ' + eval(ev3).toString() + '</p>');        _x000D_
 _x000D_
 });_x000D_
_x000D_
 function fun_1() {_x000D_
  var txt = 'text del missatge';  _x000D_
  alert(txt);_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Why are exclamation marks used in Ruby methods?

Simple explanation:

foo = "BEST DAY EVER" #assign a string to variable foo.

=> foo.downcase #call method downcase, this is without any exclamation.

"best day ever"  #returns the result in downcase, but no change in value of foo.

=> foo #call the variable foo now.

"BEST DAY EVER" #variable is unchanged.

=> foo.downcase! #call destructive version.

=> foo #call the variable foo now.

"best day ever" #variable has been mutated in place.

But if you ever called a method downcase! in the explanation above, foo would change to downcase permanently. downcase! would not return a new string object but replace the string in place, totally changing the foo to downcase. I suggest you don't use downcase! unless it is totally necessary.

Is it possible to read from a InputStream with a timeout?

Here is a way to get a NIO FileChannel from System.in and check for availability of data using a timeout, which is a special case of the problem described in the question. Run it at the console, don't type any input, and wait for the results. It was tested successfully under Java 6 on Windows and Linux.

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;

public class Main {

    static final ByteBuffer buf = ByteBuffer.allocate(4096);

    public static void main(String[] args) {

        long timeout = 1000 * 5;

        try {
            InputStream in = extract(System.in);
            if (! (in instanceof FileInputStream))
                throw new RuntimeException(
                        "Could not extract a FileInputStream from STDIN.");

            try {
                int ret = maybeAvailable((FileInputStream)in, timeout);
                System.out.println(
                        Integer.toString(ret) + " bytes were read.");

            } finally {
                in.close();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /* unravels all layers of FilterInputStream wrappers to get to the
     * core InputStream
     */
    public static InputStream extract(InputStream in)
            throws NoSuchFieldException, IllegalAccessException {

        Field f = FilterInputStream.class.getDeclaredField("in");
        f.setAccessible(true);

        while( in instanceof FilterInputStream )
            in = (InputStream)f.get((FilterInputStream)in);

        return in;
    }

    /* Returns the number of bytes which could be read from the stream,
     * timing out after the specified number of milliseconds.
     * Returns 0 on timeout (because no bytes could be read)
     * and -1 for end of stream.
     */
    public static int maybeAvailable(final FileInputStream in, long timeout)
            throws IOException, InterruptedException {

        final int[] dataReady = {0};
        final IOException[] maybeException = {null};
        final Thread reader = new Thread() {
            public void run() {                
                try {
                    dataReady[0] = in.getChannel().read(buf);
                } catch (ClosedByInterruptException e) {
                    System.err.println("Reader interrupted.");
                } catch (IOException e) {
                    maybeException[0] = e;
                }
            }
        };

        Thread interruptor = new Thread() {
            public void run() {
                reader.interrupt();
            }
        };

        reader.start();
        for(;;) {

            reader.join(timeout);
            if (!reader.isAlive())
                break;

            interruptor.start();
            interruptor.join(1000);
            reader.join(1000);
            if (!reader.isAlive())
                break;

            System.err.println("We're hung");
            System.exit(1);
        }

        if ( maybeException[0] != null )
            throw maybeException[0];

        return dataReady[0];
    }
}

Interestingly, when running the program inside NetBeans 6.5 rather than at the console, the timeout doesn't work at all, and the call to System.exit() is actually necessary to kill the zombie threads. What happens is that the interruptor thread blocks (!) on the call to reader.interrupt(). Another test program (not shown here) additionally tries to close the channel, but that doesn't work either.

Remove category & tag base from WordPress url - without a plugin

updated answer:

other solution:
In wp-includes/rewrite.php file, you'll see the code:
$this->category_structure = $this->front . 'category/'; just copy whole function, put in your functions.php and hook it. just change the above line with:
$this->category_structure = $this->front . '/';

Get size of all tables in database

Here is another method: using SQL Server Management Studio, in Object Explorer, go to your database and select Tables

enter image description here

Then open the Object Explorer Details (either by pressing F7 or going to View->Object Explorer Details). In the object explorer details page, right click on the column header and enable the columns that you would like to see in the page. You can sort the data by any column too.

enter image description here

How do I concatenate two lists in Python?

This is quite simple, and I think it was even shown in the tutorial:

>>> listone = [1,2,3]
>>> listtwo = [4,5,6]
>>>
>>> listone + listtwo
[1, 2, 3, 4, 5, 6]

Creating a UITableView Programmatically

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)theTableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    UITableViewCell *cell = (UITableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.descriptionLabel.text = @"Testing";
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Code for selection.
}

these are UITableView delegate methods.

Simpler way to create dictionary of separate variables?

I think my problem will help illustrate why this question is useful, and it may give a bit more insight into how to answer it. I wrote a small function to do a quick inline head check on various variables in my code. Basically, it lists the variable name, data type, size, and other attributes, so I can quickly catch any mistakes I've made. The code is simple:

def details(val):
  vn = val.__name__                 #  If such a thing existed
  vs = str(val)
  print("The Value of "+ str(vn) + " is " + vs)
  print("The data type of " + vn + " is " + str(type(val)))

So if you have some complicated dictionary / list / tuple situation, it would be quite helpful to have the interpreter return the variable name you assigned. For instance, here is a weird dictionary:

m = 'abracadabra'
mm=[]    
for n in m:
  mm.append(n)
mydic = {'first':(0,1,2,3,4,5,6),'second':mm,'third':np.arange(0.,10)}



details(mydic)

The Value of mydic is {'second': ['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a'], 'third': array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.]), 'first': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
The data type of mydic is <type 'dict'>

details(mydic['first'])
The Value of mydic['first'] is (0, 1, 2, 3, 4, 5, 6)]
The data type of mydic['first'] is <type 'list'>

details(mydic.keys())
The Value of mydic.keys() is ['second', 'third', 'first']
The data type of mydic.keys() is <type 'tuple'>

details(mydic['second'][0])
The Value of mydic['second'][0] is a
The data type of mydic['second'][0] is <type 'str'>

I'm not sure if I put this in the right place, but I thought it might help. I hope it does.

Capitalize the first letter of string in AngularJs

For Angular 2 and up, you can use {{ abc | titlecase }}.

Check Angular.io API for complete list.

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

That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.

(does it still work without the ToArray)?

Git:nothing added to commit but untracked files present

Also instead of adding each file manually, we could do something like:

git add --all

OR

git add -A

This will also remove any files not present or deleted (Tracked files in the current working directory which are now absent).

If you only want to add files which are tracked and have changed, you would want to do

git add -u

What is the difference between git add . & git add --all?

Cannot set content-type to 'application/json' in jQuery.ajax

Hi These two lines worked for me.

contentType:"application/json; charset=utf-8", dataType:"json"

 $.ajax({
            type: "POST",
            url: "/v1/candidates",
            data: obj,
            **contentType:"application/json; charset=utf-8",
            dataType:"json",**
            success: function (data) {
                table.row.add([
                    data.name, data.title
                ]).draw(false);
            }

Thanks, Prashant

How do I filter ForeignKey choices in a Django ModelForm?

This is simple, and works with Django 1.4:

class ClientAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ClientAdminForm, self).__init__(*args, **kwargs)
        # access object through self.instance...
        self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)

class ClientAdmin(admin.ModelAdmin):
    form = ClientAdminForm
    ....

You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):

ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to 
   override the default formfield for a foreign keys field. For example, 
   to return a subset of objects for this foreign key field based on the
   user:'''

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.

I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.

The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).

The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.

In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.

class FrontEndAdmin(models.ModelAdmin):
    def __init__(self, model, admin_site):
        self.model = model
        self.opts = model._meta
        self.admin_site = admin_site
        super(FrontEndAdmin, self).__init__(model, admin_site)

remove 'delete' buttons:

    def get_actions(self, request):
        actions = super(FrontEndAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

prevents delete permission

    def has_delete_permission(self, request, obj=None):
        return False

filters objects that can be viewed on the admin site:

    def get_queryset(self, request):
        if request.user.is_superuser:
            try:
                qs = self.model.objects.all()
            except AttributeError:
                qs = self.model._default_manager.get_queryset()
            return qs

        else:
            try:
                qs = self.model.objects.all()
            except AttributeError:
                qs = self.model._default_manager.get_queryset()

            if hasattr(self.model, ‘user’):
                return qs.filter(user=request.user)
            if hasattr(self.model, ‘porcupine’):
                return qs.filter(porcupine=request.user.porcupine)
            else:
                return qs

filters choices for all foreignkey fields on the admin site:

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if request.employee.is_superuser:
            return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

        else:
            if hasattr(db_field.rel.to, 'user'):
                kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
            if hasattr(db_field.rel.to, 'porcupine'):
                kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
            return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)

SQL Server 2008 Row Insert and Update timestamps

As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERTs that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP which it includes in the final INSERT to the database. You could do the same for the CREATE. You may also be able to set things up so that users cannot execute INSERT and CREATE statements other than via the stored procedures.

I have to admit that I haven't actually done this myself so I'm not at all sure of the details.

Attempted to read or write protected memory

Microsoft also released a hotfix (July 2nd, 2007) to prevent the error "Attempted to read or write protected memory" that has been plaguing the .NET 2.0 platform for some time now. Look at http://support.microsoft.com/kb/923028 - not sure if it applies to you, but thought you might like to check it out.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

If you need a general purpose conversion from a string which per se is not a bool, you should better write a routine similar to the one depicted below. In keeping with the spirit of duck typing, I have not silently passed the error but converted it as appropriate for the current scenario.

>>> def str2bool(st):
try:
    return ['false', 'true'].index(st.lower())
except (ValueError, AttributeError):
    raise ValueError('no Valid Conversion Possible')


>>> str2bool('garbaze')

Traceback (most recent call last):
  File "<pyshell#106>", line 1, in <module>
    str2bool('garbaze')
  File "<pyshell#105>", line 5, in str2bool
    raise TypeError('no Valid COnversion Possible')
TypeError: no Valid Conversion Possible
>>> str2bool('false')
0
>>> str2bool('True')
1

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template. (A full list of preset DisplayFormatString's can be found here.)

[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }

Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:

@model DateTime?
@if (Model.HasValue)
{
    @Model.Value.ToString("MM/dd/yyyy")
}

That will apply to all DateTimes, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:

[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }

The final option is to not use DisplayFor and instead render the property directly:

@if (Model.AuditDate.HasValue)
{
    @Model.AuditDate.Value.ToString("MM/dd/yyyy")
}

html text input onchange event

Use the oninput event

<input type="text" oninput="myFunction();" />

Android ListView selected item stay highlighted

To hold the color of listview item when you press it, include the following line in your listview item layout:

android:background="@drawable/bg_key"

Then define bg_key.xml in drawable folder like this:

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true"
        android:drawable="@color/pressed_color"/>
    <item
        android:drawable="@color/default_color" />
</selector>

Finally, include this in your ListView onClickListener:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
        view.setSelected(true);
        ... // Anything
    }
});

This way, only one item will be color-selected at any time. You can define your color values in res/values/colors.xml with something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="pressed_color">#4d90fe</color>
    <color name="default_color">#ffffff</color>
</resources>

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

(CI 3) For me, what worked was changing:

'hostname' => 'localhost' to 'hostname' => '127.0.0.1'

Creating runnable JAR with Gradle

Here is the solution I tried with Gradle 6.7

Runnable fat Jar (with all dependent libraries copied to the jar)

task fatJar(type: Jar) {
   
    manifest {
        attributes 'Main-Class': 'com.example.gradle.App'
    }
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    } with jar
    
}

Runnable jar with all dependencies copied to a directory and adding the classpath to the manifest

    def dependsDir = "${buildDir}/libs/dependencies/"
    task copyDependencies(type: Copy) {
        from configurations.compile
        into "${dependsDir}"
    }
    task createJar(dependsOn: copyDependencies, type: Jar) {
      
        manifest {
            attributes('Main-Class': 'com.example.gradle.App',
                    'Class-Path': configurations.compile.collect { 'dependencies/' + it.getName() }.join(' ')
            )
        }
        with jar
    }

How to use ?

  • Add the above tasks to build.gradle
  • Execute gradle fatJar //create fatJar
  • Execute gradle createJar // create jar with dependencies copied.

More details : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d

Case-Insensitive List Search

I realise this is an old post, but just in case anyone else is looking, you can use Contains by providing the case insensitive string equality comparer like so:

using System.Linq;

// ...

if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Keyword Exists");
}

This has been available since .net 2.0 according to msdn.

How to get height of Keyboard?

Swift 5

override func viewDidLoad() {
    //  Registering for keyboard notification.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}


/*  UIKeyboardWillShowNotification. */
    @objc internal func keyboardWillShow(_ notification : Notification?) -> Void {
        
        var _kbSize:CGSize!
        
        if let info = notification?.userInfo {

            let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
            
            //  Getting UIKeyboardSize.
            if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
                
                let screenSize = UIScreen.main.bounds
                
                //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
                let intersectRect = kbFrame.intersection(screenSize)
                
                if intersectRect.isNull {
                    _kbSize = CGSize(width: screenSize.size.width, height: 0)
                } else {
                    _kbSize = intersectRect.size
                }
                print("Your Keyboard Size \(_kbSize)")
            }
        }
    }

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

HTML

<form id="some_form">
<!-- some form elements -->
</form>

and jquery

$("#some_form").reset();

Javascript switch vs. if...else if...else

The performance difference between a switch and if...else if...else is small, they basically do the same work. One difference between them that may make a difference is that the expression to test is only evaluated once in a switch while it's evaluated for each if. If it's costly to evaluate the expression, doing it one time is of course faster than doing it a hundred times.

The difference in implementation of those commands (and all script in general) differs quite a bit between browsers. It's common to see rather big performance differences for the same code in different browsers.

As you can hardly performance test all code in all browsers, you should go for the code that fits best for what you are doing, and try to reduce the amount of work done rather than optimising how it's done.

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

How do I convert two lists into a dictionary?

You can also use dictionary comprehensions in Python = 2.7:

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> {k: v for k, v in zip(keys, values)}
{'food': 'spam', 'age': 42, 'name': 'Monty'}

What is the default maximum heap size for Sun's JVM from Java SE 6?

To answer this question it's critical whether the Java VM is in CLIENT or SERVER mode. You can specify "-client" or "-server" options. Otherwise java uses internal rules; basically win32 is always client and Linux is always server, but see the table here:

http://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html

Sun/Oracle jre6u18 doc says re client: the VM gets 1/2 of physical memory if machine has <= 192MB; 1/4 of memory if machine has <= 1Gb; max 256Mb. In my test on a 32bit WindowsXP system with 2Gb phys mem, Java allocated 256Mb, which agrees with the doc.

Sun/Oracle jre6u18 doc says re server: same as client, then adds confusing language: for 32bit JVM the default max is 1Gb, and for 64 bit JVM the default is 32Gb. In my test on a 64bit linux machine with 8Gb physical, Java allocates 2Gb, which is 1/4 of physical; on a 64bit linux machine with 128Gb physical Java allocates 32Gb, again 1/4 of physical.

Thanks to this SO post for guiding me:

Definition of server-class machine changed recently?

How do I simulate a hover with a touch in touch enabled browsers?

A mix of native Javascript and jQuery:

var gFireEvent = function (oElem,sEvent) 
{
 try {
 if( typeof sEvent == 'string' && o.isDOM( oElem ))
 {
  var b = !!(document.createEvent),
     evt = b?document.createEvent("HTMLEvents"):document.createEventObject();
  if( b )    
  {  evt.initEvent(sEvent, true, true ); 
    return !oElem.dispatchEvent(evt);
  }
  return oElem.fireEvent('on'+sEvent,evt);
 }
 } catch(e) {}
 return false;
};


// Next you can do is (bIsMob etc you have to determine yourself):

   if( <<< bIsMob || bIsTab || bisTouch >>> )
   {
     $(document).on('mousedown', function(e)
     {
       gFireEvent(e.target,'mouseover' );
     }).on('mouseup', function(e)
     {
       gFireEvent(e.target,'mouseout' );
     });
   }

How do I write a bash script to restart a process if it dies?

I'm not sure how portable it is across operating systems, but you might check if your system contains the 'run-one' command, i.e. "man run-one". Specifically, this set of commands includes 'run-one-constantly', which seems to be exactly what is needed.

From man page:

run-one-constantly COMMAND [ARGS]

Note: obviously this could be called from within your script, but also it removes the need for having a script at all.

Changing button color programmatically

use jquery :  $("#id").css("background","red");

How to get difference between two dates in Year/Month/Week/Day?

int day=0,month=0,year=0;
DateTime smallDate = Convert.ToDateTime(string.Format("{0}", "01.01.1900"));
DateTime bigDate = Convert.ToDateTime(string.Format("{0}", "05.06.2019"));
TimeSpan timeSpan = new TimeSpan();

//timeSpan is diff between bigDate and smallDate as days
timeSpan = bigDate - smallDate;

//year is totalDays / 365 as int
year = timeSpan.Days / 365;

//smallDate.AddYears(year) is closing the difference for year because we found the year variable
smallDate = smallDate.AddYears(year);

//again subtraction because we don't need the year now
timeSpan = bigDate - smallDate;

//month is totalDays / 30 as int
month = timeSpan.Days / 30;

//smallDate.AddMonths(month) is closing the difference for month because we found the month variable
smallDate = smallDate.AddMonths(month);
if (bigDate > smallDate)
{
    timeSpan = bigDate - smallDate;
    day = timeSpan.Days;
}
//else it is mean already day is 0

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

What is the most efficient/elegant way to parse a flat table into a tree?

Bill's answer is pretty gosh-darned good, this answer adds some things to it which makes me wish SO supported threaded answers.

Anyway I wanted to support the tree structure and the Order property. I included a single property in each Node called leftSibling that does the same thing Order is meant to do in the original question (maintain left-to-right order).

mysql> desc nodes ;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(255) | YES  |     | NULL    |                |
| leftSibling | int(11)      | NO   |     | 0       |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc adjacencies;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| relationId | int(11) | NO   | PRI | NULL    | auto_increment |
| parent     | int(11) | NO   |     | NULL    |                |
| child      | int(11) | NO   |     | NULL    |                |
| pathLen    | int(11) | NO   |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

More detail and SQL code on my blog.

Thanks Bill your answer was helpful in getting started!

I got error "The DELETE statement conflicted with the REFERENCE constraint"

Have you considered applying ON DELETE CASCADE where relevant?

XSLT string replace

Note: In case you wish to use the already-mentioned algo for cases where you need to replace huge number of instances in the source string (e.g. new lines in long text) there is high probability you'll end up with StackOverflowException because of the recursive call.

I resolved this issue thanks to Xalan's (didn't look how to do it in Saxon) built-in Java type embedding:

<xsl:stylesheet version="1.0" exclude-result-prefixes="xalan str"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xalan="http://xml.apache.org/xalan"
                xmlns:str="xalan://java.lang.String"
        >
...
<xsl:value-of select="str:replaceAll(
    str:new(text()),
    $search_string,
    $replace_string)"/>
...
</xsl:stylesheet>

Can't bind to 'routerLink' since it isn't a known property

You need to add RouterMoudle into imports sections of the module containing the Header component

Setting PayPal return URL and making it auto return?

one way i have found:

try to insert this field into your generated form code:

<input type='hidden' name='rm' value='2'>

rm means return method;

2 means (post)

Than after user purchases and returns to your site url, then that url gets the POST parameters as well

p.s. if using php, try to insert var_dump($_POST); in your return url(script),then make a test purchase and when you return back to your site you will see what variables are got on your url.

How can I change text color via keyboard shortcut in MS word 2010

Alt+H, then type letters FC, then pick the color.

SQL GROUP BY CASE statement with aggregate function

While Shannon's answer is technically correct, it looks like overkill.

The simple solution is that you need to put your summation outside of the case statement. This should do the trick:

sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product

Basically, your old code tells SQL to execute the sum(X*Y) for each line individually (leaving each line with its own answer that can't be grouped).

The code line I have written takes the sum product, which is what you want.

Parse error: Syntax error, unexpected end of file in my PHP code

Avoid this as well <? } ?> make sure you put <?php } ?>

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

If you could somehow locate mongod.log and the do a grep over it

grep dbpath mongod.log

The value for dbpath is the data location for mongodb!! All the best :)

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

How do I replace text inside a div element?

$('field_name').innerHTML = 'Your text.';

One of the nifty features of Prototype is that $('field_name') does the same thing as document.getElementById('field_name'). Use it! :-)

John Topley's answer using Prototype's update function is another good solution.

jQuery hasClass() - check for more than one class

$.fn.extend({
    hasClasses: function (selectors) {
        var self = this;
        for (var i in selectors) {
            if ($(self).hasClass(selectors[i])) 
                return true;
        }
        return false;
    }
});

$('#element').hasClasses(['class1', 'class2', 'class3']);

This should do it, simple and easy.

How to assign more memory to docker container

That 2GB limit you see is the total memory of the VM in which docker runs.

If you are using docker-for-windows or docker-for-mac you can easily increase it from the Whale icon in the task bar, then go to Preferences -> Advanced:

Docker Preferences

But if you are using VirtualBox behind, open VirtualBox, Select and configure the docker-machine assigned memory.

See this for Mac:

https://docs.docker.com/docker-for-mac/#memory

MEMORY By default, Docker for Mac is set to use 2 GB runtime memory, allocated from the total available memory on your Mac. You can increase the RAM on the app to get faster performance by setting this number higher (for example to 3) or lower (to 1) if you want Docker for Mac to use less memory.

For Windows:

https://docs.docker.com/docker-for-windows/#advanced

Memory - Change the amount of memory the Docker for Windows Linux VM uses

Php, wait 5 seconds before executing an action

In https://www.php.net/manual/es/function.usleep.php

<?php
// Wait 2 seconds
usleep(2000000);

// if you need 5 seconds
usleep(5000000);
?>

Intellij IDEA Java classes not auto compiling on save

I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.

In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.

Javascript change font color

Don't use <font color=. It's a really old fashioned way to style text and some browsers even don't even support it anymore.

caniuse lists it as obsolete, and strongly recommends not using the <font> tag. The same is with MDN

Do not use this element! Though once normalized in HTML 3.2, it was deprecated in HTML 4.01, at the same time as all elements related to styling only, then obsoleted in HTML5.

Starting with HTML 4, HTML does not convey styling information anymore (outside the element or the style attribute of each element). For any new web development, styling should be written using CSS only.

The former behavior of the element can be achieved, and even better controlled using the CSS Fonts CSS properties.

If we look at when the 4.01 standard was published we see it was published in 1999

published html5 standard

where <font> was officially deprecated, meaning it is still supported but shouldn't be used anymore as it will go away in the newer standard.

And in the html5 standard released in August 2014 it was deemed obsolete and non conforming.

To achieve the desired effect use spans and css:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    return '<span style="color:'+thecolor+'">'+thetext+'</span>';
}
document.write(givemecolor('green',"Hello, I'm green"));
document.write(givemecolor('red',"Hello, I'm red"));
_x000D_
body {
  background: #333;
  color: #eee;
}
_x000D_
_x000D_
_x000D_

update

This question and answer are from 2012 and now I wouldn't recommend using document.write as it needs to be executed when the document is rendered first time. I had used it back then because I assumed OP was wishing to use it in such a way. I'd recommend using a more conventional way to insert the custom elements you wish to use, at the place you wish to insert them, without relying on document rendering and when and where the script is executed.

Native:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    var span = document.createElement('span');
    span.style.color = thecolor;
    span.innerText = thetext;
    return span;
}
var container = document.getElementById('textholder');
container.append(givemecolor('green', "Hello I'm green"));
container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
function givemecolor(thecolor, thetext)
{
    var $span = $("<span>");
    $span.css({color:thecolor});
    $span.text(thetext);
    return $span;
}
var $container = $('#textholder');
$container.append(givemecolor('green', "Hello I'm green"));
$container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

Spring JPA and persistence.xml

If anyone wants to use purely Java configuration instead of xml configuration of hibernate, use this:

You can configure Hibernate without using persistence.xml at all in Spring like like this:

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
Map<String, Object> properties = new Hashtable<>();
properties.put("javax.persistence.schema-generation.database.action",
"none");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); //you can change this if you have a different DB
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(adapter);
factory.setDataSource(this.springJpaDataSource());
factory.setPackagesToScan("package name");
factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factory.setValidationMode(ValidationMode.NONE);
factory.setJpaPropertyMap(properties);
return factory;
}

Since you are not using persistence.xml, you should create a bean that returns DataSource which you specify in the above method that sets the data source:

@Bean
public DataSource springJpaDataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:mysql://localhost/SpringJpa");
dataSource.setUsername("tomcatUser");
dataSource.setPassword("password1234");
return dataSource;
}

Then you use @EnableTransactionManagement annotation over this configuration file. Now when you put that annotation, you have to create one last bean:

@Bean
public PlatformTransactionManager jpaTransactionManager()
{
return new JpaTransactionManager(
this.entityManagerFactoryBean().getObject());
}

Now, don't forget to use @Transactional Annotation over those method that deal with DB.

Lastly, don't forget to inject EntityManager in your repository (This repository class should have @Repository annotation over it).

how to change a selections options based on another select option selected?

you can use data-tag in html5 and do this using this code:

_x000D_
_x000D_
<script>_x000D_
 $('#mainCat').on('change', function() {_x000D_
  var selected = $(this).val();_x000D_
  $("#expertCat option").each(function(item){_x000D_
   console.log(selected) ;  _x000D_
   var element =  $(this) ; _x000D_
   console.log(element.data("tag")) ; _x000D_
   if (element.data("tag") != selected){_x000D_
    element.hide() ; _x000D_
   }else{_x000D_
    element.show();_x000D_
   }_x000D_
  }) ; _x000D_
  _x000D_
  $("#expertCat").val($("#expertCat option:visible:first").val());_x000D_
  _x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<select id="mainCat">_x000D_
   <option value = '1'>navid</option>_x000D_
   <option value = '2'>javad</option>_x000D_
   <option value = '3'>mamal</option>_x000D_
  </select>_x000D_
  _x000D_
  <select id="expertCat">_x000D_
   <option  value = '1' data-tag='2'>UI</option>_x000D_
   <option  value = '2' data-tag='2'>Java Android</option>_x000D_
   <option  value = '3' data-tag='1'>Web</option>_x000D_
   <option  value = '3' data-tag='1'>Server</option>_x000D_
   <option  value = '3' data-tag='3'>Back End</option>_x000D_
   <option  value = '3' data-tag='3'>.net</option>_x000D_
  </select>
_x000D_
_x000D_
_x000D_

Android fade in and fade out with ImageView

For infinite Fade In and Out

AlphaAnimation fadeIn=new AlphaAnimation(0,1);

AlphaAnimation fadeOut=new AlphaAnimation(1,0);


final AnimationSet set = new AnimationSet(false);

set.addAnimation(fadeIn);
set.addAnimation(fadeOut);
fadeOut.setStartOffset(2000);
set.setDuration(2000);
imageView.startAnimation(set);

set.setAnimationListener(new Animation.AnimationListener() {
    @Override
    public void onAnimationStart(Animation animation) { }
    @Override
    public void onAnimationRepeat(Animation animation) { }
    @Override
    public void onAnimationEnd(Animation animation) {
        imageView.startAnimation(set);
    }
});

How to serialize SqlAlchemy result to JSON?

You can use introspection of SqlAlchemy as this :

mysql = SQLAlchemy()
from sqlalchemy import inspect

class Contacts(mysql.Model):  
    __tablename__ = 'CONTACTS'
    id = mysql.Column(mysql.Integer, primary_key=True)
    first_name = mysql.Column(mysql.String(128), nullable=False)
    last_name = mysql.Column(mysql.String(128), nullable=False)
    phone = mysql.Column(mysql.String(128), nullable=False)
    email = mysql.Column(mysql.String(128), nullable=False)
    street = mysql.Column(mysql.String(128), nullable=False)
    zip_code = mysql.Column(mysql.String(128), nullable=False)
    city = mysql.Column(mysql.String(128), nullable=False)
    def toDict(self):
        return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs }

@app.route('/contacts',methods=['GET'])
def getContacts():
    contacts = Contacts.query.all()
    contactsArr = []
    for contact in contacts:
        contactsArr.append(contact.toDict()) 
    return jsonify(contactsArr)

@app.route('/contacts/<int:id>',methods=['GET'])
def getContact(id):
    contact = Contacts.query.get(id)
    return jsonify(contact.toDict())

Get inspired from an answer here : Convert sqlalchemy row object to python dict

How does the "position: sticky;" property work?

The real behavior of a sticky element is:

  • First it is relative for a while
  • then it is fixed for a while
  • finally, it disappears from the view

A stickily positioned element is treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.

This value always creates a new stacking context. Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor.

This example will help you understand:

code https://codepen.io/darylljann/pen/PpjwPM

How do I get console input in javascript?

You can try something like process.argv, that is if you are using node.js to run the program.
console.log(process.argv) => Would print an array containing

[                                                                                                                                                                                          
  '/usr/bin/node',                                                                                                                                                                         
  '/home/user/path/filename.js',                                                                                                                                            
  'your_input'                                                                                                                                                                                   
]

You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


Example:

var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two

console.log(somevariable);
console.log(somevariable2);

If you are building a command-line program then the npm package yargs would be really helpful.

How to extract the decision rules from scikit-learn decision-tree?

Now you can use export_text.

from sklearn.tree import export_text

r = export_text(loan_tree, feature_names=(list(X_train.columns)))
print(r)

A complete example from [sklearn][1]

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
X = iris['data']
y = iris['target']
decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
decision_tree = decision_tree.fit(X, y)
r = export_text(decision_tree, feature_names=iris['feature_names'])
print(r)

How can I get selector from jQuery object

Are you trying to get the name of the current tag that was clicked?

If so, do this..

$("*").click(function(){
    alert($(this)[0].nodeName);
});

You can't really get the "selector", the "selector" in your case is *.

WAMP server, localhost is not working

The simplest solution is to disable the IIS service from the services snapin

(use the start menu -> search programs and files -> services.msc to launch the snapin )

This will stop IIS using port 80. Then change Apache back to using port 80.

How to get the file path from HTML input form in Firefox 3

This is an alternate solution/fix... In FF3, You can retrieve file's full path in a textbox instead of file browse box. And that too... By drag/dropping the file!

You can drag drop your file into a text box in your html page. and it will display the file's complete path. This data can transferred to your server easily or manipulate them.

All you have to do is to use the extension DragDropUpload

http://www.teslacore.it/wiki/index.php?title=DragDropUpload

This extension will helps you in drag dropping files into your File Browse (Input file) box. But still you wont able to get the file full path, If you try to retrieve.

So, I tweaked this extension a little. In the way I can drag drop a file on to any "Text Input" box and get the file full path. And thus I can able to get the file full path in FF3 Firefox 3.

"for loop" with two variables?

If you want the effect of a nested for loop, use:

import itertools
for i, j in itertools.product(range(x), range(y)):
    # Stuff...

If you just want to loop simultaneously, use:

for i, j in zip(range(x), range(y)):
    # Stuff...

Note that if x and y are not the same length, zip will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest.

UPDATE

Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip or product. I think they want a set:

def equal_elements(t1, t2):
    return list(set(t1).intersection(set(t2)))
    # You could also do
    # return list(set(t1) & set(t2))

The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists to tuples first so that they are hashable; otherwise the call to set will fail.). The list function then turns the set back into a list.

UPDATE 2

OR, the OP might want elements that are identical in the same position in the lists. In this case, zip would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:

def equal_elements(t1, t2):
    return [x for x, y in zip(t1, t2) if x == y]

This will return a list containing only the elements that are the same and in the same position in the lists.

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Android Studio 3.0 Execution failed for task: unable to merge dex

Also be sure your app is subclassing MultiDexApplication

import android.support.multidex.MultiDexApplication

class App : MultiDexApplication()

or if not subclassing Application class, add to AndroidManifest.xml

<application
  android:name="android.support.multidex.MultiDexApplication"

cannot find module "lodash"

If there is a package.json, and in it there is lodash configuration in it. then you should:

npm install

if in the package.json there is no lodash:

npm install --save-dev

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

C# windows application Event: CLR20r3 on application start

.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.

Hex-encoded String to Byte Array

Use:

str.getBytes("UTF-16LE");

Can a CSS class inherit one or more other classes?

As others have said, you can add multiple classes to an element.

But that's not really the point. I get your question about inheritance. The real point is that inheritance in CSS is done not through classes, but through element hierarchies. So to model inherited traits you need to apply them to different levels of elements in the DOM.

How to store Configuration file and read it using React

You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so

REACT_APP_SERVER_PORT=8000

In your applications entry file your just call dotenv(); before accessing the keys like so

process.env.REACT_APP_SERVER_PORT

Set the layout weight of a TextView programmatically

This should works to you

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT LayoutParams.MATCH_PARENT);

param.weight=1.0f;

Disable Logback in SpringBoot

Just add logback.xml configuration in your classpath and add all your configuration with root appender added. Once the Spring boot completes the bean loading, it will start logging based on your configuration.

How to write a:hover in inline CSS?

As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:

style="cursor: pointer;"

Check whether a path is valid

Get the invalid chars from System.IO.Path.GetInvalidPathChars(); and check if your string (Directory path) contains those or not.

Java ArrayList - how can I tell if two lists are equal, order not mattering?

I had this same problem and came up with a different solution. This one also works when duplicates are involved:

public static boolean equalsWithoutOrder(List<?> fst, List<?> snd){
  if(fst != null && snd != null){
    if(fst.size() == snd.size()){
      // create copied lists so the original list is not modified
      List<?> cfst = new ArrayList<Object>(fst);
      List<?> csnd = new ArrayList<Object>(snd);

      Iterator<?> ifst = cfst.iterator();
      boolean foundEqualObject;
      while( ifst.hasNext() ){
        Iterator<?> isnd = csnd.iterator();
        foundEqualObject = false;
        while( isnd.hasNext() ){
          if( ifst.next().equals(isnd.next()) ){
            ifst.remove();
            isnd.remove();
            foundEqualObject = true;
            break;
          }
        }

        if( !foundEqualObject ){
          // fail early
          break;
        }
      }
      if(cfst.isEmpty()){ //both temporary lists have the same size
        return true;
      }
    }
  }else if( fst == null && snd == null ){
    return true;
  }
  return false;
}

Advantages compared to some other solutions:

  • less than O(N²) complexity (although I have not tested it's real performance comparing to solutions in other answers here);
  • exits early;
  • checks for null;
  • works even when duplicates are involved: if you have an array [1,2,3,3] and another array [1,2,2,3] most solutions here tell you they are the same when not considering the order. This solution avoids this by removing equal elements from the temporary lists;
  • uses semantic equality (equals) and not reference equality (==);
  • does not sort itens, so they don't need to be sortable (by implement Comparable) for this solution to work.

Read data from SqlDataReader

I know this is kind of old but if you are reading the contents of a SqlDataReader into a class, then this will be very handy. the column names of reader and class should be same

public static List<T> Fill<T>(this SqlDataReader reader) where T : new()
        {
            List<T> res = new List<T>();
            while (reader.Read())
            {
                T t = new T();
                for (int inc = 0; inc < reader.FieldCount; inc++)
                {
                    Type type = t.GetType();
                    string name = reader.GetName(inc);
                    PropertyInfo prop = type.GetProperty(name);
                    if (prop != null)
                    {
                        if (name == prop.Name)
                        {
                            var value = reader.GetValue(inc);
                            if (value != DBNull.Value)
                            { 
                                prop.SetValue(t, Convert.ChangeType(value, prop.PropertyType), null);
                            }
                            //prop.SetValue(t, value, null);

                        }
                    }
                }
                res.Add(t);
            }
            reader.Close();

            return res;
        }

Boolean.parseBoolean("1") = false...?

Java is strongly typed. 0 and 1 are numbers, which is a different type than a boolean. A number will never be equal to a boolean.

How to create Custom Ratings bar in Android

I need to add my solution which is WAY eaiser than the one above. We don't even need to use styles.

Create a selector file in the drawable folder:

custom_ratingbar_selector.xml

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@android:id/background"
    android:drawable="@drawable/star_off" />

 <item android:id="@android:id/secondaryProgress"
    android:drawable="@drawable/star_off" />

 <item android:id="@android:id/progress"
    android:drawable="@drawable/star_on" />

</layer-list>

In the layout set the selector file as progressDrawable:

 <RatingBar
        android:id="@+id/ratingBar2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:progressDrawable="@drawable/custom_ratingbar_selector"
        android:numStars="8"
        android:stepSize="0.2"
        android:rating="3.0" />

And that's all we need.

how to set radio option checked onload with jQuery

I liked the answer by @Amc. I found the expression could be condensed further to not use a filter() call (@chaiko apparently also noticed this). Also, prop() is the way to go vs attr() for jQuery v1.6+, see the jQuery documentation for prop() for the official best practices on the subject.

Consider the same input tags from @Paolo Bergantino's answer.

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

The updated one-liner might read something like:

$('input:radio[name="gender"][value="Male"]').prop('checked', true);

In JPA 2, using a CriteriaQuery, how to count results

With Spring Data Jpa, we can use this method:

    /*
     * (non-Javadoc)
     * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#count(org.springframework.data.jpa.domain.Specification)
     */
    @Override
    public long count(@Nullable Specification<T> spec) {
        return executeCountQuery(getCountQuery(spec, getDomainClass()));
    }

Can I do Android Programming in C++, C?

PLEASE NOTE: THE ANSWER BELOW IS HORRIBLY OUTDATED, AND MIGHT NOT BE ENTIRELY CORRECT ANYMORE.

You can program in C/C++ using the Android NDK. You'll have to wrap your c++ codebase in a static library and load that through a Java wrapper & JNI.

The standard NDK does not support RTTI and a lot of the functionality of standard c++ is also not available such as std::string, etc. To solve this you can recompile the NDK. Dmitry Moskalchuk supplies a modified version of the NDK that supports this at http://www.crystax.net/android/ndk-r3.php. This modified version works on all Android phones that run on an ARM processor.

Depending on the kind of application you should decide to use Java or C/C++. I'd use C/C++ for anything that requires above average computational power and games -- Java for the rest.

Just pick one language and write the majority of your application in that language; JNI calls can decrease your performance by a lot. Java isn't that hard though -- if you know how to program in C/C++. The advantage of Java is that the application can run on any device running Android, where as NDK applications depend on the architecture it was compiled for.

One DbContext per web request... why?

I'm pretty certain it is because the DbContext is not at all thread safe. So sharing the thing is never a good idea.

HSL to RGB color conversion

For all who said that Garry Tan solution converting incorrect from RGB to HSL and back. It because he left out fraction part of number in his code. I corrected his code (javascript). Sorry for link on russian languadge, but on english absent - HSL-wiki

function toHsl(r, g, b)
{
    r /= 255.0;
    g /= 255.0;
    b /= 255.0;
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2.0;

    if(max == min)
    {
        h = s = 0; 
    }
    else
    {
        var d = max - min;
        s = (l > 0.5 ? d / (2.0 - max - min) : d / (max + min));

        if(max == r && g >= b)
        {
            h = 1.0472 * (g - b) / d ;
        }
        else if(max == r && g < b)
        {
            h = 1.0472 * (g - b) / d + 6.2832;
        }
        else if(max == g)
        {
            h = 1.0472 * (b - r) / d + 2.0944;
        }
        else if(max == b)
        {
            h = 1.0472 * (r - g) / d + 4.1888;
        }
    }
    return {
        str: 'hsl(' + parseInt(h / 6.2832 * 360.0 + 0.5) + ',' + parseInt(s * 100.0 + 0.5) + '%,' + parseInt(l * 100.0 + 0.5) + '%)',
        obj: { h: parseInt(h / 6.2832 * 360.0 + 0.5), s: parseInt(s * 100.0 + 0.5), l: parseInt(l * 100.0 + 0.5) }
    };
};

How to run travis-ci locally

Similar to Scott McLeod's but this also generates a bash script to run the steps from the .travis.yml.

Troubleshooting Locally in Docker with a generated Bash script

# choose the image according to the language chosen in .travis.yml
$ docker run -it -u travis quay.io/travisci/travis-jvm /bin/bash

# now that you are in the docker image, switch to the travis user
sudo - travis

# Install a recent ruby (default is 1.9.3)
rvm install 2.3.0
rvm use 2.3.0

# Install travis-build to generate a .sh out of .travis.yml
cd builds
git clone https://github.com/travis-ci/travis-build.git
cd travis-build
gem install travis
# to create ~/.travis
travis version
ln -s `pwd` ~/.travis/travis-build
bundle install

# Create project dir, assuming your project is `AUTHOR/PROJECT` on GitHub
cd ~/builds
mkdir AUTHOR
cd AUTHOR
git clone https://github.com/AUTHOR/PROJECT.git
cd PROJECT
# change to the branch or commit you want to investigate
travis compile > ci.sh
# You most likely will need to edit ci.sh as it ignores matrix and env
bash ci.sh

Java SSLHandshakeException "no cipher suites in common"

Having had this exception myself, I delved into the JRE source code. It became apparent that the message is rather misleading. It could mean what it says, but it more generally means that the server doesn't have the data it needs to respond to the client in the requested way. This can happen, for example, if certificates are missing from the keystore, or haven't been generated with the an appropriate algoritm. Indeed, given the cipher suites that are installed by default, one would have to go to some lengths to really get this exception because of lack of common cipher suites. In my particular case I'd generated the certificates with the default algorithm of DSA, when what I needed to get the server to work with Firefox was RSA.

Why does GitHub recommend HTTPS over SSH?

Either you are quoting wrong or github has different recommendation on different pages or they may learned with time and updated their reco.

We strongly recommend using an SSH connection when interacting with GitHub. SSH keys are a way to identify trusted computers, without involving passwords. The steps below will walk you through generating an SSH key and then adding the public key to your GitHub account.

https://help.github.com/articles/generating-ssh-keys

Single quotes vs. double quotes in C or C++

  • 'x' is an integer, representing the numerical value of the letter x in the machine’s character set
  • "x" is an array of characters, two characters long, consisting of ‘x’ followed by ‘\0’

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

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

One of the reasons for me getting an error was the file name make sure the file name is Dockerfile So i figured it out, hope it might help someone.

How many parameters are too many?

I think the actual number really depends on what makes logical sense with the context of the function. I agree that around 4-5 parameters starts getting crowded.

In the case of setting flags, a great way to handle this situation is to enumerate the values and OR them together.

Count Rows in Doctrine QueryBuilder

Since Doctrine 2.6 it is possible to use count() method directly from EntityRepository. For details see the link.

https://github.com/doctrine/doctrine2/blob/77e3e5c96c1beec7b28443c5b59145eeadbc0baf/lib/Doctrine/ORM/EntityRepository.php#L161

How can I uninstall Ruby on ubuntu?

Here is what sudo apt-get purge ruby* removed relating to GRUB for me:

grub-pc 
grub-gfxpayload-lists
grub2-common
grub-pc-bin 
grub-common 

How do I use spaces in the Command Prompt?

Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:

cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""

Grid of responsive squares

Now we can easily do this using the aspect-ratio ref property

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

Also like below where we can have a variable number of columns

_x000D_
_x000D_
.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-gap: 10px;
}

.container>* {
  aspect-ratio: 1 / 1; /* a square ratio */
  border: 1px solid;
  
  /* center content */
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

img {
  max-width: 100%;
  display: block;
}
_x000D_
<div class="container">
  <div> some content here </div>
  <div><img src="https://picsum.photos/id/25/400/400"></div>
  <div>
    <h1>a title</h1>
  </div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
  <div>more and more content <br>here</div>
  <div>
    <h2>another title</h2>
  </div>
  <div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
_x000D_
_x000D_

JavaScript TypeError: Cannot read property 'style' of null

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

let clock = setInterval(() => {
        clearInterval(clock)
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

Passing Objects By Reference or Value in C#

Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.

When you pass an instance as an argument to the method it passes the copy of the instance. Now, if the instance you pass is a value type(resides in the stack) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.

How to iterate object in JavaScript?

Here's all the options you have:

1. for...of (ES2015)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
for (const entry of dictionary.data) {_x000D_
  console.log(JSON.stringify(entry))_x000D_
}
_x000D_
_x000D_
_x000D_

2. Array.prototype.forEach (ES5)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
dictionary.data.forEach(function(entry) {_x000D_
  console.log(JSON.stringify(entry))_x000D_
})
_x000D_
_x000D_
_x000D_

3. for() (ES1)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
for (let i = 0; i < dictionary.data.length; i++) {_x000D_
  console.log(JSON.stringify(dictionary.data[i]))_x000D_
}
_x000D_
_x000D_
_x000D_

Why can't I duplicate a slice with `copy()`?

The copy() runs for the least length of dst and src, so you must initialize the dst to the desired length.

A := []int{1, 2, 3}
B := make([]int, 3)
copy(B, A)
C := make([]int, 2)
copy(C, A)
fmt.Println(A, B, C)

Output:

[1 2 3] [1 2 3] [1 2]

You can initialize and copy all elements in one line using append() to a nil slice.

x := append([]T{}, []...)

Example:

A := []int{1, 2, 3}
B := append([]int{}, A...)
C := append([]int{}, A[:2]...)
fmt.Println(A, B, C)    

Output:

[1 2 3] [1 2 3] [1 2]

Comparing with allocation+copy(), for greater than 1,000 elements, use append. Actually bellow 1,000 the difference may be neglected, make it a go for rule of thumb unless you have many slices.

BenchmarkCopy1-4                50000000            27.0 ns/op
BenchmarkCopy10-4               30000000            53.3 ns/op
BenchmarkCopy100-4              10000000           229 ns/op
BenchmarkCopy1000-4              1000000          1942 ns/op
BenchmarkCopy10000-4              100000         18009 ns/op
BenchmarkCopy100000-4              10000        220113 ns/op
BenchmarkCopy1000000-4              1000       2028157 ns/op
BenchmarkCopy10000000-4              100      15323924 ns/op
BenchmarkCopy100000000-4               1    1200488116 ns/op
BenchmarkAppend1-4              50000000            34.2 ns/op
BenchmarkAppend10-4             20000000            60.0 ns/op
BenchmarkAppend100-4             5000000           240 ns/op
BenchmarkAppend1000-4            1000000          1832 ns/op
BenchmarkAppend10000-4            100000         13378 ns/op
BenchmarkAppend100000-4            10000        142397 ns/op
BenchmarkAppend1000000-4            2000       1053891 ns/op
BenchmarkAppend10000000-4            200       9500541 ns/op
BenchmarkAppend100000000-4            20     176361861 ns/op

Setting width and height

I cannot believe nobody talked about using a relative parent element.

Code:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="chart"></canvas>
</div>

Sources: Official documentation

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

On linux SUSE or RedHat, how do I load Python 2.7

Instructions to download source and install:

https://www.python.org/download/

NOTE: You should check for the latest version of python 2.7.x, as it gets updated frequently. Currently (Oct 2017), the latest version is 2.7.14 though this comment will get old and new versions likely will be released every 6 months or so.

wget https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tgz # Download
tar xvfz Python-2.7.14.tgz # unzip
cd Python-2.7.14 # go into directory
./configure
make # build
su # or 'sudo su' if there is no root user
make altinstall

(EDIT: make install -> make altinstall per Ignacio's comment).

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

How can I change the thickness of my <hr> tag

I would recommend setting the HR itself to be 0px high and use its border to be visible instead. I have noticed that when you zoom in and out (ctrl + mouse wheel) the thickness of HR itself changes, while when you set the border it always stays the same:

hr {
    height: 0px;
    border: none;
    border-top: 1px solid black;
}

video as site background? HTML 5

Take a look at my jquery videoBG plugin

http://syddev.com/jquery.videoBG/

Make any HTML5 video a site background... has an image fallback for browsers that don't support html5

Really easy to use

Let me know if you need any help.

How can I get the current user's username in Bash?

Get the current task's user_struct

#define get_current_user()              \
({                                      \
    struct user_struct *__u;            \
    const struct cred *__cred;          \
    __cred = current_cred();            \
    __u = get_uid(__cred->user);        \
    __u;                                \
})

How to get $HOME directory of different user in bash script?

The title of this question is How to get $HOME directory of different user in bash script? and that is what people are coming here from Google to find out.

There is a safe way to do this!

on Linux/BSD/macOS/OSX without sudo or root

user=pi
user_home=$(bash -c "cd ~$(printf %q $USER) && pwd")

NOTE: The reason this is safe is because bash (even versions prior to 4.4) has its own printf function that includes:

%q quote the argument in a way that can be reused as shell input

See: help printf

Compare the how other answers here respond to code injection

# "ls /" is not dangerous so you can try this on your machine
# But, it could just as easily be "sudo rm -rf /*"
$ user="root; ls /"
$ printf "%q" "$user"
root\;\ ls\ /

# This is what you get when you are PROTECTED from code injection
$ user_home=$(bash -c "cd ~$(printf "%q" "$user") && pwd"); echo $user_home
bash: line 0: cd: ~root; ls /: No such file or directory

# This is what you get when you ARE NOT PROTECTED from code injection
$ user_home=$(bash -c "cd ~$user && pwd"); echo $user_home
bin boot dev etc home lib lib64 media mnt ono opt proc root run sbin srv sys tmp usr var /root

$ user_home=$(eval "echo ~$user"); echo $user_home
/root bin boot dev etc home lib lib64 media mnt ono opt proc root run sbin srv sys tmp usr var

on Linux/BSD/macOS/OSX as root

If you are doing this because you are running something as root then you can use the power of sudo:

user=pi
user_home=$(sudo -u $user sh -c 'echo $HOME')

on Linux/BSD (but not modern macOS/OSX) without sudo or root

If not, the you can get it from /etc/passwd. There are already lots of examples of using eval and getent, so I'll give another option:

user=pi
user_home=$(awk -v u="$user" -v FS=':' '$1==u {print $6}' /etc/passwd)

I would really only use that one if I had a bash script with lots of other awk oneliners and no uses of cut. While many people like to "code golf" to use the fewest characters to accomplish a task, I favor "tool golf" because using fewer tools gives your script a smaller "compatibility footprint". Also, it's less man pages for your coworker or future-self to have to read to make sense of it.

New line in JavaScript alert box

List of Special Character codes in JavaScript:

Code    Outputs
\'  single quote
\"  double quote
\\  backslash
\n  new line
\r  carriage return
\t  tab
\b  backspace
\f  form feed

Hide div if screen is smaller than a certain width

Use media queries. Your CSS code would be:

@media screen and (max-width: 1024px) {
    .yourClass {
        display: none !important;
    }
}

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

Gerrit error when Change-Id in commit messages are missing

It is because Gerrit is configured to require Change-Id in the commit messages.

http://gerrit.googlecode.com/svn-history/r6114/documentation/2.1.7/error-missing-changeid.html

You have to change the messages of every commit that you are pushing to include the change id ( using git filter-branch ) and only then push.

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

How to set Android camera orientation properly?

check out this solution

 public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

Set IDENTITY_INSERT ON is not working

Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.

to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

Windows equivalent of linux cksum command

To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil

How do I 'foreach' through a two-dimensional array?

Remember that a multi-dimensional array is like a table. You don't have an x element and a y element for each entry; you have a string at (for instance) table[1,2].

So, each entry is still only one string (in your example), it's just an entry at a specific x/y value. So, to get both entries at table[1, x], you'd do a nested for loop. Something like the following (not tested, but should be close)

for (int x = 0; x < table.Length; x++)
{
    for (int y = 0; y < table.Length; y += 2)
    {
        Console.WriteLine("{0} {1}", table[x, y], table[x, y + 1]);
    }
}

How to post JSON to a server using C#?

The HttpClient type is a newer implementation than the WebClient and HttpWebRequest.

You can simply use the following lines.

string myJson = "{'Username': 'myusername','Password':'pass'}";
using (var client = new HttpClient())
{
    var response = await client.PostAsync(
        "http://yourUrl", 
         new StringContent(myJson, Encoding.UTF8, "application/json"));
}

When you need your HttpClient more than once it's recommended to only create one instance and reuse it or use the new HttpClientFactory.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

Is there a conditional ternary operator in VB.NET?

If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"

For example, if your not careful you may be tempted to try something like:

Dim foo As Integer? = If(someTrueExpression, Nothing, 2)

Will give "foo" a value of 0!

I think the '?' operator equivalent in C# would instead fail compilation

Initializing C dynamic arrays

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

You can never use this:

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

loop is right

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

Instance member cannot be used on type

For anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)

eg.

MyClass.variable = 'Foo' // WRONG! - Instance member 'variable' cannot be used on type 'MyClass'

instanceOfMyClass.variable = 'Foo' // Right!

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

Just come across it and got an answer somewhere. you can use below annotation since 2.7.0

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Point {
    final private double x;
    final private double y;

    @ConstructorProperties({"x", "y"})
    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

How do I declare a 2d array in C++ using new?

I'm using this when creating dynamic array. If you have a class or a struct. And this works. Example:

struct Sprite {
    int x;
};

int main () {
   int num = 50;
   Sprite **spritearray;//a pointer to a pointer to an object from the Sprite class
   spritearray = new Sprite *[num];
   for (int n = 0; n < num; n++) {
       spritearray[n] = new Sprite;
       spritearray->x = n * 3;
  }

   //delete from random position
    for (int n = 0; n < num; n++) {
        if (spritearray[n]->x < 0) {
      delete spritearray[n];
      spritearray[n] = NULL;
        }
    }

   //delete the array
    for (int n = 0; n < num; n++) {
      if (spritearray[n] != NULL){
         delete spritearray[n];
         spritearray[n] = NULL;
      }
    }
    delete []spritearray;
    spritearray = NULL;

   return 0;
  } 

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Now.ToShortDateString() will display only the date part

Print commit message of a given commit in git

I use shortlog for this:

$ git shortlog master..
Username (3):
      Write something
      Add something
      Bump to 1.3.8 

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

Automatically start forever (node) on system restart

I would suggest using crontab. It's easy to use.

How to

  1. To start editing run the following replacing the "testuser" with your desired runtime user for the node process. If you choose a different user other than yourself, you will have to run this with sudo.

    $ crontab -u testuser -e
    
  2. If you have never done this before, it will ask you which editor you wish to edit with. I like vim, but will recommend nano for ease of use.

  3. Once in the editor add the following line:

    @reboot /usr/local/bin/forever start /your/path/to/your/app.js
    
  4. Save the file. You should get some feedback that the cron has been installed.

  5. For further confirmation of the installation of the cron, execute the following (again replacing "testuser" with your target username) to list the currently installed crons:

    $ crontab -u testuser -l 
    

Note that in my opinion, you should always use full paths when executing binaries in cron. Also, if the path to your forever script is not correct, run which forever to get the full path.

Given that forever calls node, you may also want to provide the full path to node:

@reboot /usr/local/bin/forever start -c /usr/local/bin/node /your/path/to/your/app.js

Further Reading

Import and Export Excel - What is the best library?

How about the apache POI java library. I havent used it for Excel , but did use it for Word 2007.

Set custom HTML5 required field validation message

Try this:

$(function() {
    var elements = document.getElementsByName("topicName");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("Please enter Room Topic Title");
        };
    }
})

I tested this in Chrome and FF and it worked in both browsers.

Why would $_FILES be empty when uploading files to PHP?

No one mentioned this but it helped me out and not many places on the net mention it.

Make sure your php.ini sets the following key:

    upload_tmp_dir="/path/to/some/tmp/folder"

You'll need to check with your webhost if they want you to use an absolute server file path. You should be able to see other directory examples in your php.ini file to determine this. As soon as I set it I got values in my _FILES object.

Finally make sure that your tmp folder and wherever you are moving files to have the correct permissions so that they can be read and written to.

How can I backup a Docker-container with its data-volumes?

I have created a tool to orchestrate and launch backup of data and mysql containers, simply called docker-backup. There is even a ready-to-use image on the docker hub.

It's mainly written in Bash as it is mainly orchestration. It uses duplicity for the actual backup engine. You can currently backup to FTP(S) and Amazon S3.

The configuration is quite simple: write a config file in YAML describing what to backup and where, and here you go!

For data containers, it automatically mount the volumes shared by your container to backup and process it. For mysql containers, it links them and execute a mysqldump bundled with your container and process the result.

I wrote it because I use Docker-Cloud which is not up-to-date with recent docker-engine releases and because I wanted to embrace the Docker way by not including any process of backup inside my application containers.

Reverse ip, find domain names on ip address

windows user can just using the simple nslookup command

G:\wwwRoot\JavaScript Testing>nslookup 208.97.177.124
Server:  phicomm.me
Address:  192.168.2.1

Name:    apache2-argon.william-floyd.dreamhost.com
Address:  208.97.177.124


G:\wwwRoot\JavaScript Testing>

http://www.guidingtech.com/2890/find-ip-address-nslookup-command-windows/

if you want get more info, please check the following answer!

https://superuser.com/questions/287577/how-to-find-a-domain-based-on-the-ip-address/1177576#1177576

What does "for" attribute do in HTML <label> tag?

It labels whatever input is the parameter for the for attribute.

_x000D_
_x000D_
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
_x000D_
_x000D_

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.

My initial wrong XSD was alike the following:

<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="XXX" type="XXX_TYPE"/>
    </xs:sequence>
</xs:complexType>

The good XSD format for my migration to succeed was the following:

<xs:element name="Document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="XXX"/>
        </xs:sequence>
    </xs:complexType>        
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>

And so on for every similar XSD nodes.

Handling InterruptedException in Java

The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.

Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.

So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.

There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.

If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.

So in summary your choices for handling should follow this list:

  1. By default, add to throws.
  2. If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
  3. Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

SQL Server - Convert date field to UTC

If you have to convert dates other than today to different timezones you have to deal with daylight savings. I wanted a solution that could be done without worrying about database version, without using stored functions and something that could easily be ported to Oracle.

I think Warren is on the right track with getting the correct dates for daylight time, but to make it more useful for multiple time zone and different rules for countries and even the rule that changed in the US between 2006 and 2007, here a variation on the above solution. Notice that this not only has us time zones, but also central Europe. Central Europe follow the last sunday of april and last sunday of october. You will also notice that the US in 2006 follows the old first sunday in april, last sunday in october rule.

This SQL code may look a little ugly, but just copy and paste it into SQL Server and try it. Notice there are 3 section for years, timezones and rules. If you want another year, just add it to the year union. Same for another time zone or rule.

select yr, zone, standard, daylight, rulename, strule, edrule, yrstart, yrend,
    dateadd(day, (stdowref + stweekadd), stmonthref) dstlow,
    dateadd(day, (eddowref + edweekadd), edmonthref)  dsthigh
from (
  select yrs.yr, z.zone, z.standard, z.daylight, z.rulename, r.strule, r.edrule, 
    yrs.yr + '-01-01 00:00:00' yrstart,
    yrs.yr + '-12-31 23:59:59' yrend,
    yrs.yr + r.stdtpart + ' ' + r.cngtime stmonthref,
    yrs.yr + r.eddtpart + ' ' + r.cngtime edmonthref,
    case when r.strule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.stdtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.stdtpart) end
    else (datepart(dw, yrs.yr + r.stdtpart) - 1) * -1 end stdowref,
    case when r.edrule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.eddtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.eddtpart) end
    else (datepart(dw, yrs.yr + r.eddtpart) - 1) * -1 end eddowref,
    datename(dw, yrs.yr + r.stdtpart) stdow,
    datename(dw, yrs.yr + r.eddtpart) eddow,
    case when r.strule in ('1', '2', '3') then (7 * CAST(r.strule AS Integer)) - 7 else 0 end stweekadd,
    case when r.edrule in ('1', '2', '3') then (7 * CAST(r.edrule AS Integer)) - 7 else 0 end edweekadd
from (
    select '2005' yr union select '2006' yr -- old us rules
    UNION select '2007' yr UNION select '2008' yr UNION select '2009' yr UNION select '2010' yr UNION select '2011' yr
    UNION select '2012' yr UNION select '2013' yr UNION select '2014' yr UNION select '2015' yr UNION select '2016' yr
    UNION select '2017' yr UNION select '2018' yr UNION select '2019' yr UNION select '2020' yr UNION select '2021' yr
    UNION select '2022' yr UNION select '2023' yr UNION select '2024' yr UNION select '2025' yr UNION select '2026' yr
) yrs
cross join (
    SELECT 'ET' zone, '-05:00' standard, '-04:00' daylight, 'US' rulename
    UNION SELECT 'CT' zone, '-06:00' standard, '-05:00' daylight, 'US' rulename
    UNION SELECT 'MT' zone, '-07:00' standard, '-06:00' daylight, 'US' rulename
    UNION SELECT 'PT' zone, '-08:00' standard, '-07:00' daylight, 'US' rulename
    UNION SELECT 'CET' zone, '+01:00' standard, '+02:00' daylight, 'EU' rulename
) z
join (
    SELECT 'US' rulename, '2' strule, '-03-01' stdtpart, '1' edrule, '-11-01' eddtpart, 2007 firstyr, 2099 lastyr, '02:00:00' cngtime
    UNION SELECT 'US' rulename, '1' strule, '-04-01' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2006 lastyr, '02:00:00' cngtime
    UNION SELECT  'EU' rulename, 'L' strule, '-03-31' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2099 lastyr, '01:00:00' cngtime
) r on r.rulename = z.rulename
    and datepart(year, yrs.yr) between firstyr and lastyr
) dstdates

For the rules, use 1, 2, 3 or L for first, second, third or last sunday. The date part gives the month and depending on the rule, the first day of the month or the last day of the month for rule type L.

I put the above query into a view. Now, anytime I want a date with the time zone offset or converted to UTC time, I just join to this view and select get the date in the date format. Instead of datetime, I converted these to datetimeoffset.

select createdon, dst.zone
    , case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end pacificoffsettime
    , TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end) pacifictime
    , SWITCHOFFSET(TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end), '+00:00')  utctime
from (select '2014-01-01 12:00:00' createdon union select '2014-06-01 12:00:00' createdon) photos
left join US_DAYLIGHT_DATES dst on createdon between yrstart and yrend and zone = 'PT'

How to resolve this System.IO.FileNotFoundException

I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.

To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:

Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.

Indent List in HTML and CSS

You can use [Adjacent sibling combinators] as described in the W3 CSS Selectors Recommendation1 So you can use a + sign (or even a ~ tilde) apply a padding to the nested ul tag, as you described in your question and you'll get the result you need. I also think what you want it to override the main css, locally. You can do this:

<style>
    li+ul {padding-left: 20px;}
</style>

This way the inner ul will be nested including the bullets of the li elements. I wish this was helpful! =)

How to install and run phpize

For ubuntu with Plesk installed run apt-get install plesk-php56-dev, for other versions just change XX in phpXX (without the dot)

Clear image on picturebox

I used this method to clear the image from picturebox. It may help some one

private void btnClear1_Click(object sender, EventArgs e)
        {

            img1.ImageLocation = null;
        }

Dynamically add item to jQuery Select2 control that uses AJAX

In Select2 4.0.2

$("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
$('#yourId').trigger('change'); 

Bash script processing limited number of commands in parallel

See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

Correct way of using log4net (logger naming)

Regarding how you log messages within code, I would opt for the second approach:

ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");

Where messages sent to the log above will be 'named' using the fully-qualifed type Bar, e.g.

MyNamespace.Foo.Bar [INFO] message

The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar specifically to DEBUG:

<log4net>
    <!-- appenders go here -->
    <root>
        <level value="INFO" />
        <appender-ref ref="myLogAppender" />
    </root>

    <logger name="MyNamespace.Foo.Bar">
        <level value="DEBUG" />
    </logger>
</log4net>

The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog", you loose much of this power!

Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.

For further reading, here is a codeproject article I wrote on logging:

How to check if a Unix .tar.gz file is a valid file without uncompressing?

I have tried the following command and they work well.

bzip2 -t file.bz2
gunzip -t file.gz

However, we can found these two command are time-consuming. Maybe we need some more quick way to determine the intact of the compress files.

Correct way to focus an element in Selenium WebDriver using Java

FWIW, I had what I think is a related problem and came up with a workaround: I wrote a Chrome Extension that did an document.execCommand('paste') into a textarea with focus on window unload in order to populate the element with the system clipboard contents. This worked 100% of the time manually, but the execCommand returned false almost all the time when run under Selenium.

I added a driver.refresh() after the initial driver.get( myChromeExtensionURL ), and now it works 100% of the time. This was with Selenium driver version 2.16.333243 and Chrome version 43 on Mac OS 10.9.

When I was researching the problem, I didn't see any mentions of this workaround, so I thought I'd document my discovery for those following in my Selenium/focus/execCommand('paste') footsteps.

API vs. Webservice

Think of Web service as a web api. API is such a general term now so a web service is an interface to functionality, usually business related, that you can get to from the network over a variety of protocols.

Paste in insert mode?

You can use this to paste from clipboard with Ctrlv:

set pastetoggle=<F10>
inoremap <C-v> <F10><C-r>+<F10>

And this for yanking visual selection into clipboard with Ctrlc:

vnoremap <C-c> "+y

If you also want to use clipboard by default for classic vim yanking/pasting (y/p) in normal mode, here is a config option that does it:

set clipboard=unnamedplus

With this configs you can e.g. yank first in normal mode and then paste with Ctrlv in insert mode. Also, you can paste text from different vim instances and different applications.

Another option is:

set clipboard=unnamed

Then you will be able to just select something by mouse dragging in your X environment and paste it into vim afterwards. But (for some reason) you won't be able to yank something (y) in Vim and shiftinsert it somewhere else afterwards, which is probably quite limiting.

Vim docs about this: http://vim.wikia.com/wiki/Accessing_the_system_clipboard

For pasting from custom registers you can follow the other answers :). This answer is mainly about integrating Vim with your system clipboard.


Note that for set clipboard=unnamedplus and set clipboard=unnamed to work, you need to use gvim or vimx (vim-X11): Those are compiled with +xterm_clipboard. You can optionally put this into your .bashrc to alias vim with vimx:

if [ -e /usr/bin/vimx ]; then
    alias vim='/usr/bin/vimx'; # vim with +xterm_clipboard
fi

You can find out whether or not your vim has the +xterm_clipboard in the information provided by vim --version.

How do I call the base class constructor?

You do this in the initializer-list of the constructor of the subclass.

class Foo : public BaseClass {
public:
    Foo() : BaseClass("asdf") {}
};

Base-class constructors that take arguments have to be called there before any members are initialized.

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

Disabling same-origin policy in Safari

Most of these answers are old. The latest Safari 14.0.2 (in 2021), has the option to Disable Cross-Origin Restrictions, however, it doesn't work if the paths have ../../ kind of path names; even though Safari correctly resolves to a local file path, it still doesn't permit loading the file, even though it exists. This is a recent bug in Safari 14 that didn't happen in 13.

Regular expression for not allowing spaces in the input field

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:

var regexp = /^\S*$/; // a string consisting only of non-whitespaces

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

Generics/templates in python?

Actually now you can use generics in Python 3.5+. See PEP-484 and typing module documentation.

According to my practice it is not very seamless and clear especially for those who are familiar with Java Generics, but still usable.