Programs & Examples On #Laconica

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

You need to fix your include_path system variable to point to the correct location.

To fix it edit the php.ini file. In that file you will find a line that says, "include_path = ...". (You can find out what the location of php.ini by running phpinfo() on a page.) Fix the part of the line that says, "\xampplite\php\pear\PEAR" to read "C:\xampplite\php\pear". Make sure to leave the semi-colons before and/or after the line in place.

Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

Follow below steps:

    1. Ensure to delete all the contents of the jar folder located in your local except the jar that you want to keep.
      For example files like .repositories, .pom, .sha1, .lastUpdated etc.
    1. Execute mvn clean install -o command

This will help to use local repository jar files rather than connecting to any repository.

How to style input and submit button with CSS?

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Button</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="container">
<a href="#" class="btn">Push</a>
</div>
</body>
</html>

CSS styling

a.btn {
display: block; width: 250px; height: 60px; padding: 40px 0 0 0; margin: 0 auto;

background: #398525; /* old browsers */
background: -moz-linear-gradient(top, #8DD297 0%, #398525 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#8DD297), color-stop(100%,#398525)); /* webkit */

box-shadow: inset 0px 0px 6px #fff;
-webkit-box-shadow: inset 0px 0px 6px #fff;
border: 1px solid #5ea617;
border-radius: 10px;
}

ConfigurationManager.AppSettings - How to modify and save?

You can change it manually:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}

How to draw a line in android

Another approach to draw a line programatically using ImageView

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ImageView;

public class Test extends Activity {
  ImageView drawingImageView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    drawingImageView = (ImageView) this.findViewById(R.id.DrawingImageView);
    Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
        .getDefaultDisplay().getWidth(), (int) getWindowManager()
        .getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawingImageView.setImageBitmap(bitmap);

    // Line
    Paint paint = new Paint();
    paint.setColor(Color.GREEN);
    paint.setStrokeWidth(10);
    int startx = 50;
    int starty = 100;
    int endx = 150;
    int endy = 210;
    canvas.drawLine(startx, starty, endx, endy, paint);

  }
}

SyntaxError: missing ; before statement

I got this error, hope this will help someone:

const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';

The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.

Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

How do I make a placeholder for a 'select' box?

Solution for Angular 2

Create a label on top of the select

<label class="hidden-label" for="IsActive"
    *ngIf="filterIsActive == undefined">Placeholder text</label>
<select class="form-control form-control-sm" type="text" name="filterIsActive"
    [(ngModel)]="filterIsActive" id="IsActive">
    <option value="true">true</option>
    <option value="false">false</option>
</select>

and apply CSS to place it on top

.hidden-label {
    position: absolute;
    margin-top: .34rem;
    margin-left: .56rem;
    font-style: italic;
    pointer-events: none;
}

pointer-events: none allows you to display the select when you click on the label, which is hidden when you select an option.

vuejs update parent data from child component

I agree with the event emitting and v-model answers for those above. However, I thought I would post what I found about components with multiple form elements that want to emit back to their parent since this seems one of the first articles returned by google.

I know the question specifies a single input, but this seemed the closest match and might save people some time with similar vue components. Also, no one has mentioned the .sync modifier yet.

As far as I know, the v-model solution is only suited to one input returning to their parent. I took a bit of time looking for it but Vue (2.3.0) documentation does show how to sync multiple props sent into the component back to the parent (via emit of course).

It is appropriately called the .sync modifier.

Here is what the documentation says:

In some cases, we may need “two-way binding” for a prop. Unfortunately, true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.

That’s why instead, we recommend emitting events in the pattern of update:myPropName. For example, in a hypothetical component with a title prop, we could communicate the intent of assigning a new value with:

this.$emit('update:title', newTitle)

Then the parent can listen to that event and update a local data property, if it wants to. For example:

<text-document   
 v-bind:title="doc.title"  
 v-on:update:title="doc.title = $event"
></text-document>

For convenience, we offer a shorthand for this pattern with the .sync modifier:

<text-document v-bind:title.sync="doc.title"></text-document>

You can also sync multiple at a time by sending through an object. Check out the documentation here

Tomcat base URL redirection

In Tomcat 8 you can also use the rewrite-valve

RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/(.*)$         /somethingelse/index.jsp

To setup the rewrite-valve look here:

http://tonyjunkes.com/blog/a-brief-look-at-the-rewrite-valve-in-tomcat-8/

How to redirect to a 404 in Rails?

Don't render 404 yourself, there's no reason to; Rails has this functionality built in already. If you want to show a 404 page, create a render_404 method (or not_found as I called it) in ApplicationController like this:

def not_found
  raise ActionController::RoutingError.new('Not Found')
end

Rails also handles AbstractController::ActionNotFound, and ActiveRecord::RecordNotFound the same way.

This does two things better:

1) It uses Rails' built in rescue_from handler to render the 404 page, and 2) it interrupts the execution of your code, letting you do nice things like:

  user = User.find_by_email(params[:email]) or not_found
  user.do_something!

without having to write ugly conditional statements.

As a bonus, it's also super easy to handle in tests. For example, in an rspec integration test:

# RSpec 1

lambda {
  visit '/something/you/want/to/404'
}.should raise_error(ActionController::RoutingError)

# RSpec 2+

expect {
  get '/something/you/want/to/404'
}.to raise_error(ActionController::RoutingError)

And minitest:

assert_raises(ActionController::RoutingError) do 
  get '/something/you/want/to/404'
end

OR refer more info from Rails render 404 not found from a controller action

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

PyTorch: How to get the shape of a Tensor as a list of int

For PyTorch v1.0 and possibly above:

>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>

# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>

You can cast any torch.Size object to a native Python list:

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

In PyTorch v0.3 and 0.4:

Simply list(var.size()), e.g.:

>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))

>>> var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

>>> var.size()
torch.Size([2, 2])

>>> list(var.size())
[2, 2]

Moving from one activity to another Activity in Android

@Override
public void onClick(View v)
{
    // TODO Auto-generated method stub
    Intent intent = new Intent(Activity1.this,Activity2.class);
    startActivity(intent);

}

Compiling an application for use in highly radioactive environments

It may be possible to use C to write programs that behave robustly in such environments, but only if most forms of compiler optimization are disabled. Optimizing compilers are designed to replace many seemingly-redundant coding patterns with "more efficient" ones, and may have no clue that the reason the programmer is testing x==42 when the compiler knows there's no way x could possibly hold anything else is because the programmer wants to prevent the execution of certain code with x holding some other value--even in cases where the only way it could hold that value would be if the system received some kind of electrical glitch.

Declaring variables as volatile is often helpful, but may not be a panacea. Of particular importance, note that safe coding often requires that dangerous operations have hardware interlocks that require multiple steps to activate, and that code be written using the pattern:

... code that checks system state
if (system_state_favors_activation)
{
  prepare_for_activation();
  ... code that checks system state again
  if (system_state_is_valid)
  {
    if (system_state_favors_activation)
      trigger_activation();
  }
  else
    perform_safety_shutdown_and_restart();
}
cancel_preparations();

If a compiler translates the code in relatively literal fashion, and if all the checks for system state are repeated after the prepare_for_activation(), the system may be robust against almost any plausible single glitch event, even those which would arbitrarily corrupt the program counter and stack. If a glitch occurs just after a call to prepare_for_activation(), that would imply that activation would have been appropriate (since there's no other reason prepare_for_activation() would have been called before the glitch). If the glitch causes code to reach prepare_for_activation() inappropriately, but there are no subsequent glitch events, there would be no way for code to subsequently reach trigger_activation() without having passed through the validation check or calling cancel_preparations first [if the stack glitches, execution might proceed to a spot just before trigger_activation() after the context that called prepare_for_activation() returns, but the call to cancel_preparations() would have occurred between the calls to prepare_for_activation() and trigger_activation(), thus rendering the latter call harmless.

Such code may be safe in traditional C, but not with modern C compilers. Such compilers can be very dangerous in that sort of environment because aggressive they strive to only include code which will be relevant in situations that could come about via some well-defined mechanism and whose resulting consequences would also be well defined. Code whose purpose would be to detect and clean up after failures may, in some cases, end up making things worse. If the compiler determines that the attempted recovery would in some cases invoke undefined behavior, it may infer that the conditions that would necessitate such recovery in such cases cannot possibly occur, thus eliminating the code that would have checked for them.

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Synchronizing with threads. 1) NEVER use synchronized(this) in a thread it doesn't work. Synchronizing with (this) uses the current thread as the locking thread object. Since each thread is independent of other threads, there is NO coordination of synchronization. 2) Tests of code show that in Java 1.6 on a Mac the method synchronization does not work. 3) synchronized(lockObj) where lockObj is a common shared object of all threads synchronizing on it will work. 4) ReenterantLock.lock() and .unlock() work. See Java tutorials for this.

The following code shows these points. It also contains the thread-safe Vector which would be substituted for the ArrayList, to show that many threads adding to a Vector do not lose any information, while the same with an ArrayList can lose information. 0) Current code shows loss of information due to race conditions A) Comment the current labeled A line, and uncomment the A line above it, then run, method loses data but it shouldn't. B) Reverse step A, uncomment B and // end block }. Then run to see results no loss of data C) Comment out B, uncomment C. Run, see synchronizing on (this) loses data, as expected. Don't have time to complete all the variations, hope this helps. If synchronizing on (this), or the method synchronization works, please state what version of Java and OS you tested. Thank you.

import java.util.*;

/** RaceCondition - Shows that when multiple threads compete for resources 
     thread one may grab the resource expecting to update a particular 
     area but is removed from the CPU before finishing.  Thread one still 
     points to that resource.  Then thread two grabs that resource and 
     completes the update.  Then thread one gets to complete the update, 
     which over writes thread two's work.
     DEMO:  1) Run as is - see missing counts from race condition, Run severa times, values change  
            2) Uncomment "synchronized(countLock){ }" - see counts work
            Synchronized creates a lock on that block of code, no other threads can 
            execute code within a block that another thread has a lock.
        3) Comment ArrayList, unComment Vector - See no loss in collection
            Vectors work like ArrayList, but Vectors are "Thread Safe"
         May use this code as long as attribution to the author remains intact.
     /mf
*/ 

public class RaceCondition {
    private ArrayList<Integer> raceList = new ArrayList<Integer>(); // simple add(#)
//  private Vector<Integer> raceList = new Vector<Integer>(); // simple add(#)

    private String countLock="lock";    // Object use for locking the raceCount
    private int raceCount = 0;        // simple add 1 to this counter
    private int MAX = 10000;        // Do this 10,000 times
    private int NUM_THREADS = 100;    // Create 100 threads

    public static void main(String [] args) {
    new RaceCondition();
    }

    public RaceCondition() {
    ArrayList<Thread> arT = new ArrayList<Thread>();

    // Create thread objects, add them to an array list
    for( int i=0; i<NUM_THREADS; i++){
        Thread rt = new RaceThread( ); // i );
        arT.add( rt );
    }

    // Start all object at once.
    for( Thread rt : arT ){
        rt.start();
    }

    // Wait for all threads to finish before we can print totals created by threads
    for( int i=0; i<NUM_THREADS; i++){
        try { arT.get(i).join(); }
        catch( InterruptedException ie ) { System.out.println("Interrupted thread "+i); }
    }

    // All threads finished, print the summary information.
    // (Try to print this informaiton without the join loop above)
    System.out.printf("\nRace condition, should have %,d. Really have %,d in array, and count of %,d.\n",
                MAX*NUM_THREADS, raceList.size(), raceCount );
    System.out.printf("Array lost %,d. Count lost %,d\n",
             MAX*NUM_THREADS-raceList.size(), MAX*NUM_THREADS-raceCount );
    }   // end RaceCondition constructor



    class RaceThread extends Thread {
    public void run() {
        for ( int i=0; i<MAX; i++){
        try {
            update( i );        
        }    // These  catches show when one thread steps on another's values
        catch( ArrayIndexOutOfBoundsException ai ){ System.out.print("A"); }
        catch( OutOfMemoryError oome ) { System.out.print("O"); }
        }
    }

    // so we don't lose counts, need to synchronize on some object, not primitive
    // Created "countLock" to show how this can work.
    // Comment out the synchronized and ending {, see that we lose counts.

//    public synchronized void update(int i){   // use A
    public void update(int i){                  // remove this when adding A
//      synchronized(countLock){            // or B
//      synchronized(this){             // or C
        raceCount = raceCount + 1;
        raceList.add( i );      // use Vector  
//          }           // end block for B or C
    }   // end update

    }   // end RaceThread inner class


} // end RaceCondition outter class

Is there a library function for Root mean square error (RMSE) in python?

from sklearn.metrics import mean_squared_error
rmse = mean_squared_error(y_actual, y_predicted, squared=False)

or 

import math
from sklearn.metrics import mean_squared_error
rmse = math.sqrt(mean_squared_error(y_actual, y_predicted))

Best way to replace multiple characters in a string?

Late to the party, but I lost a lot of time with this issue until I found my answer.

Short and sweet, translate is superior to replace. If you're more interested in funcionality over time optimization, do not use replace.

Also use translate if you don't know if the set of characters to be replaced overlaps the set of characters used to replace.

Case in point:

Using replace you would naively expect the snippet "1234".replace("1", "2").replace("2", "3").replace("3", "4") to return "2344", but it will return in fact "4444".

Translation seems to perform what OP originally desired.

In C/C++ what's the simplest way to reverse the order of bits in a byte?

Two lines:

for(i=0;i<8;i++)
     reversed |= ((original>>i) & 0b1)<<(7-i);

or in case you have issues with the "0b1" part:

for(i=0;i<8;i++)
     reversed |= ((original>>i) & 1)<<(7-i);

"original" is the byte you want to reverse. "reversed" is the result, initialized to 0.

Pandas percentage of total with groupby

For conciseness I'd use the SeriesGroupBy:

In [11]: c = df.groupby(['state', 'office_id'])['sales'].sum().rename("count")

In [12]: c
Out[12]:
state  office_id
AZ     2            925105
       4            592852
       6            362198
CA     1            819164
       3            743055
       5            292885
CO     1            525994
       3            338378
       5            490335
WA     2            623380
       4            441560
       6            451428
Name: count, dtype: int64

In [13]: c / c.groupby(level=0).sum()
Out[13]:
state  office_id
AZ     2            0.492037
       4            0.315321
       6            0.192643
CA     1            0.441573
       3            0.400546
       5            0.157881
CO     1            0.388271
       3            0.249779
       5            0.361949
WA     2            0.411101
       4            0.291196
       6            0.297703
Name: count, dtype: float64

For multiple groups you have to use transform (using Radical's df):

In [21]: c =  df.groupby(["Group 1","Group 2","Final Group"])["Numbers I want as percents"].sum().rename("count")

In [22]: c / c.groupby(level=[0, 1]).transform("sum")
Out[22]:
Group 1  Group 2  Final Group
AAHQ     BOSC     OWON           0.331006
                  TLAM           0.668994
         MQVF     BWSI           0.288961
                  FXZM           0.711039
         ODWV     NFCH           0.262395
...
Name: count, dtype: float64

This seems to be slightly more performant than the other answers (just less than twice the speed of Radical's answer, for me ~0.08s).

document.getelementbyId will return null if element is not defined?

console.log(document.getElementById('xx') ) evaluates to null.

document.getElementById('xx') !=null evaluates to false

You should use document.getElementById('xx') !== null as it is a stronger equality check.

Is it possible in Java to catch two exceptions in the same catch block?

Java 7 and later

Multiple-exception catches are supported, starting in Java 7.

The syntax is:

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.


Java 6 and earlier

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

Approach #1

try {
     // stuff
} catch (Exception1 ex) {
     handleException(ex);
} catch (Exception2 ex) {
     handleException(ex);
}

public void handleException(SuperException ex) {
     // handle exception here
}

This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.

Approach #2

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

Once again, we have a potential problem with signatures.

Approach #3

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

C default arguments

Yes you can do somthing simulair, here you have to know the different argument lists you can get but you have the same function to handle then all.

typedef enum { my_input_set1 = 0, my_input_set2, my_input_set3} INPUT_SET;

typedef struct{
    INPUT_SET type;
    char* text;
} input_set1;

typedef struct{
    INPUT_SET type;
    char* text;
    int var;
} input_set2;

typedef struct{
    INPUT_SET type;
    int text;
} input_set3;

typedef union
{
    INPUT_SET type;
    input_set1 set1;
    input_set2 set2;
    input_set3 set3;
} MY_INPUT;

void my_func(MY_INPUT input)
{
    switch(input.type)
    {
        case my_input_set1:
        break;
        case my_input_set2:
        break;
        case my_input_set3:
        break;
        default:
        // unknown input
        break;
    }
}

How do I change a PictureBox's image?

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

Android how to convert int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

int i = 5;
String strI = String.valueOf(i);

Or

int aInt = 1;    
String aString = Integer.toString(aInt);

Imported a csv-dataset to R but the values becomes factors

When importing csv data files the import command should reflect both the data seperation between each column (;) and the float-number seperator for your numeric values (for numerical variable = 2,5 this would be ",").

The command for importing a csv, therefore, has to be a bit more comprehensive with more commands:

    stuckey <- read.csv2("C:/kalle/R/stuckey.csv", header=TRUE, sep=";", dec=",")

This should import all variables as either integers or numeric.

Use find command but exclude files in two directories

for me, this solution didn't worked on a command exec with find, don't really know why, so my solution is

find . -type f -path "./a/*" -prune -o -path "./b/*" -prune -o -exec gzip -f -v {} \;

Explanation: same as sampson-chen one with the additions of

-prune - ignore the proceding path of ...

-o - Then if no match print the results, (prune the directories and print the remaining results)

18:12 $ mkdir a b c d e
18:13 $ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
18:13 $ find . -type f -path "./a/*" -prune -o -path "./b/*" -prune -o -exec gzip -f -v {} \;

gzip: . is a directory -- ignored
gzip: ./a is a directory -- ignored
gzip: ./b is a directory -- ignored
gzip: ./c is a directory -- ignored
./c/3:    0.0% -- replaced with ./c/3.gz
gzip: ./d is a directory -- ignored
./d/4:    0.0% -- replaced with ./d/4.gz
gzip: ./e is a directory -- ignored
./e/5:    0.0% -- replaced with ./e/5.gz
./e/a:    0.0% -- replaced with ./e/a.gz
./e/b:    0.0% -- replaced with ./e/b.gz

How can I change all input values to uppercase using Jquery?

Try like below,

$('input[type=text]').val (function () {
    return this.value.toUpperCase();
})

You should use input[type=text] instead of :input or input as I believe your intention are to operate on textbox only.

How to convert a Collection to List?

Collections.sort( new ArrayList( coll ) );

What's is the difference between train, validation and test set, in neural networks?

Training set: A set of examples used for learning, that is to fit the parameters [i.e., weights] of the classifier.

Validation set: A set of examples used to tune the parameters [i.e., architecture, not weights] of a classifier, for example to choose the number of hidden units in a neural network.

Test set: A set of examples used only to assess the performance [generalization] of a fully specified classifier.

From ftp://ftp.sas.com/pub/neural/FAQ1.txt section "What are the population, sample, training set, design set, validation"

The error surface will be different for different sets of data from your data set (batch learning). Therefore if you find a very good local minima for your test set data, that may not be a very good point, and may be a very bad point in the surface generated by some other set of data for the same problem. Therefore you need to compute such a model which not only finds a good weight configuration for the training set but also should be able to predict new data (which is not in the training set) with good error. In other words the network should be able to generalize the examples so that it learns the data and does not simply remembers or loads the training set by overfitting the training data.

The validation data set is a set of data for the function you want to learn, which you are not directly using to train the network. You are training the network with a set of data which you call the training data set. If you are using gradient based algorithm to train the network then the error surface and the gradient at some point will completely depend on the training data set thus the training data set is being directly used to adjust the weights. To make sure you don't overfit the network you need to input the validation dataset to the network and check if the error is within some range. Because the validation set is not being using directly to adjust the weights of the netowork, therefore a good error for the validation and also the test set indicates that the network predicts well for the train set examples, also it is expected to perform well when new example are presented to the network which was not used in the training process.

Early stopping is a way to stop training. There are different variations available, the main outline is, both the train and the validation set errors are monitored, the train error decreases at each iteration (backprop and brothers) and at first the validation error decreases. The training is stopped at the moment the validation error starts to rise. The weight configuration at this point indicates a model, which predicts the training data well, as well as the data which is not seen by the network . But because the validation data actually affects the weight configuration indirectly to select the weight configuration. This is where the Test set comes in. This set of data is never used in the training process. Once a model is selected based on the validation set, the test set data is applied on the network model and the error for this set is found. This error is a representative of the error which we can expect from absolutely new data for the same problem.

EDIT:

Also, in the case you do not have enough data for a validation set, you can use crossvalidation to tune the parameters as well as estimate the test error.

Read and write into a file using VBScript

Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.

How to upgrade Python version to 3.7?

On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7

Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa

See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)

If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:

tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install        <-- sudo is required.

This might take a while

How can I force users to access my page over HTTPS instead of HTTP?

Don't mix HTTP and HTTPS on the same page. If you have a form page that is served up via HTTP, I'm going to be nervous about submitting data -- I can't see if the submit goes over HTTPS or HTTP without doing a View Source and hunting for it.

Serving up the form over HTTPS along with the submit link isn't that heavy a change for the advantage.

How to get the text node of an element?

ES6 version that return the first #text node content

const extract = (node) => {
  const text = [...node.childNodes].find(child => child.nodeType === Node.TEXT_NODE);
  return text && text.textContent.trim();
}

Appending to an empty DataFrame in Pandas?

That should work:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
   A
0  0
1  1
2  2

But the append doesn't happen in-place, so you'll have to store the output if you want it:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
   A
0  0
1  1
2  2

How does System.out.print() work?

Evidently, the compiler was made in a confusing way although the compiler developers thought they added some smartness. The true smartness they should really add is to look entire argument and interpret + operator consistently. For example, System.out.println(1+2+"hello"+3+4); should output 3hello7 instead of 3hello34

Send mail via Gmail with PowerShell V2's Send-MailMessage

I haven't used PowerShell V2's Send-MailMessage, but I have used System.Net.Mail.SMTPClient class in V1 to send messages to a Gmail account for demo purposes. This might be overkill, but I run an SMTP server on my Windows Vista laptop (see this link). If you're in an enterprise you will already have a mail relay server, and this step isn't necessary. Having an SMTP server I'm able to send email to my Gmail account with the following code:

$smtpmail = [System.Net.Mail.SMTPClient]("127.0.0.1")
$smtpmail.Send("[email protected]", "[email protected]", "Test Message", "Message via local SMTP")

How do I escape a percentage sign in T-SQL?

You can use the code below to find a specific value.

WHERE col1 LIKE '%[%]75%'

When you want a single digit number after the% sign, you can write the following code.

WHERE col2 LIKE '%[%]_'

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

View is the superclass for all widgets and the OnClickListener interface belongs to this class. All widgets inherit this. View.OnClickListener is the same as OnClickListener. You would have to override the onClick(View view) method from this listener to achieve the action that you want for your button.

To tell Android to listen to click events for a widget, you need to do:

widget.setOnClickListener(this); // If the containing class implements the interface
// Or you can do the following to set it for each widget individually
widget.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something here
    }
});

The 'View' parameter passed in the onClick() method simply lets Android know that a view has been clicked. It can be a Button or a TextView or something else. It is up to you to set an OnClickListener for every widget or to simply make the class containing all these widgets implement the interface. In this case you will have a common onClick() method for all the widgets and all you have to do is to check the id of the view that is passed into the method and then match that against the id for each element that you want and take action for that element.

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:

Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015

How to calculate the intersection of two sets?

Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

Spring cannot find bean xml configuration file when it does exist

Note that the first applicationContext is loaded as part of web.xml; which is mentioned with the below.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>META-INF/spring/applicationContext.xml</param-value>
</context-param>

<servlet>
    <servlet-name>myOwn-controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>META-INF/spring/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Where as below code will also tries to create one more applicationContext.

private static final ApplicationContext context = 
               new ClassPathXmlApplicationContext("beans.xml");

See the difference between beans.xml and applicationContext.xml

And if appliationContext.xml under <META-INF/spring/> has declared with <import resource="beans.xml"/> then this appliationContext.xml is loading the beans.xml under the same location META-INF/spring of appliationContext.xml.

Where as; in the code; if it is declared like below

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

This is looking the beans.xml at WEB-INF/classes OR in eclipse src/main/resources.

[If you have added beans.xml at src/main/resources then it might be placed at WEB-INF/classes while creating the WAR.]

So totally TWO files are looked up.

I have resolved this issue by adding classpath lookup while importing at applicationContext.xml like below

<import resource="classpath*:beans.xml" />

and removed the the line ClassPathXmlApplicationContext("beans.xml") in java code, so that there will be only one ApplicationContext loaded.

Why can't variables be declared in a switch statement?

You can't do this, because case labels are actually just entry points into the containing block.

This is most clearly illustrated by Duff's device. Here's some code from Wikipedia:

strcpy(char *to, char *from, size_t count) {
    int n = (count + 7) / 8;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}

Notice how the case labels totally ignore the block boundaries. Yes, this is evil. But this is why your code example doesn't work. Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable with a constructor.

As several other posters have indicated, you need to put in a block of your own:

switch (...) {
    case FOO: {
        MyObject x(...);
        ...
        break; 
    }
    ...
 }

PHP Warning: Division by zero

You can try with this. You have this error because we can not divide by 'zero' (0) value. So we want to validate before when we do calculations.

if ($itemCost != 0 && $itemCost != NULL && $itemQty != 0 && $itemQty != NULL) 
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}

And also we can validate POST data. Refer following

$itemQty = isset($_POST['num1']) ? $_POST['num1'] : 0;

$itemCost = isset($_POST['num2']) ? $_POST['num2'] : 0;

$itemSale = isset($_POST['num3']) ? $_POST['num3'] : 0;

$shipMat = isset($_POST['num4']) ? $_POST['num4'] : 0;

Online SQL Query Syntax Checker

SQLFiddle will let you test out your queries, while it doesn't explicitly correct syntax etc. per se it does let you play around with the script and will definitely let you know if things are working or not.

Select rows having 2 columns equal value

SELECT *
FROM my_table
WHERE column_a <=> column_b AND column_a <=> column_c

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

C# find biggest number

Use Math.Max:

int x = 3, y = 4, z = 5;
Console.WriteLine(Math.Max(Math.Max(x, y), z));

Landscape printing from HTML

The size property is what you're after as mentioned. To set both the the orientation and size of your page when printing, you could use the following:

/* ISO Paper Size */
@page {
  size: A4 landscape;
}

/* Size in mm */    
@page {
  size: 100mm 200mm landscape;
}

/* Size in inches */    
@page {
  size: 4in 6in landscape;
}

Here's a link to the @page documentation.

How to format DateTime columns in DataGridView?

You can set the format you want:

dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

Here is my combined solution for various PHP versions.

In my company we are working with different servers with various PHP versions, so I had to find solution working for all.

$phpVersion = substr(phpversion(), 0, 3)*1;

if($phpVersion >= 5.4) {
  $encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
  $encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}

Credits should go to Marco Gasi & abu. The solution for PHP >= 5.4 is provided in the json_encode docs.

Where can I find my Facebook application id and secret key?

It is under Account -> Application Settings, click on your application's profile, then go to Edit Application.

Unable to load DLL 'SQLite.Interop.dll'

I had this same problem when using SQLite in a WPF project whose platform target was Any CPU. I fixed it by following the following steps:

  1. Open the project designer in Visual Studio. Details on how to do it can be found here.
  2. Click on the Build tab.
  3. Disable the prefer 32-bit option.

Alternatively, you could just set the platform target to x86 or x64. I think this problem is caused by the System.Data.SQLite library using the platform target to get the location of the 'SQLite.Interop.dll' file.

UPDATE:

In case the project designer cannot be reached, just open the project (*.csproj) file from a text editor and add the value <Prefer32Bit>false</Prefer32Bit> into the <PropertyGroup>...</PropertyGroup> tag.

Example code

<PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>[Set by Visual Studio]</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>[Set by Visual Studio]</RootNamespace>
    <AssemblyName>[Set by Visual Studio]</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>[Set by Visual Studio]</FileAlignment>
    <!--Add the line below to your project file. Leave everything else untouched-->
    <Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>

Using strtok with a std::string

Typecasting to (char*) got it working for me!

token = strtok((char *)str.c_str(), " "); 

How to get default gateway in Mac OSX

You can try with:

route -n get default

It is not the same as GNU/Linux's route -n (or even ip route show) but is useful for checking the default route information. Also, you can check the route that packages will take to a particular host. E.g.

route -n get www.yahoo.com

The output would be similar to:

   route to: 98.137.149.56
destination: default
       mask: 128.0.0.0
    gateway: 5.5.0.1
  interface: tun0
      flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0      1500         0

IMHO netstat -nr is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information. Network utility screenshot displaying routing table information

I hope this helps :)

(*) You can start Network utility with open /Applications/Utilities/Network\ Utility.app

How to manually set an authenticated user in Spring Security / SpringMVC

I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.

public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
                           RequestContext requestContext,
                           ExternalContext externalContext) {

    try {
        Locale userLocale = requestContext.getExternalContext().getLocale();
        this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
        String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
        String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
        doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
        return "success";

    } catch (EmailAddressNotUniqueException e) {
        MessageResolver messageResolvable 
                = new MessageBuilder().error()
                                      .source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
                                      .code("userRegistration.emailAddress.not.unique")
                                      .build();
        requestContext.getMessageContext().addMessage(messageResolvable);
        return "error";
    }

}


private void doAutoLogin(String username, String password, HttpServletRequest request) {

    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = this.authenticationProvider.authenticate(token);
        logger.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        logger.error("Failure in autoLogin", e);
    }

}

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

In addition to REMOTE_ADDR and HTTP_X_FORWARDED_FOR there are some other headers that can be set such as:

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR can be comma delimited list of IPs
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED

I found the code on the following site useful:
http://www.grantburton.com/?p=97

Spring Boot Program cannot find main class

I was having the same problem just delete .m2 folder folder from your local repositry Hope it will work.

How to create jobs in SQL Server Express edition

SQL Server Express doesn't include SQL Server Agent, so it's not possible to just create SQL Agent jobs.

What you can do is:
You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler.
For example, you can backup your database with two files like this:

backup.bat:

sqlcmd -i backup.sql

backup.sql:

backup database TeamCity to disk = 'c:\backups\MyBackup.bak'

Just put both files into the same folder and exeute the batch file via Windows Task Scheduler.

The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file.
The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead.


If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren.

It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express:

How do I get started with the SQL Server Maintenance Solution on SQL Server Express?

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps.

  1. Download MaintenanceSolution.sql.

  2. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need.

  3. Create cmd files to execute the stored procedures; for example:
    sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory = N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt

  4. In Windows Scheduled Tasks, create tasks to call the cmd files.

  5. Schedule the tasks.

  6. Start the tasks and verify that they are completing successfully.

PHP removing a character in a string

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

No suitable records were found verify your bundle identifier is correct

Since this is question obviously has different potential answers depending on the individual circumstances I thought I'd add my problem and what solved it:

Problem: I had someone copy the binary archive, make some changes and then pass the binary onto me. This caused a binary conflict.

Solution: I had to create a new certificate. I copied the bundle ID from the develop consul, pasted into xcode and was able to upload.

Side note: You can regenerate a new bundle id by turning on "In-App Purchases" under Capabilities.

enter image description here

Sorting Python list based on the length of the string

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key=lambda s: len(s))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

Freeze screen in chrome debugger / DevTools panel for popover inspection?

I found that this works really well in Chrome.

Right click on the element that you'd like to inspect, then click Force Element State > Hover. Screenshot attached.

Force element state

What should a JSON service return on failure / error

Rails scaffolds use 422 Unprocessable Entity for these kinds of errors. See RFC 4918 for more information.

How to export html table to excel using javascript

Check this out... I just got this working and it seems exactly what you are trying to do as well.

2 functions. One to select the table and copy it to the clipboard, and the second writes it to excel en masse. Just call write_to_excel() and put in your table id (or modify it to take it as an argument).

  function selectElementContents(el) {
        var body = document.body, range, sel;
        if (document.createRange && window.getSelection) {
            range = document.createRange();
            sel = window.getSelection();
            sel.removeAllRanges();
            try {
                range.selectNodeContents(el);
                sel.addRange(range);
            } catch (e) {
                range.selectNode(el);
                sel.addRange(range);
            }
        } else if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
        range.execCommand("Copy");
    }

function write_to_excel() 
{
var tableID = "AllItems";
selectElementContents( document.getElementById(tableID) );

var excel = new ActiveXObject("Excel.Application");
// excel.Application.Visible = true; 
var wb=excel.WorkBooks.Add();
var ws=wb.Sheets("Sheet1");
ws.Cells(1,1).Select;
ws.Paste;
ws.DrawingObjects.Delete;
ws.Range("A1").Select
 excel.Application.Visible = true; 
}

Heavily influenced from: Select a complete table with Javascript (to be copied to clipboard)

replace NULL with Blank value or Zero in sql server

You should always return the same type on all case condition:

In the first one you have an character and on the else you have an int.

You can use:

Select convert(varchar(11),isnull(totalamount,0))

or if you want with your solution:

Case when total_amount = 0 then '0'   
else convert(varchar(11),isnull(total_amount, 0))  
end as total_amount  

Show MySQL host via SQL Command

show variables where Variable_name='hostname'; 

That could help you !!

How do I use a char as the case in a switch-case?

charAt gets a character from a string, and you can switch on them since char is an integer type.

So to switch on the first char in the String hello,

switch (hello.charAt(0)) {
  case 'a': ... break;
}

You should be aware though that Java chars do not correspond one-to-one with code-points. See codePointAt for a way to reliably get a single Unicode codepoints.

Python convert set to string and vice versa

The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !

let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.

If interested to serialize you can use:

json.dumps  -> serialize
json.loads  -> deserialize

If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)

String to Set

set('abca')

Set to String

''.join(some_var_set)

example:

def test():
    some_var_set=set('abca')
    print("here is the set:",some_var_set,type(some_var_set))
    some_var_string=''.join(some_var_set)    
    print("here is the string:",some_var_string,type(some_var_string))

test()

How do I open an .exe from another C++ .exe?

Try this:

#include <windows.h>

int main ()

{
    system ("start notepad.exe") // As an example. Change [notepad] to any executable file //

    return 0 ;
}

How to convert int to char with leading zeros?

Works in SQLServer

declare @myNumber int = 123
declare @leadingChar varchar(1) = '0'
declare @numberOfLeadingChars int = 5

select right(REPLICATE ( @leadingChar , @numberOfLeadingChars ) + cast(@myNumber as varchar(max)), @numberOfLeadingChars)

Enjoy

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Although I like fhucho's recommendation of

String.valueOf(i)

The irony is that this method actually calls

Integer.toString(i)

Thus, use String.valueOf(i) if you like how it reads and you don't need radix, but also knowing that it is less efficient than Integer.toString(i).

Get PHP class property by string

Something like this? Haven't tested it but should work fine.

function magic($obj, $var, $value = NULL)
{
    if($value == NULL)
    {
        return $obj->$var;
    }
    else
    {
        $obj->$var = $value;
    }
}

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

when you setup the java home variable try to target path till JDK instead of java. setup path like: C:\Program Files\Java\jdk1.8.0_231

if you make path like C:\Program Files\Java it will run java but it will not run maven.

Git: Remove committed file after push

Reset the file in a correct state, commit, and push again.

If you're sure nobody else has fetched your changes yet, you can use --amend when committing, to modify your previous commit (i.e. rewrite history), and then push. I think you'll have to use the -f option when pushing, to force the push, though.

Import numpy on pycharm

In general, the cause of the problem could be the following:

You started a new project with the new virtual environment. So probably you install numpy from the terminal, but it is not in your venv. So

  • either install it from PyCahrm Interface: Settings -> Project Interpreter -> Add the package

  • or activate your venv and -> pip install numPy

excel plot against a date time x series

I know this is an old question, but I was struggling to do this with a time period over 2 hours, so this might help someone. Also, several of the answers don't actually plot against time, giving equal space whatever the duration.

Firstly, as @jameswarren says, use a scatter graph. Then right-click the horizontal axis and choose Format Axis.

Under Number, select Time, and at this point you may find your scale goes a bit crazy, because it chooses to scale the axis by days. So go back to Axis Options and select Fixed for the Minimum, Maximum and Major unit scales.

To set the unit to hours, type in 1/24 = 0.0416667 (I used half that to get half-hourly increments). To make this start at a round number, multiply it by your preferred number of hours and type that into the Minimum box. In my case 08:00 = 0.333333

graph showing plot against time on x-axis

How to split a dataframe string column into two columns?

Surprised I haven't seen this one yet. If you only need two splits, I highly recommend. . .

Series.str.partition

partition performs one split on the separator, and is generally quite performant.

df['row'].str.partition(' ')[[0, 2]]

       0                   2
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If you need to rename the rows,

df['row'].str.partition(' ')[[0, 2]].rename({0: 'fips', 2: 'row'}, axis=1)

    fips                 row
0  00000       UNITED STATES
1  01000             ALABAMA
2  01001  Autauga County, AL
3  01003  Baldwin County, AL
4  01005  Barbour County, AL

If you need to join this back to the original, use join or concat:

df.join(df['row'].str.partition(' ')[[0, 2]])

pd.concat([df, df['row'].str.partition(' ')[[0, 2]]], axis=1)

                        row      0                   2
0       00000 UNITED STATES  00000       UNITED STATES
1             01000 ALABAMA  01000             ALABAMA
2  01001 Autauga County, AL  01001  Autauga County, AL
3  01003 Baldwin County, AL  01003  Baldwin County, AL
4  01005 Barbour County, AL  01005  Barbour County, AL

Select values of checkbox group with jQuery

You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):

$("input[name='user_group[]']:checked")

With those checked items, you can either create a collection of those values or do something to the collection:

var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
  values.push($(this).val());
  // or you can do something to the actual checked checkboxes by working directly with  'this'
  // something like $(this).hide() (only something useful, probably) :P
});

get current date from [NSDate date] but set the time to 10:00 am

You can use this method for any minute / hour / period (aka am/pm) combination:

- (NSDate *)todayModifiedWithHours:(NSString *)hours
                           minutes:(NSString *)minutes
                         andPeriod:(NSString *)period
{
    NSDate *todayModified = NSDate.date;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];

    [components setMinute:minutes.intValue];

    int hour = 0;

    if ([period.uppercaseString isEqualToString:@"AM"]) {

        if (hours.intValue == 12) {
            hour = 0;
        }
        else {
            hour = hours.intValue;
        }
    }
    else if ([period.uppercaseString isEqualToString:@"PM"]) {

        if (hours.intValue != 12) {
            hour = hours.intValue + 12;
        }
        else {
            hour = 12;
        }
    }
    [components setHour:hour];

    todayModified = [calendar dateFromComponents:components];

    return todayModified;
}

Requested Example:

NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
                                           minutes:@"00"
                                         andPeriod:@"am"];

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

  • It did not work so i switched to oracle sql developer and it worked with no problems (making connection under 1 minute).
  • This link gave me an idea connect to MS Access so i created a user in oracle sql developer and the tried to connect to it in Toad and it worked.

Or second solution

you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I was trying to get clang to work (which also requires 6.0.15), and while poking around I found it was installed at /usr/local/lib/libstdc++.so.6.0.15. It installed there when I installed graphite (an experimental gcc version).

If you need access to libraries at that location, then you’ll need to define LD_LIBRARY_PATH as:

export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/usr/local/lib64:/usr/lib64

I was able to get clang to work after doing this. Hope that is helpful to someone.

How to programmatically send a 404 response with Express/Node?

IMO the nicest way is to use the next() function:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

Then the error is handled by your error handler and you can style the error nicely using HTML.

Array or List in Java. Which is faster?

I suggest that you use a profiler to test which is faster.

My personal opinion is that you should use Lists.

I work on a large codebase and a previous group of developers used arrays everywhere. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.

Escape @ character in razor view engine

I tried all the options above and none worked. This is what I did that worked :

@{
    string str = @"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$";
}

<td>Email</td>
<td>
   <input type="text" id="txtEmail" required name="email" pattern=@str /> 
</td>

I created a string varible and passed all the RegEx pattern code into it, then used the variable in the html, and Razor was cool with it.

Python can't find module in the same folder

I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script

Input widths on Bootstrap 3

Bootstrap uses the class 'form-input' for controlling the attributes of 'input fields'. Simply, add your own 'form-input' class with the desired width, border, text size, etc in your css file or head section.

(or else, directly add the size='5' inline code in input attributes in the body section.)

<script async src="//jsfiddle.net/tX3ae/embed/"></script> 

Convert SQL Server result set into string

Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:

NULL + "Any text" => NULL

It's a very common mistake, don't forget it!

Also is good idea to use ISNULL function:

SELECT @result = @result + ISNULL(StudentId + ',', '') FROM Student

Are complex expressions possible in ng-hide / ng-show?

Some of these above answers didn't work for me but this did. Just in case someone else has the same issue.

ng-show="column != 'vendorid' && column !='billingMonth'"

Java Program to test if a character is uppercase/lowercase/number/vowel

In Java : Character class has static method called isLowerCase(Char ch) ans isUpperCase(Char ch) , Character.isDigit(Char ch)gives you Boolean value, base on that you can easily achieve your task

example:

String abc = "HomePage";

char ch = abc.charAt(i); // here i= 1,2,3......

if(Character.isLowerCase(ch))
{
   // do something :  ch is in lower case
}

if(Character.isUpperCase(ch))
{
   // do something : ch is in Upper case
}

if(Character.isDigit(ch))
{
  // do something : ch is in Number / Digit
}

How to Right-align flex item?

If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:

h1 {
   flex-basis: 100%; // forces this element to take up any remaining space
}

img {
   margin: 0 5px; // small margin between images
   height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}

Here's what that will look like (only relavent CSS was included in snippet above)

enter image description here

How do I insert multiple checkbox values into a table?

I think you should $_POST[][], i tried it and it work :)), tks

How to split a string between letters and digits (or between digits and letters)?

Didn't use Java for ages, so just some pseudo code, that should help get you started (faster for me than looking up everything :) ).

 string a = "123abc345def";
 string[] result;
 while(a.Length > 0)
 {
      string part;
      if((part = a.Match(/\d+/)).Length) // match digits
           ;
      else if((part = a.Match(/\a+/)).Length) // match letters
           ;
      else
           break; // something invalid - neither digit nor letter
      result.append(part);
      a = a.SubStr(part.Length - 1); // remove the part we've found
 }

Possible to iterate backwards through a foreach?

This works pretty well

List<string> list = new List<string>();

list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");

foreach (String s in list)
{
    Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How to use a jQuery plugin inside Vue

First install jquery using npm,

npm install jquery --save

I use:

global.jQuery = require('jquery');
var $ = global.jQuery;
window.$ = $;

Check for database connection, otherwise display message

Please check this:

$servername='localhost';
$username='root';
$password='';
$databasename='MyDb';

$connection = mysqli_connect($servername,$username,$password);

if (!$connection) {
die("Connection failed: " . $conn->connect_error);
}

/*mysqli_query($connection, "DROP DATABASE if exists MyDb;");

if(!mysqli_query($connection, "CREATE DATABASE MyDb;")){
echo "Error creating database: " . $connection->error;
}

mysqli_query($connection, "use MyDb;");
mysqli_query($connection, "DROP TABLE if exists employee;");

$table="CREATE TABLE employee (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)"; 
$value="INSERT INTO employee (firstname,lastname,email) VALUES ('john', 'steve', '[email protected]')";
if(!mysqli_query($connection, $table)){echo "Error creating table: " . $connection->error;}
if(!mysqli_query($connection, $value)){echo "Error inserting values: " . $connection->error;}*/

IIS7 folder permissions for web application

Worked for me in 30 seconds, short and sweet:

  1. In IIS Manager (run inetmgr)
  2. Go to ApplicationPool -> Advanced Settings
  3. Set ApplicationPoolIdentity to NetworkService
  4. Go to the file, right click properties, go to security, click edit, click add, enter Network Service (with space, then click 'check names'), and give full control (or just whatever permissions you need)

Add days Oracle SQL

If you want to add N days to your days. You can use the plus operator as follows -

SELECT ( SYSDATE + N ) FROM DUAL;

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

How to set menu to Toolbar in Android

Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.

enter image description here

1. Make a menu xml

This is going to be in res/menu/main_menu.

  • Right click the res folder and choose New > Android Resource File.
  • Type main_menu for the File name.
  • Choose Menu for the Resource type.

Paste in the following content as a starter.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_add"
        android:icon="@drawable/ic_add"
        app:showAsAction="ifRoom"
        android:title="Add">
    </item>
    <item
        android:id="@+id/action_settings"
        app:showAsAction="never"
        android:title="Settings">
    </item>
</menu>

You can right click res and choose New image asset to create the ic_add icon.

2. Inflate the menu

In your activity add the following method.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

3. Handle menu clicks

Also in your Activity, add the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_add:
            addSomething();
            return true;
        case R.id.action_settings:
            startSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Further reading

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

Text-align class for inside a table

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
Left aligned text on viewports sized MD (medium) or wider.

Left aligned text on viewports sized LG (large) or wider.

Left aligned text on viewports sized XL (extra-large) or wider.

Toolbar navigation icon never set

I tried to set up toolbar like @Gabriele Mariotti, but I had some problem with title. So then I set order to

toolbar.setTitle("Title")
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_good);

and it works.

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Make sure to import component in declarations array

@NgModule({
  declarations: [ExampleComponent],
  imports: [
      CommonModule,
      ExampleRoutingModule,
      ReactiveFormsModule
  ]
})

executing shell command in background from script

Leave off the quotes

$cmd &
$othercmd &

eg:

nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash

cmd="ls -la"

$cmd &


nicholas@nick-win7 /tmp
$ ./test

nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root    0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx  1 nicholas None   35 2010-09-10 20:44 test
-rwxr-xr-x  1 nicholas None   41 2010-09-10 20:43 test~

How to run a function when the page is loaded?

window.onload will work like this:

_x000D_
_x000D_
function codeAddress() {_x000D_
 document.getElementById("test").innerHTML=Date();_x000D_
}_x000D_
window.onload = codeAddress;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>learning java script</title>_x000D_
 <script src="custom.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
 <p id="test"></p>_x000D_
 <li>abcd</li>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Safest way to convert float to integer in python?

That this works is not trivial at all! It's a property of the IEEE floating point representation that int°floor = ?·? if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

This post explains why it works in that range.

In a double, you can represent 32bit integers without any problems. There cannot be any rounding issues. More precisely, doubles can represent all integers between and including 253 and -253.

Short explanation: A double can store up to 53 binary digits. When you require more, the number is padded with zeroes on the right.

It follows that 53 ones is the largest number that can be stored without padding. Naturally, all (integer) numbers requiring less digits can be stored accurately.

Adding one to 111(omitted)111 (53 ones) yields 100...000, (53 zeroes). As we know, we can store 53 digits, that makes the rightmost zero padding.

This is where 253 comes from.


More detail: We need to consider how IEEE-754 floating point works.

  1 bit    11 / 8     52 / 23      # bits double/single precision
[ sign |  exponent | mantissa ]

The number is then calculated as follows (excluding special cases that are irrelevant here):

-1sign × 1.mantissa ×2exponent - bias

where bias = 2exponent - 1 - 1, i.e. 1023 and 127 for double/single precision respectively.

Knowing that multiplying by 2X simply shifts all bits X places to the left, it's easy to see that any integer must have all bits in the mantissa that end up right of the decimal point to zero.

Any integer except zero has the following form in binary:

1x...x where the x-es represent the bits to the right of the MSB (most significant bit).

Because we excluded zero, there will always be a MSB that is one—which is why it's not stored. To store the integer, we must bring it into the aforementioned form: -1sign × 1.mantissa ×2exponent - bias.

That's saying the same as shifting the bits over the decimal point until there's only the MSB towards the left of the MSB. All the bits right of the decimal point are then stored in the mantissa.

From this, we can see that we can store at most 52 binary digits apart from the MSB.

It follows that the highest number where all bits are explicitly stored is

111(omitted)111.   that's 53 ones (52 + implicit 1) in the case of doubles.

For this, we need to set the exponent, such that the decimal point will be shifted 52 places. If we were to increase the exponent by one, we cannot know the digit right to the left after the decimal point.

111(omitted)111x.

By convention, it's 0. Setting the entire mantissa to zero, we receive the following number:

100(omitted)00x. = 100(omitted)000.

That's a 1 followed by 53 zeroes, 52 stored and 1 added due to the exponent.

It represents 253, which marks the boundary (both negative and positive) between which we can accurately represent all integers. If we wanted to add one to 253, we would have to set the implicit zero (denoted by the x) to one, but that's impossible.

Uninstalling Android ADT

If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.

What is __gxx_personality_v0 for?

Exception handling is included in free standing implementations.

The reason of this is that you possibly use gcc to compile your code. If you compile with the option -### you will notice it is missing the linker-option -lstdc++ when it invokes the linker process . Compiling with g++ will include that library, and thus the symbols defined in it.

Factory Pattern. When to use factory methods?

Factory classes are more heavyweight, but give you certain advantages. In cases when you need to build your objects from multiple, raw data sources they allow you to encapsulate only the building logic (and maybe the aggregation of the data) in one place. There it can be tested in abstract without being concerned with the object interface.

I have found this a useful pattern, particularly where I am unable to replace and inadequate ORM and want to efficiently instantiate many objects from DB table joins or stored procedures.

Filtering DataGridView without changing datasource

I developed a generic statement to apply the filter:

string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;

The square brackets allow for spaces in the column name.

Additionally, if you want to include multiple values in your filter, you can add the following line for each additional value:

rowFilter += string.Format(" OR [{0}] = '{1}'", columnName, additionalFilterValue);

When should we use Observer and Observable?

In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):

If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.

Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.

Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.

The last thing to close the puzzle is how will the Observable class know who is interested? So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o) internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.

It might be that in the interview they did not ask you explicitly about the java.util.Observer and java.util.Observable but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).

UPDATE

In response to your comment, the actual java.util.Observable class offers the following facilities:

  1. Maintaining a list of java.util.Observer instances. New instances interested in being notified can be added through addObserver(Observer o), and removed through deleteObserver(Observer o).

  2. Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged(). So you just call it when you changed something to the Observable and you want the rest of the Observers to eventually know about it.

  3. Notifying all observers that the specific Observable has changed state. This is done through notifyObservers(). This checks if the object has actually changed (i.e. a call to setChanged() was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer instances and calls the update(Observable o, Object arg) method for each of them. This tells the Observer which was the Observable object that changed (you could be observing more than one), and the extra Object arg to potentially carry some extra information (passed through notifyObservers().

JavaScript chop/slice/trim off last character in string

Using JavaScript's slice function:

_x000D_
_x000D_
let string = 'foo_bar';_x000D_
string = string.slice(0, -4); // Slice off last four characters here_x000D_
console.log(string);
_x000D_
_x000D_
_x000D_

This could be used to remove '_bar' at end of a string, of any length.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Docker: How to use bash with an Alpine based docker image?

RUN /bin/sh -c "apk add --no-cache bash"

worked for me.

How to Sort Multi-dimensional Array by Value?

I use this function :

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}


array_sort_by_column($array, 'order');

Implement a simple factory pattern with Spring 3 annotations

You are right, by creating object manually you are not letting Spring to perform autowiring. Consider managing your services by Spring as well:

@Component
public class MyServiceFactory {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public static MyService getMyService(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne;
        } else if (service.equals("two")) {
            return myServiceTwo;
        } else if (service.equals("three")) {
            return myServiceThree;
        } else {
            return myServiceDefault;
        }
    }
}

But I would consider the overall design to be rather poor. Wouldn't it better to have one general MyService implementation and pass one/two/three string as extra parameter to checkStatus()? What do you want to achieve?

@Component
public class MyServiceAdapter implements MyService {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public boolean checkStatus(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne.checkStatus();
        } else if (service.equals("two")) {
            return myServiceTwo.checkStatus();
        } else if (service.equals("three")) {
            return myServiceThree.checkStatus();
        } else {
            return myServiceDefault.checkStatus();
        }
    }
}

This is still poorly designed because adding new MyService implementation requires MyServiceAdapter modification as well (SRP violation). But this is actually a good starting point (hint: map and Strategy pattern).

How do I fix MSB3073 error in my post-build event?

I was getting this error after downloading some source code from Github. Specifically the rust oxide development framework. My problem is that the Steam.ps1 script file, that's used to update some of the dlls from Steam was blocked by the OS. I had to open the files properties an UNBLOCK it. I had not realized this was done to ps1 files as well as exes.

How do I get the project basepath in CodeIgniter

use base_url()

echo $baseurl=base_url();

if you need to pass url to a function then use site_url()

 echo site_url('controller/function');

if you need the root path then FCPATH..

echo FCPATH;

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

Center div on the middle of screen

The best way to align a div in center both horizontally and vertically will be

HTML

<div></div>

CSS:

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

Remove a JSON attribute

Simple:

delete myObj.test.key1;

How to catch integer(0)?

You can easily catch integer(0) with function identical(x,y)

x = integer(0)
identical(x, integer(0))
[1] TRUE

foo = function(x){identical(x, integer(0))}
foo(x)
[1] TRUE

foo(0)
[1] FALSE

Can't update: no tracked branch

In the same case this works for me:

< git checkout Branch_name
> Switched to branch 'Branch_name'

< git fetch
> [Branch_name]      Branch_name       -> origin/Branch_name

< git branch --set-upstream-to origin/Branch_name Branch_name
> Branch Branch_name set up to track remote branch <New_Branch> from origin.

Cannot bulk load. Operating system error code 5 (Access is denied.)

This is what worked for me:

Log on SSIS with Windows authentication.

1. Open services and find MSSQL NT Service account name and copy it:

enter image description here

2. Open folder from which SQL server should read from. Security - Group or user names tab - Add and paste there copied account:**

enter image description here

  1. You will probably get "Multiple names found error", just select MSSQL user:

enter image description here

Your BULK INSERT query should run fine now. If problem persists try adding SQL Server Agent account to folder permissions in same way. Make sure you restart MSSQL server in services after you are done.

Convert a Python int into a big-endian string of bytes

Single-source Python 2/3 compatible version based on @pts' answer:

#!/usr/bin/env python
import binascii

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

print(int2bytes(1245427))
# -> b'\x13\x00\xf3'

Bootstrap trying to load map file. How to disable it? Do I need to do it?

Delete /*# sourceMappingURL=bootstrap.min.css.map */ in css/bootstrap.min.css

and delete /*# sourceMappingURL=bootstrap.css.map */ in css/bootstrap.css

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

I fixed this by generating my provisioning profile again (and again).

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

Spark - Error "A master URL must be set in your configuration" when submitting an app

var appName:String ="test"
val conf = new SparkConf().setAppName(appName).setMaster("local[*]").set("spark.executor.memory","1g");
val sc =  SparkContext.getOrCreate(conf)
sc.setLogLevel("WARN")

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Can't ping a local VM from the host

The issue could be that the VM is connected to the network via NAT. You need to set the network adapter of the VM to a bridged connection so that the VM will get it's own IP within the actual network and not on the LAN on the host.

List names of all tables in a SQL Server 2012 schema

SQL Server 2005, 2008, 2012 or 2014:

SELECT * FROM information_schema.tables WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA = 'dbo'

For more details: How do I get list of all tables in a database using TSQL?

Setting up JUnit with IntelliJ IDEA

  1. Create and setup a "tests" folder
    • In the Project sidebar on the left, right-click your project and do New > Directory. Name it "test" or whatever you like.
    • Right-click the folder and choose "Mark Directory As > Test Source Root".
  2. Adding JUnit library
    • Right-click your project and choose "Open Module Settings" or hit F4. (Alternatively, File > Project Structure, Ctrl-Alt-Shift-S is probably the "right" way to do this)
    • Go to the "Libraries" group, click the little green plus (look up), and choose "From Maven...".
    • Search for "junit" -- you're looking for something like "junit:junit:4.11".
    • Check whichever boxes you want (Sources, JavaDocs) then hit OK.
    • Keep hitting OK until you're back to the code.
  3. Write your first unit test

    • Right-click on your test folder, "New > Java Class", call it whatever, e.g. MyFirstTest.
    • Write a JUnit test -- here's mine:

      import org.junit.Assert;
      import org.junit.Test;
      
      public class MyFirstTest {
          @Test
          public void firstTest() {
              Assert.assertTrue(true);
          }
      }
      
  4. Run your tests
    • Right-click on your test folder and choose "Run 'All Tests'". Presto, testo.
    • To run again, you can either hit the green "Play"-style button that appeared in the new section that popped on the bottom of your window, or you can hit the green "Play"-style button in the top bar.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:

.navbar-brand {
    min-height: 80px;
}

@media (min-width: 768px) {
    #navbar-collapse {
        position: absolute;
        bottom: 0px;
        left: 250px;
    }
}

My brand image is SVG and I used height: 50px; width: auto which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px; to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse's left setting until it looked right.

Difference between UTF-8 and UTF-16?

Security: Use only UTF-8

Difference between UTF-8 and UTF-16? Why do we need these?

There have been at least a couple of security vulnerabilities in implementations of UTF-16. See Wikipedia for details.

WHATWG and W3C have now declared that only UTF-8 is to be used on the Web.

The [security] problems outlined here go away when exclusively using UTF-8, which is one of the many reasons that is now the mandatory encoding for all things.

Other groups are saying the same.

So while UTF-16 may continue being used internally by some systems such as Java and Windows, what little use of UTF-16 you may have seen in the past for data files, data exchange, and such, will likely fade away entirely.

Can a class member function template be virtual?

No they can't. But:

template<typename T>
class Foo {
public:
  template<typename P>
  void f(const P& p) {
    ((T*)this)->f<P>(p);
  }
};

class Bar : public Foo<Bar> {
public:
  template<typename P>
  void f(const P& p) {
    std::cout << p << std::endl;
  }
};

int main() {
  Bar bar;

  Bar *pbar = &bar;
  pbar -> f(1);

  Foo<Bar> *pfoo = &bar;
  pfoo -> f(1);
};

has much the same effect if all you want to do is have a common interface and defer implementation to subclasses.

Jenkins - How to access BUILD_NUMBER environment variable

Assuming I am understanding your question and setup correctly,

If you're trying to use the build number in your script, you have two options:

1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}

2) Change your script so that:

<property environment="env" />
<property name="build_parameter"  value="${env.BUILD_NUMBER}"/>

How to add "active" class to Html.ActionLink in ASP.NET MVC

I have make combination of answers above and made my solution.

So..

First in razor block create one string variable which will contain name value of controller and action that is called by user.

    @{
        string controllerAction =  ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString(); 
    }

Then use combination of HTML and Razor code:

    <ul class="nav navbar-nav">
        <li class="@(controllerAction == "HomeIndex" ? "active" : "" )">@Html.ActionLink("Home", "Index", "Home")</li>
        <li class="@(controllerAction == "AboutIndex" ? "active" : "" )">@Html.ActionLink("About", "Index", "About")</li>
        <li class="@(controllerAction == "HomeContact" ? "active" : "" )">@Html.ActionLink("Contact", "Contact", "Home")</li>
    </ul>

I think, that this is good because you don't need to access "ViewContext.RouteData.Values" each time to get controller name and action name.

Is there a macro to conditionally copy rows to another worksheet?

This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

You may want to add logic to sort your monthly data after it's all been copied

Public Sub MoveData(MonthNumber As Integer, SheetName As String)

Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range

Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
    If Format(cell.Value, "MM") = MonthNumber Then
        copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
    End If
Next cell

End Sub

Sub copyRowTo(rng As Range, ws As Worksheet)
    Dim newRange As Range
    Set newRange = ws.Range("A1")
    If newRange.Offset(1).Value <> "" Then
        Set newRange = newRange.End(xlDown).Offset(1)
        Else
        Set newRange = newRange.Offset(1)
    End If
    rng.Copy
    newRange.PasteSpecial (xlPasteAll)
End Sub

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

Difference between ProcessBuilder and Runtime.exec()

The various overloads of Runtime.getRuntime().exec(...) take either an array of strings or a single string. The single-string overloads of exec() will tokenise the string into an array of arguments, before passing the string array onto one of the exec() overloads that takes a string array. The ProcessBuilder constructors, on the other hand, only take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.

So, for example, on Windows,

Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");

will run a DoStuff.exe program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");

will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2 in C:\. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");

or alternatively

List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);

Extracting .jar file with command line

Java has a class specifically for zip files and one even more specifically for Jar Files.

java.util.jar.JarOutputStream
java.util.jar.JarInputStream

using those you could, on a command from the console, using a scanner set to system.in

Scanner console = new Scanner(System.in);
String input = console.nextLine();

then get all the components and write them as a file.

JarEntry JE = null;
while((JE = getNextJarEntry()) != null)
{
    //do stuff with JE
}

You can also use java.util.zip.ZipInputStream instead, as seeing a JAR file is in the same format as a ZIP file, ZipInputStream will be able to handle the Jar file, in fact JarInputStream actually extends ZipInputStream.

an alternative is also instead of getNextJarEntry, to use getNextEntry

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind is also safer because it represents html as a string.

So for example, '<script on*=maliciousCode()></script>' will be displayed as a string and not be executed.

Laravel whereIn OR whereIn

For example, if you have multiple whereIn OR whereIn conditions and you want to put brackets, do it like this:

$getrecord = DiamondMaster::where('is_delete','0')->where('user_id',Auth::user()->id);
if(!empty($request->stone_id))
{
    $postdata = $request->stone_id;
    $certi_id =trim($postdata,",");
    $getrecord = $getrecord->whereIn('id',explode(",", $certi_id))
                           ->orWhereIn('Certi_NO',explode(",", $certi_id));     
}
$getrecord = $getrecord->get();

"SyntaxError: Unexpected token < in JSON at position 0"

In my Case there was problem with "Bearer" in header ideally it should be "Bearer "(space after the end character) but in my case it was "Bearer" there was no space after the character. Hope it helps some one!

Asynchronous vs synchronous execution, what does it really mean?

When executing a sequence like: a>b>c>d>, if we get a failure in the middle of execution like:

a
b
c
fail

Then we re-start from the beginning:

a
b
c
d

this is synchronous

If, however, we have the same sequence to execute: a>b>c>d>, and we have a failure in the middle:

a
b
c
fail

...but instead of restarting from the beginning, we re-start from the point of failure:

c
d

...this is know as asynchronous.

Testing if a list of integer is odd or even

        #region even and odd numbers
        for (int x = 0; x <= 50; x = x + 2)
        {

            int y = 1;
            y = y + x;
            if (y < 50)
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
                Console.ReadKey();
            }

        }

        //order by desc

        for (int z = 50; z >= 0; z = z - 2)
        {
            int w = z;
            w = w - 1;
            if (w > 0)
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
                Console.ReadKey();
            }
        }

How to use aria-expanded="true" to change a css property

If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded set to true by doing the following...

$("a[aria-expanded='true']").css("background-color", "#42DCA3");

Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.

How to open a link in new tab using angular?

Use window.open(). It's pretty straightforward !

In your component.html file-

<a (click)="goToLink("www.example.com")">page link</a>

In your component.ts file-

goToLink(url: string){
    window.open(url, "_blank");
}

Use latest version of Internet Explorer in the webbrowser control

I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype

InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;

internal class InternetExplorerFeatureControl
{
    private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
    private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
    private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
    private readonly string _processName;
    private readonly Version _version;

    #region Feature Control Strings (A)

    private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
    private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";

    #endregion

    #region Feature Control Strings (B)

    private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";

    #endregion

    #region Feature Control Strings (G)

    private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";

    #endregion

    #region Feature Control Strings (L)

    private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";

    #endregion

    internal InternetExplorerFeatureControl()
    {
        _processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
        using (var webBrowser = new WebBrowser())
            _version = webBrowser.Version;
    }

    internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;

    internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;

    private int GetFeatureControl(string featureControl)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
            {
                if (key.GetValue(_processName) is int value)
                {
                    return value;
                }
                return -1;
            }
        }
    }

    private void SetFeatureControl(string featureControl, int value)
    {
        using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
        {
            using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
            {
                key.SetValue(_processName, value, RegistryValueKind.DWord);
            }
        }
    }

    #region Internet Feature Controls (A)

    /// <summary>
    /// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
    /// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool AboutProtocolRestriction
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
            var releaseVersion = new Version(8, 0, 6001, 18702);
            SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (B)

    /// <summary>
    /// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
    /// </summary>
    internal DocumentMode BrowserEmulation
    {
        get
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var value = GetFeatureControl(FeatureBrowserEmulation);
            if (Enum.IsDefined(typeof(DocumentMode), value))
            {
                return (DocumentMode)value;
            }
            return DocumentMode.NotSet;
        }
        set
        {
            if (_version.Major < 8)
                throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
            var tmp = value;
            if (value == DocumentMode.DefaultRespectDocType)
                tmp = DefaultRespectDocType;
            else if (value == DocumentMode.DefaultOverrideDocType)
                tmp = DefaultOverrideDocType;
            SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
        }
    }

    #endregion

    #region Internet Feature Controls (G)

    /// <summary>
    /// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
    /// </summary>
    internal bool GpuRendering
    {
        get
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
        }
        set
        {
            if (_version.Major < 9)
                throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
            SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
        }
    }

    #endregion

    #region Internet Feature Controls (L)

    /// <summary>
    /// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
    /// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
    /// </summary>
    internal bool LocalScriptBlocking
    {
        get
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
        }
        set
        {
            if (_version.Major < 7)
                throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
            SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
        }
    }

    #endregion


    private DocumentMode DefaultRespectDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11RespectDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10RespectDocType;
                case 9:
                    return DocumentMode.InternetExplorer9RespectDocType;
                case 8:
                    return DocumentMode.InternetExplorer8RespectDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }

    private DocumentMode DefaultOverrideDocType
    {
        get
        {
            if (_version.Major >= 11)
                return DocumentMode.InternetExplorer11OverrideDocType;
            switch (_version.Major)
            {
                case 10:
                    return DocumentMode.InternetExplorer10OverrideDocType;
                case 9:
                    return DocumentMode.InternetExplorer9OverrideDocType;
                case 8:
                    return DocumentMode.InternetExplorer8OverrideDocType;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

internal enum DocumentMode
{
    NotSet = -1,
    [Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
    DefaultRespectDocType,
    [Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive.  Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
    DefaultOverrideDocType,
    [Description(
        "Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer11OverrideDocType = 11001,

    [Description(
        "IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
    )] InternetExplorer11RespectDocType = 11000,

    [Description(
        "Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
    )] InternetExplorer10OverrideDocType = 10001,

    [Description(
        "Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
    )] InternetExplorer10RespectDocType = 10000,

    [Description(
        "Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer9OverrideDocType = 9999,

    [Description(
        "Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer9RespectDocType = 9000,

    [Description(
        "Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
    )] InternetExplorer8OverrideDocType = 8888,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
        "Important  In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
    )] InternetExplorer8RespectDocType = 8000,

    [Description(
        "Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
    )] InternetExplorer7RespectDocType = 7000
}

How to find current transaction level?

DECLARE   @UserOptions TABLE(SetOption varchar(100), Value varchar(100))
DECLARE   @IsolationLevel varchar(100)

INSERT    @UserOptions
EXEC('DBCC USEROPTIONS WITH NO_INFOMSGS')

SELECT    @IsolationLevel = Value
FROM      @UserOptions
WHERE     SetOption = 'isolation level'

-- Do whatever you want with the variable here...  
PRINT     @IsolationLevel

Log4Net configuring log level

you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters

in ur appender section add

<filter type="log4net.Filter.LevelMatchFilter">
    <levelToMatch value="Info" />
    <acceptOnMatch value="true" />
</filter>

the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters

String comparison - Android

This should work:

if(gender.equals("Male")){
 salutation ="Mr.";
}
else if(gender.equals("Female")){
 salutation ="Ms.";
}

Remember, not to use ; after if statement.

PostgreSQL: How to make "case-insensitive" query

The most common approach is to either lowercase or uppercase the search string and the data. But there are two problems with that.

  1. It works in English, but not in all languages. (Maybe not even in most languages.) Not every lowercase letter has a corresponding uppercase letter; not every uppercase letter has a corresponding lowercase letter.
  2. Using functions like lower() and upper() will give you a sequential scan. It can't use indexes. On my test system, using lower() takes about 2000 times longer than a query that can use an index. (Test data has a little over 100k rows.)

There are at least three less frequently used solutions that might be more effective.

  1. Use the citext module, which mostly mimics the behavior of a case-insensitive data type. Having loaded that module, you can create a case-insensitive index by CREATE INDEX ON groups (name::citext);. (But see below.)
  2. Use a case-insensitive collation. This is set when you initialize a database. Using a case-insensitive collation means you can accept just about any format from client code, and you'll still return useful results. (It also means you can't do case-sensitive queries. Duh.)
  3. Create a functional index. Create a lowercase index by using CREATE INDEX ON groups (LOWER(name));. Having done that, you can take advantage of the index with queries like SELECT id FROM groups WHERE LOWER(name) = LOWER('ADMINISTRATOR');, or SELECT id FROM groups WHERE LOWER(name) = 'administrator'; You have to remember to use LOWER(), though.

The citext module doesn't provide a true case-insensitive data type. Instead, it behaves as if each string were lowercased. That is, it behaves as if you had called lower() on each string, as in number 3 above. The advantage is that programmers don't have to remember to lowercase strings. But you need to read the sections "String Comparison Behavior" and "Limitations" in the docs before you decide to use citext.

Maven does not find JUnit tests to run

Another thing that can cause Maven to not find the tests if if the module's packaging is not declared correctly.

In a recent case, someone had <packaging>pom</packaging> and my tests never ran. I changed it to <packaging>jar</packaging> and now it works fine.

href="file://" doesn't work

Although the ffile:////.exe used to work (for example - some versions of early html 4) it appears html 5 disallows this. Tested using the following:

<a href="ffile:///<path name>/<filename>.exe" TestLink /a> 
<a href="ffile://<path name>/<filename>.exe" TestLink /a> 
<a href="ffile:/<path name>/<filename>.exe" TestLink /a> 
<a href="ffile:<path name>/<filename>.exe" TestLink /a> 
<a href="ffile://///<path name>/<filename>.exe" TestLink /a> 
<a href="file://<path name>/<filename>.exe" TestLink /a> 
<a href="file:/<path name>/<filename>.exe" TestLink /a> 
<a href="file:<path name>/<filename>.exe" TestLink /a> 
<a href="ffile://///<path name>/<filename>.exe" TestLink /a>

as well as ... 1/ substituted the "ffile" with just "file" 2/ all the above variations with the http:// prefixed before the ffile or file.

The best I could see was there is a possibility that if one wanted to open (edit) or save the file, it could be accomplished. However, the exec file would not execute otherwise.

Java TreeMap Comparator

You can not sort TreeMap on values.

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare on keys.

To provide sort on values you will need SortedSet. Use

SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
            new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Map.Entry<String, Double> e1,
                        Map.Entry<String, Double> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });

  sortedset.addAll(myMap.entrySet());

To give you an example

    SortedMap<String, Double> myMap = new TreeMap<String, Double>();
    myMap.put("a", 10.0);
    myMap.put("b", 9.0);
    myMap.put("c", 11.0);
    myMap.put("d", 2.0);
    sortedset.addAll(myMap.entrySet());
    System.out.println(sortedset);

Output:

  [d=2.0, b=9.0, a=10.0, c=11.0]

indexOf method in an object array?

I think you can solve it in one line using the map function:

pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

How to create the most compact mapping n ? isprime(n) up to a limit N?

You could try something like this.

def main():
    try:
        user_in = int(input("Enter a number to determine whether the number is prime or not: "))
    except ValueError:
        print()
        print("You must enter a number!")
        print()
        return
    list_range = list(range(2,user_in+1))
    divisor_list = []
    for number in list_range:
        if user_in%number==0:
            divisor_list.append(number)
    if len(divisor_list) < 2:
        print(user_in, "is a prime number!")
        return
    else:
        print(user_in, "is not a prime number!")
        return
main()

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

How SQL query result insert in temp table?

Look at SELECT INTO. This will create a new table for you, which can be temporary if you want by prefixing the table name with a pound sign (#).

For example, you can do:

SELECT * 
INTO #YourTempTable
FROM YourReportQuery

Simulating Button click in javascript

Or you can use what JQuery alreay made for you:

http://jqueryui.com/datepicker/#icon-trigger

It's what you are trying to achieve isn't it?

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

How to import existing Git repository into another?

If you want to retain the exact commit history of the second repository and therefore also retain the ability to easily merge upstream changes in the future then here is the method you want. It results in unmodified history of the subtree being imported into your repo plus one merge commit to move the merged repository to the subdirectory.

git remote add XXX_remote <path-or-url-to-XXX-repo>
git fetch XXX_remote
git merge -s ours --no-commit --allow-unrelated-histories XXX_remote/master
git read-tree --prefix=ZZZ/ -u XXX_remote/master
git commit -m "Imported XXX as a subtree."

You can track upstream changes like so:

git pull -s subtree XXX_remote master

Git figures out on its own where the roots are before doing the merge, so you don't need to specify the prefix on subsequent merges.

The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a will show you all the changes (if any) except those in the merged history. You can do:

git log --follow -- a

but that won't show the changes other then in the merged history.

In other words, if you don't change ZZZ's files in repository XXX, then you need to specify --follow and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.

Git versions before 2.9: You don’t need to pass the --allow-unrelated-histories option to git merge.

The method in the other answer that uses read-tree and skips the merge -s ours step is effectively no different than copying the files with cp and committing the result.

Original source was from github's "Subtree Merge" help article. And another useful link.

MySQL order by before group by

Try this one. Just get the list of latest post dates from each author. Thats it

SELECT wp_posts.* FROM wp_posts WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post' AND wp_posts.post_date IN(SELECT MAX(wp_posts.post_date) FROM wp_posts GROUP BY wp_posts.post_author) 

Get text from DataGridView selected cells

Or in case you just need the value of the first seleted sell (or just one selected cell if one is selected)

TextBox1.Text = SelectedCells[0].Value.ToString();

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:

 (?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

Append text with .bat

You need to use ECHO. Also, put the quotes around the entire file path if it contains spaces.

One other note, use > to overwrite a file if it exists or create if it does not exist. Use >> to append to an existing file or create if it does not exist.

Overwrite the file with a blank line:

ECHO.>"C:\My folder\Myfile.log"

Append a blank line to a file:

ECHO.>>"C:\My folder\Myfile.log"

Append text to a file:

ECHO Some text>>"C:\My folder\Myfile.log"

Append a variable to a file:

ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"

Storing Objects in HTML5 localStorage

Here some extented version of the code posted by @danott

It'll also implement delete value from localstorage and shows how to adds a Getter and Setter layer so instead of

localstorage.setItem(preview, true)

you can write

config.preview = true

Okay here were go:

var PT=Storage.prototype

if (typeof PT._setItem >='u') PT._setItem = PT.setItem;
PT.setItem = function(key, value)
{
  if (typeof value >='u')//..ndefined
    this.removeItem(key)
  else
    this._setItem(key, JSON.stringify(value));
}

if (typeof PT._getItem >='u') PT._getItem = PT.getItem;
PT.getItem = function(key)
{  
  var ItemData = this._getItem(key)
  try
  {
    return JSON.parse(ItemData);
  }
  catch(e)
  {
    return ItemData;
  }
}

// Aliases for localStorage.set/getItem 
get =   localStorage.getItem.bind(localStorage)
set =   localStorage.setItem.bind(localStorage)

// Create ConfigWrapperObject
var config = {}

// Helper to create getter & setter
function configCreate(PropToAdd){
    Object.defineProperty( config, PropToAdd, {
      get: function ()      { return (  get(PropToAdd)      ) },
      set: function (val)   {           set(PropToAdd,  val ) }
    })
}
//------------------------------

// Usage Part
// Create properties
configCreate('preview')
configCreate('notification')
//...

// Config Data transfer
//set
config.preview = true

//get
config.preview

// delete
config.preview = undefined

Well you may strip the aliases part with .bind(...). However I just put it in since it's really good to know about this. I tooked me hours to find out why a simple get = localStorage.getItem; don't work

@Directive vs @Component in Angular

A @Component requires a view whereas a @Directive does not.

Directives

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

import {Directive} from '@angular/core';

@Directive({
    selector: "[logOnClick]",
    hostListeners: {
        'click': 'onClick()',
    },
})
class LogOnClick {
    constructor() {}
    onClick() { console.log('Element clicked!'); }
}

Which would be used like so:

<button logOnClick>I log when clicked!</button>

Components

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

import {Component, View} from '@angular/core';

@Component({
  selector: 'contact-card',
  template: `
    <div>
      <h1>{{name}}</h1>
      <p>{{city}}</p>
    </div>
  `
})
class ContactCard {
  @Input() name: string
  @Input() city: string
  constructor() {}
}

Which would be used like so:

<contact-card [name]="'foo'" [city]="'bar'"></contact-card>

ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.

In summary

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

Sources:

Regex for parsing directory and filename

A very late answer, but hope this will help

^(.+?)/([\w]+\.log)$

This uses lazy check for /, and I just modified the accepted answer

http://regex101.com/r/gV2xB7/1

If using maven, usually you put log4j.properties under java or resources?

Some "data mining" accounts for that src/main/resources is the typical place.

Results on Google Code Search:

  • src/main/resources/log4j.properties: 4877
  • src/main/java/log4j.properties: 215

Take screenshots in the iOS simulator

Simple answer with sample answer ;-)

on iOS Simulator,

Press Command + control + c or from menu : Edit>Copy Screen

enter image description here

open "Preview" app, Press Command + n or from menu : File> New from clipboard , then you can save Command + s

UnCheck Alpha

enter image description here

You can change Image dimension to your requirement.

enter image description here

Here is the Final Image,For example

enter image description here

MATLAB, Filling in the area between two sets of data, lines in one figure

You want to look at the patch() function, and sneak in points for the start and end of the horizontal line:

x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;

x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);

If you only want the filled in area for a part of the data, you'll need to truncate the x and y vectors to only include the points you need.

Have Excel formulas that return 0, make the result blank

None of the above worked for me today, so I tried putting the 0 in quotes, as shown in the example below.

Example: =IF(INDEX(a,b,c)="0","", INDEX(a,b,c))

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

EC2 Instance Cloning

The easier way is through the web management console:

  1. go to the instance
  2. select the instance and click on instance action
  3. create image

Once you have an image you can launch another cloned instance, data and all. :)

What is the (function() { } )() construct in JavaScript?

(function () {
})();

This is called IIFE (Immediately Invoked Function Expression). One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. As the name suggests it executes immediately after it is created. This pattern creates an isolated or private scope of execution.

JavaScript prior to ECMAScript 6 used lexical scoping, so IIFE was used for simulating block scoping. (With ECMAScript 6 block scoping is possible with the introduction of the let and const keywords.) Reference for issue with lexical scoping

Simulate block scoping with IIFE

The performance benefit of using IIFE’s is the ability to pass commonly used global objects like window, document, etc. as an argument by reducing the scope lookup. (Remember JavaScript looks for properties in local scope and way up the chain until global scope). So accessing global objects in local scope reduces the lookup time like below.

(function (globalObj) {
//Access the globalObj
})(window);

How to save python screen output to a text file

abarnert's answer is very good and pythonic. Another completely different route (not in python) is to let bash do this for you:

$ python myscript.py > myoutput.txt

This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to file for more.

How to check if any Checkbox is checked in Angular

You can do something like:

function ChckbxsCtrl($scope, $filter) {
    $scope.chkbxs = [{
        label: "Led Zeppelin",
        val: false
    }, {
        label: "Electric Light Orchestra",
        val: false
    }, {
        label: "Mark Almond",
        val: false
    }];

    $scope.$watch("chkbxs", function(n, o) {
        var trues = $filter("filter")(n, {
            val: true
        });
        $scope.flag = trues.length;
    }, true);
}

And a template:

<div ng-controller="ChckbxsCtrl">
    <div ng-repeat="chk in chkbxs">
        <input type="checkbox" ng-model="chk.val" />
        <label>{{chk.label}}</label>
    </div>
    <div ng-show="flag">I'm ON when band choosed</div>
</div>

Working: http://jsfiddle.net/cherniv/JBwmA/

UPDATE: Or you can go little bit different way , without using $scope's $watch() method, like:

$scope.bandChoosed = function() {
    var trues = $filter("filter")($scope.chkbxs, {
        val: true
    });
    return trues.length;
}

And in a template do:

<div ng-show="bandChoosed()">I'm ON when band choosed</div>

Fiddle: http://jsfiddle.net/uzs4sgnp/

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

Maybe because other languages do this as well, so it is generally-accepted behavior. (For good reasons, as shown in the other answers)

java.sql.SQLException: Exhausted Resultset

This exception occurs when the ResultSet is used outside of the while loop. Please keep all processing related to the ResultSet inside the While loop.

iPhone 5 CSS media query

All these answers listed above, that use max-device-width or max-device-height for media queries, suffer from very strong bug: they also target a lot of other popular mobile devices (probably unwanted and never tested, or that will hit the market in future).

This queries will work for any device that has a smaller screen, and probably your design will be broken.

Combined with similar device-specific media queries (for HTC, Samsung, IPod, Nexus...) this practice will launch a time-bomb. For debigging, this idea can make your CSS an uncontrolled spagetti. You can never test all possible devices.

Please be aware that the only media query always targeting IPhone5 and nothing else, is:

/* iPhone 5 Retina regardless of IOS version */
@media (device-height : 568px) 
   and (device-width : 320px) 
   and (-webkit-min-device-pixel-ratio: 2)
/* and (orientation : todo: you can add orientation or delete this comment)*/ {
                 /*IPhone 5 only CSS here*/
}

Note that exact width and height, not max-width is checked here.


Now, what is the solution? If you want to write a webpage that will look good on all possible devices, the best practice is to you use degradation

/* degradation pattern we are checking screen width only sure, this will change is turning from portrait to landscape*/

/*css for desktops here*/

@media (max-device-width: 1024px) {
  /*IPad portrait AND netbooks, AND anything with smaller screen*/
  /*make the design flexible if possible */
  /*Structure your code thinking about all devices that go below*/
}
@media (max-device-width: 640px) {
 /*Iphone portrait and smaller*/
}
@media (max-device-width: 540px) {
 /*Smaller and smaller...*/
}
@media (max-device-width: 320px) {
 /*IPhone portrait and smaller. You can probably stop on 320px*/
}

If more than 30% of your website visitors come from mobile, turn this scheme upside-down, providing mobile-first approach. Use min-device-width in that case. This will speed up webpage rendering for mobile browsers.

What is the current directory in a batch file?

From within your batch file:

  • %cd% refers to the current working directory (variable)
  • %~dp0 refers to the full path to the batch file's directory (static)
  • %~dpnx0 and %~f0 both refer to the full path to the batch directory and file name (static).

See also: What does %~dp0 mean, and how does it work?

What is the difference between `git merge` and `git merge --no-ff`?

Other answers indicate perfectly well that --no-ff results in a merge commit. This retains historical information about the feature branch which is useful since feature branches are regularly cleaned up and deleted.

This answer may provide context for when to use or not to use --no-ff.

Merging from feature into the main branch: use --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
$ git commit -am  "New feature complete!"
$ git checkout main
$ git merge --no-ff NewFeature
$ git push origin main
$ git branch -d NewFeature

Merging changes from main into feature branch: leave off --no-ff

Worked example:

$ git checkout -b NewFeature
[work...work...work]
[New changes made for HotFix in the main branch! Lets get them...]
$ git commit -am  "New feature in progress"
$ git pull origin main
[shortcut for "git fetch origin main", "git merge origin main"]

Converting string "true" / "false" to boolean value

You could simply have: var result = (str == "true").