Programs & Examples On #Momentum

How to load a model from an HDF5 file in Keras?

load_weights only sets the weights of your network. You still need to define its architecture before calling load_weights:

def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5)) 
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

Where do I call the BatchNormalization function in Keras?

Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.

Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().

from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, 
validation_split=0.2, verbose = 2)

How is Batch Normalization applied?

Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity

  1. Using a[l-1] and W[l] we can calculate z[l] for the layer l
  2. Usually in feed-forward propagation we will add bias unit to the z[l] at this stage like this z[l]+b[l], but in Batch Normalization this step of addition of b[l] is not required and no b[l] parameter is used.
  3. Calculate z[l] means and subtract it from each element
  4. Divide (z[l] - mean) using standard deviation. Call it Z_temp[l]
  5. Now define new parameters ? and ß that will change the scale of the hidden layer as follows:

    z_norm[l] = ?.Z_temp[l] + ß

In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.

a[l] = tanh(z_norm[l])

Horizontal swipe slider with jQuery and touch devices support?

Ive found another: http://swipejs.com/

seems to work nicely however I encounter an issue with it when paired with bootstrap on the OS X version of Chrome. If total cross-browser compatibility isn't an issue, then you're golden.

Good ways to manage a changelog using git?

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

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

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

The training and validation sets are used during training.

for each epoch
    for each training data instance
        propagate error through the network
        adjust the weights
        calculate the accuracy over training data
    for each validation data instance
        calculate the accuracy over the validation data
    if the threshold validation accuracy is met
        exit training
    else
        continue training

Once you're finished training, then you run against your testing set and verify that the accuracy is sufficient.

Training Set: this data set is used to adjust the weights on the neural network.

Validation Set: this data set is used to minimize overfitting. You're not adjusting the weights of the network with this data set, you're just verifying that any increase in accuracy over the training data set actually yields an increase in accuracy over a data set that has not been shown to the network before, or at least the network hasn't trained on it (i.e. validation data set). If the accuracy over the training data set increases, but the accuracy over the validation data set stays the same or decreases, then you're overfitting your neural network and you should stop training.

Testing Set: this data set is used only for testing the final solution in order to confirm the actual predictive power of the network.

jQuery SVG vs. Raphael

As a Javascript beginner, I found Rapahel samples not so easy, I recommend http://cancerbero.mbarreneche.com/raphaeltut, which is a real Step by step tutorial.

Ball to Ball Collision - Detection and Handling

I found an excellent page with information on collision detection and response in 2D.

http://www.metanetsoftware.com/technique.html (web.archive.org)

They try to explain how it's done from an academic point of view. They start with the simple object-to-object collision detection, and move on to collision response and how to scale it up.

Edit: Updated link

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

It's not a big deal, it's pretty easy to switch between them. MSTest being integrated isn't a big deal either, just grab testdriven.net.

Like the previous person said pick a mocking framework, my favourite at the moment is Moq.

Is there a good Valgrind substitute for Windows?

Try Intel's Inspector XE product which can help you detect both memory and threading issues: http://software.intel.com/en-us/articles/intel-inspector-xe/

KeyListener, keyPressed versus keyTyped

private String message;
private ScreenManager s;


//Here is an example of code to add the keyListener() as suggested; modify 
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);

public void keyPressed(KeyEvent e){
    int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_F5)
            message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

How to get CRON to call in the correct PATHs

The simplest workaround I've found looks like this:

* * * * * root su -l -c command

This example invokes su as root user and starts the shell with the user's full environment, including $PATH, set as if they were logged in. It works the same on different distros, is more reliable than sourcing .bashrc (which hasn't worked for me) and avoids hardcoding specific paths which can be a problem if you're providing an example or setup tool and don't know what distro or file layout on the user's system.

You can also specify the username after su if you want a different user than root, but you should probably leave the root parameter before su command since this ensures su has sufficient privileges to switch to any user you specify.

jQuery: Test if checkbox is NOT checked

try this one

if ($("#checkSurfaceEnvironment-1:checked").length>0) {
    //your code in case of NOT checked
}

In Above code selecting the element by Id (#checkSurfaceEnvironment-1) then filter out it's checked state by (:checked) filter.

It will return array of checked element object. If there any object exists in the array then if condition will be satisfied.

How can I count the occurrences of a string within a file?

This will output the number of lines that contain your search string.

grep -c "echo" FILE

This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).

edit:

After playing around a bit, you could get the number of occurrences using this dirty little bit of code:

sed 's/echo/echo\n/g' FILE | grep -c "echo"

This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.

What is a method group in C#?

Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup).

So, for example, I have:

private string DoSomethingToMyString(string input)
{
    // blah
}

Instead of explicitly stating the variable to be used like this:

public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}

I can just omit the name of the var:

public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}

How can I calculate the number of lines changed between two commits in Git?

git diff --shortstat

gives you just the number of lines changed and added. This only works with unstaged changes. To compare against a branch:

git diff --shortstat some-branch

Replacing from match to end-of-line

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

Remove the last three characters from a string

Easy. text = text.remove(text.length - 3). I subtracted 3 because the Remove function removes all items from that index to the end of the string which is text.length. So if I subtract 3 then I get the string with 3 characters removed from it.

You can generalize this to removing a characters from the end of the string, like this:

text = text.remove(text.length - a) 

So what I did was the same logic. The remove function removes all items from its inside to the end of the string which is the length of the text. So if I subtract a from the length of the string that will give me the string with a characters removed.

So it doesn't just work for 3, it works for all positive integers, except if the length of the string is less than or equal to a, in that case it will return a negative number or 0.

How to create a GUID in Excel?

This is not a problem with the function at all.

It took me a bit of digging, but the problem is in copying and pasting. Try copying this: RANDBETWEEN(0,6553??5) string, posted in your original question, and paste it into a Hex Editor, then you'll see that there are actually two null characters in the 65535:

00000000  52 41 4E 44 42 45 54 57 45 45 4E 28 30 2C 36 35  RANDBETWEEN(0,65
00000010  35 33 00 00 35 29                                53?..?5)

How to add constraints programmatically using Swift

This is one way to adding constraints programmatically

override func viewDidLoad() {
            super.viewDidLoad()


let myLabel = UILabel()
        myLabel.labelFrameUpdate(label: myLabel, text: "Welcome User", font: UIFont(name: "times new roman", size: 40)!, textColor: UIColor.red, textAlignment: .center, numberOfLines: 0, borderWidth: 2.0, BorderColor: UIColor.red.cgColor)
        self.view.addSubview(myLabel)


         let myLabelhorizontalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let myLabelverticalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        let mylabelLeading = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 10)
        let mylabelTrailing = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -10)
        let myLabelheightConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
        NSLayoutConstraint.activate(\[myLabelhorizontalConstraint, myLabelverticalConstraint, myLabelheightConstraint,mylabelLeading,mylabelTrailing\])
}

extension UILabel
{
    func labelFrameUpdate(label:UILabel,text:String = "This is sample Label",font:UIFont = UIFont(name: "times new roman", size: 20)!,textColor:UIColor = UIColor.red,textAlignment:NSTextAlignment = .center,numberOfLines:Int = 0,borderWidth:CGFloat = 2.0,BorderColor:CGColor = UIColor.red.cgColor){
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = text
        label.font = font
        label.textColor = textColor
        label.textAlignment = textAlignment
        label.numberOfLines = numberOfLines
        label.layer.borderWidth = borderWidth
        label.layer.borderColor = UIColor.red.cgColor
    }
}

enter image description here

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

AngularJS format JSON string output

In addition to the angular json filter already mentioned, there is also the angular toJson() function.

angular.toJson(obj, pretty);

The second param of this function lets you switch on pretty printing and set the number of spaces to use.

If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

Difference between left join and right join in SQL Server

Select * from Table1 left join Table2 ...

and

Select * from Table2 right join Table1 ...

are indeed completely interchangeable. Try however Table2 left join Table1 (or its identical pair, Table1 right join Table2) to see a difference. This query should give you more rows, since Table2 contains a row with an id which is not present in Table1.

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Excel: Use a cell value as a parameter for a SQL query

The SQL is somewhat like the syntax of MS SQL.

SELECT * FROM [table$] WHERE *;

It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.

If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:

SELECT Name FROM [Users$] WHERE id = 1;

Hope this helps.

Reading binary file and looping over each byte

if you are looking for something speedy, here's a method I've been using that's worked for years:

from array import array

with open( path, 'rb' ) as file:
    data = array( 'B', file.read() ) # buffer the file

# evaluate it's data
for byte in data:
    v = byte # int value
    c = chr(byte)

if you want to iterate chars instead of ints, you can simply use data = file.read(), which should be a bytes() object in py3.

setting y-axis limit in matplotlib

Just for fine tuning. If you want to set only one of the boundaries of the axis and let the other boundary unchanged, you can choose one or more of the following statements

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

Take a look at the documentation for xlim and for ylim

How to resize datagridview control when form resizes

For me, anchoring works only if I set it to all four sides:

Anchoring: Top, Bottom, Left, Right

Setting anchoring just to Left, Bottom moves the whole object when the form is resized in bottom, left side. Setting all four sizes really resizes the object, when parent is resized.

Apply formula to the entire column

I think you are in luck. Please try entering in B1:

=text(A1:A,"00000")

(very similar!) but before hitting Enter hit Ctrl+Shift+Enter.

CSS Circular Cropping of Rectangle Image

The approach is wrong, you need to apply the border-radius to the container div instead of the actual image.

This would work:

_x000D_
_x000D_
.image-cropper {
  width: 100px;
  height: 100px;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
}

img {
  display: inline;
  margin: 0 auto;
  height: 100%;
  width: auto;
}
_x000D_
<div class="image-cropper">
  <img src="https://via.placeholder.com/150" class="rounded" />
</div>
_x000D_
_x000D_
_x000D_

Maven Run Project

1. Edit POM.xml

Add the following property in pom.xml. Make sure you use the fully qualified class name (i.e. with package name) which contains the main method:

<properties>
        <exec.mainClass>fully-qualified-class-name</exec.mainClass>
</properties>

2. Run Command

Now from the terminal, trigger the following command:

mvn clean compile exec:java

NOTE You can pass further arguments via -Dexec.args="xxx" flag.

Test if a property is available on a dynamic variable

I thought I'd do a comparison of Martijn's answer and svick's answer...

The following program returns the following results:

Testing with exception: 2430985 ticks
Testing with reflection: 155570 ticks

void Main()
{
    var random = new Random(Environment.TickCount);

    dynamic test = new Test();

    var sw = new Stopwatch();

    sw.Start();

    for (int i = 0; i < 100000; i++)
    {
        TestWithException(test, FlipCoin(random));
    }

    sw.Stop();

    Console.WriteLine("Testing with exception: " + sw.ElapsedTicks.ToString() + " ticks");

    sw.Restart();

    for (int i = 0; i < 100000; i++)
    {
        TestWithReflection(test, FlipCoin(random));
    }

    sw.Stop();

    Console.WriteLine("Testing with reflection: " + sw.ElapsedTicks.ToString() + " ticks");
}

class Test
{
    public bool Exists { get { return true; } }
}

bool FlipCoin(Random random)
{
    return random.Next(2) == 0;
}

bool TestWithException(dynamic d, bool useExisting)
{
    try
    {
        bool result = useExisting ? d.Exists : d.DoesntExist;
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

bool TestWithReflection(dynamic d, bool useExisting)
{
    Type type = d.GetType();

    return type.GetProperties().Any(p => p.Name.Equals(useExisting ? "Exists" : "DoesntExist"));
}

As a result I'd suggest using reflection. See below.


Responding to bland's comment:

Ratios are reflection:exception ticks for 100000 iterations:

Fails 1/1: - 1:43 ticks
Fails 1/2: - 1:22 ticks
Fails 1/3: - 1:14 ticks
Fails 1/5: - 1:9 ticks
Fails 1/7: - 1:7 ticks
Fails 1/13: - 1:4 ticks
Fails 1/17: - 1:3 ticks
Fails 1/23: - 1:2 ticks
...
Fails 1/43: - 1:2 ticks
Fails 1/47: - 1:1 ticks

...fair enough - if you expect it to fail with a probability with less than ~1/47, then go for exception.


The above assumes that you're running GetProperties() each time. You may be able to speed up the process by caching the result of GetProperties() for each type in a dictionary or similar. This may help if you're checking against the same set of types over and again.

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

How to handle notification when app in background in Firebase

Simple summary like this

  • if your app is running;

    onMessageReceived()
    

is triggers.

  • if your app is not running (killed by swiping) ;

    onMessageReceived()
    

is not triggered and delivered by direclty. If you have any specialy key-value pair. They don' t work beacuse of onMessageReceived() not working.

I' ve found this way;

In your launcher activity, put this logic,

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState, R.layout.activity_splash);

    if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("PACKAGE_NAME")) {

        // do what you want

        // and this for killing app if we dont want to start
        android.os.Process.killProcess(android.os.Process.myPid());

    } else {

        //continue to app
    }
}

in this if block, search for your keys according to firebase UI.

In this example my key and value like above; (sorry for language =)) enter image description here

When my code works, i get "com.rda.note".

android.os.Process.killProcess(android.os.Process.myPid());

with this line of code, i closed my application and open Google Play Market

happy coding =)

HTML: how to force links to open in a new tab, not new window

In Internet Explorer, click the Tools -> Internet Options. Click General tab -> Tabs -> Settings. Choose "When a pop-up is encountered"-> Always open pop up in new tab option. Click OK.

Creating watermark using html and css

#watermark
{
 position:fixed;
 bottom:5px;
 right:5px;
 opacity:0.5;
 z-index:99;
 color:white;
}

jSFiddle

What's the difference between TRUNCATE and DELETE in SQL

It is not that truncate does not log anything in SQL Server. truncate does not log any information but it log the deallocation of data page for the table on which you fired TRUNCATE.

and truncated record can be rollback if we define transaction at beginning and we can recover the truncated record after rollback it. But can not recover truncated records from the transaction log backup after committed truncated transaction.

Python, how to read bytes from file and save it?

In my examples I use the 'b' flag ('wb', 'rb') when opening the files because you said you wanted to read bytes. The 'b' flag tells Python not to interpret end-of-line characters which can differ between operating systems. If you are reading text, then omit the 'b' and use 'w' and 'r' respectively.

This reads the entire file in one chunk using the "simplest" Python code. The problem with this approach is that you could run out memory when reading a large file:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()

This example is refined to read 1MB chunks to ensure it works for files of any size without running out of memory:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
    ofile.write(data)
    data = ifile.read(1024*1024)
ofile.close()
ifile.close()

This example is the same as above but leverages using with to create a context. The advantage of this approach is that the file is automatically closed when exiting the context:

with open(input_filename,'rb') as ifile:
    with open(output_filename, 'wb') as ofile:
        data = ifile.read(1024*1024)
        while data:
            ofile.write(data)
            data = ifile.read(1024*1024)

See the following:

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

Pass your date in the date object:

var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');

Pandas DataFrame column to list

The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values the output is an numpy array. So if the data has int and float in it then output will either have int or float and the columns will loose their original dtype. Consider df

a  b 
0  1  4
1  2  5 
2  3  6 

a    float64
b    int64 

So if you want to keep original dtype, you can do something like

row_list = df.to_csv(None, header=False, index=False).split('\n')

this will return each row as a string.

['1.0,4', '2.0,5', '3.0,6', '']

Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.

def f(row_str): 
  row_list = row_str.split(',')
  return [float(row_list[0]), int(row_list[1])]

df_list_of_list = map(f, row_list[:-1])

[[1.0, 4], [2.0, 5], [3.0, 6]]

What are some reasons for jquery .focus() not working?

The problem is there is a JavaScript .focus and a jQuery .focus function. This call to .focus is ambiguous. So it doesn't always work. What I do is cast my jQuery object to a JavaScript object and use the JavaScript .focus. This works for me:

$("#goal-input")[0].focus();

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

When to use in vs ref vs out

Below are some notes which i pulled from this codeproject article on C# Out Vs Ref

  1. It should be used only when we are expecting multiple outputs from a function or a method. A thought on structures can be also a good option for the same.
  2. REF and OUT are keywords which dictate how data is passed from caller to callee and vice versa.
  3. In REF data passes two way. From caller to callee and vice-versa.
  4. In Out data passes only one way from callee to caller. In this case if Caller tried to send data to the callee it will be overlooked / rejected.

If you are a visual person then please see this yourtube video which demonstrates the difference practically https://www.youtube.com/watch?v=lYdcY5zulXA

Below image shows the differences more visually

C# Out Vs Ref

How to detect the end of loading of UITableView

The best approach that I know is Eric's answer at: Get notified when UITableView has finished asking for data?

Update: To make it work I have to put these calls in -tableView:cellForRowAtIndexPath:

[tableView beginUpdates];
[tableView endUpdates];

SQL update statement in C#

I dont want to use like this

That is the syntax for Update statement in SQL, you have to use that syntax otherwise you will get the exception.

command.Text = "UPDATE Student SET Address = @add, City = @cit Where FirstName = @fn AND LastName = @ln";

and then add your parameters accordingly.

command.Parameters.AddWithValue("@ln", lastName);
command.Parameters.AddWithValue("@fn", firstName);
command.Parameters.AddWithValue("@add", address);
command.Parameters.AddWithValue("@cit", city);  

How to get Top 5 records in SqLite?

select * from [Table_Name] limit 5

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I had this problem in a unit test which opened a lot of connections to the DB via a connection pool and then "stopped" the connection pool (ManagedDataSource actually) to release the connections at the end of the each test. I always ran out of connections at some point in the suite of tests.

Added a Thread.sleep(500) in the teardown() of my tests and this resolved the issue. I think that what was happening was that the connection pool stop() releases the active connections in another thread so that if the main thread keeps running tests the cleanup thread(s) got so far behind that the Oracle server ran out of connections. Adding the sleep allows the background threads to release the pooled connections.

This is much less of an issue in the real world because the DB servers are much bigger and there is a healthy mix of operations (not just endless DB connect/disconnect operations).

How to make VS Code to treat other file extensions as certain language?

This works for me.

enter image description here

{
"files.associations": {"*.bitesize": "yaml"}
 }

Postgresql -bash: psql: command not found

If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.

bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

...then run bundle again.

Note: check the version first using the following.

ls /Applications/Postgres.app/Contents/Versions/

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.

Why doesn't margin:auto center an image?

Because your image is an inline-block element. You could change it to a block-level element like this:

<img src="queuedError.jpg" style="margin:auto; width:200px;display:block" />

and it will be centered.

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...

Find duplicate records in a table using SQL Server

First of all, I doubt that the result it not accurate? Seem like there are Three 'Sam' from the original table. But it is not critical to the question.

Then here we come for the question itself. Based on your table, the best way to show duplicate value is to use count(*) and Group by clause. The query would look like this

SELECT OrderNo, shoppername, amountPayed, city, item, count(*) as RepeatTimes FROM dbo.sales GROUP BY OrderNo, shoppername, amountPayed, city, item HAVING COUNT(*) > 1

The reason is that all columns together from your table uniquely identified each record, which means the records will be considered as duplicate only when all values from each column are exactly the same, also you want to show all fields for duplicate records, so the group by will not miss any column, otherwise yes because you can only select columns that participate in the 'group by' clause.

Now I would like to give you any example for With...Row_Number()Over(...), which is using table expression together with Row_Number function.

Suppose you have a nearly same table but with one extra column called Shipping Date, and the value may change even the rest are the same. Here it is:

OrderNo shoppername amountpayed city Item Shipping Date
1 Sam 10 A Iphone 2016-01-01 1 Sam 10 A Iphone 2016-02-02 1 Sam 5 A Ipod 2016-03-03 2 John 20 B Macbook 2016-04-04 3 John 25 B Macbookair 2016-05-05 4 Jack 5 A Ipod 2016-06-06

Notice that row# 2 is not a duplicate one if you still take all columns as a unit. But what if you want to treat them as duplicate as well in this case? You should use With...Row_Number()Over(...), and the query would look like this:

WITH TABLEEXPRESSION AS (SELECT *,ROW_NUMBER() OVER (PARTITION BY OrderNo, shoppername, amountPayed, city, item ORDER BY [Shipping Date] as Identifier) --if you consider the one with late shipping date as the duplicate FROM dbo.sales) SELECT * FROM TABLEEXPRESSION WHERE Identifier !=1 --or use '>1'

The above query will give result together with Shipping Date, for example:

OrderNo shoppername amountpayed city Item Shipping Date Identifier 1 Sam 10 A Iphone 2016-02-02 2

Note this one is different from the one with 2016-01-01, and the reason why 2016-02-02 has been filtered out is PARTITION BY OrderNo, shoppername, amountPayed, city, item ORDER BY [Shipping Date] as Identifier, and Shipping Date is NOT one of the column that need to be took care of for duplicate records, which means the one with 2016-02-02 still could be a perfect result for your question.

Now summarize it little bit, using count(*) and Group by clause together is the best choice when you only want to show all columns from Group byclause as the result, otherwise you will miss the columns that do not participate in group by.

While For With...Row_Number()Over(...), it is suitable in every scenario that you want to find duplicate records, however, it is little bit complicated to write the query and little bit over engineered compared to the former one.

If your purpose is to delete duplicate records from table, you have to use the later WITH...ROW_NUMBER()OVER(...)...DELETE FROM...WHERE one.

Hope this helps!

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

Unable to process Jar entry [module-info.class] from Jar [jar:file:/xxxxxxxx/lombok-1.18.4.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19

1.update and append below argument in <root or instance tomcat folder>/conf/catalina.properties

org.apache.catalina.startup.ContextConfig.jarsToSkip=...,lombok-1.18.4.jar

2.clean and deploy the to-be-pulish project.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

How to get a List<string> collection of values from app.config in WPF?

In App.config:

<add key="YOURKEY" value="a,b,c"/>

In C#:

string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);

C# declare empty string array

If you must create an empty array you can do this:

string[] arr = new string[0];

If you don't know about the size then You may also use List<string> as well like

var valStrings = new List<string>();

// do stuff...

string[] arrStrings = valStrings.ToArray();

How to update Android Studio automatically?

I am having a similar problem while updating from 2.3.2 to 2.3.3.

Go to the bin folder of your Android Studio installation folder: e.g.

cd opt/android-studio/bin

Provide run permission for studio.sh file: chmod +x studio.sh

Run Android Studio from here: ./studio.sh

and try "update and restart" from android studio.

Private class declaration

You can.

package test;

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

class B {
  // Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}

Multiple controllers with AngularJS in single page app

We can simply declare more than one Controller in the same module. Here's an example:

  <!DOCTYPE html>
    <html>

    <head>
       <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
       </script>
      <title> New Page </title>


    </head> 
    <body ng-app="mainApp"> <!-- if we remove ng-app the add book button [show/hide] will has no effect --> 
      <h2> Books </h2>

    <!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
    <input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
             Enter book name: <input type = "text" ng-model = "book.name"><br>
             Enter book category: <input type = "text" ng-model = "book.category"><br>
             Enter book price: <input type = "text" ng-model = "book.price"><br>
             Enter book author: <input type = "text" ng-model = "book.author"><br>


             You are entering book: {{book.bookDetails()}}
     </div>

    <script>
             var mainApp = angular.module("mainApp", []);

             mainApp.controller('bookController', function($scope) {
                $scope.book = {
                   name: "",
                   category: "",
                   price:"",
                   author: "",


                   bookDetails: function() {
                      var bookObject;
                      bookObject = $scope.book;
                      return "Book name: " + bookObject.name +  '\n' + "Book category: " + bookObject.category + "  \n" + "Book price: " + bookObject.price + "  \n" + "Book Author: " + bookObject.author;
                   }

                };
             });
    </script>

    <h2> Albums </h2>
    <input type = "button" value = "Add Album"ng-click="hideShow2=(hideShow2 ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "albumController" ng-if="hideShow2">
             Enter Album name: <input type = "text" ng-model = "album.name"><br>
             Enter Album category: <input type = "text" ng-model = "album.category"><br>
             Enter Album price: <input type = "text" ng-model = "album.price"><br>
             Enter Album singer: <input type = "text" ng-model = "album.singer"><br>


             You are entering Album: {{album.albumDetails()}}
     </div>

    <script>
             //no need to declare this again ;)
             //var mainApp = angular.module("mainApp", []);

             mainApp.controller('albumController', function($scope) {
                $scope.album = {
                   name: "",
                   category: "",
                   price:"",
                   singer: "",

                   albumDetails: function() {
                      var albumObject;
                      albumObject = $scope.album;
                      return "Album name: " + albumObject.name +  '\n' + "album category: " + albumObject.category + "\n" + "Book price: " + albumObject.price + "\n" + "Album Singer: " + albumObject.singer;
                   }
                };
             });
    </script>

    </body>
    </html>

can we use xpath with BeautifulSoup?

As others have said, BeautifulSoup doesn't have xpath support. There are probably a number of ways to get something from an xpath, including using Selenium. However, here's a solution that works in either Python 2 or 3:

from lxml import html
import requests

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)
#This will create a list of buyers:
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')

print('Buyers: ', buyers)
print('Prices: ', prices)

I used this as a reference.

Where does PostgreSQL store the database?

On Mac: /Library/PostgreSQL/9.0/data/base

The directory can't be entered, but you can look at the content via: sudo du -hc data

mysql datatype for telephone number and address

Consider normalizing to E.164 format. For full international support, you'd need a VARCHAR of 15 digits.

See Twilio's recommendation for more information on localization of phone numbers.

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

How to adjust the size of y axis labels only in R?

ucfagls is right, providing you use the plot() command. If not, please give us more detail.

In any case, you can control every axis seperately by using the axis() command and the xaxt/yaxt options in plot(). Using the data of ucfagls, this becomes :

plot(Y ~ X, data=foo,yaxt="n")
axis(2,cex.axis=2)

the option yaxt="n" is necessary to avoid that the plot command plots the y-axis without changing. For the x-axis, this works exactly the same :

plot(Y ~ X, data=foo,xaxt="n")
axis(1,cex.axis=2)

See also the help files ?par and ?axis


Edit : as it is for a barplot, look at the options cex.axis and cex.names :

tN <- table(sample(letters[1:5],100,replace=T,p=c(0.2,0.1,0.3,0.2,0.2)))

op <- par(mfrow=c(1,2))
barplot(tN, col=rainbow(5),cex.axis=0.5) # for the Y-axis
barplot(tN, col=rainbow(5),cex.names=0.5) # for the X-axis
par(op)

alt text

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

In addition to what the other answers have said, note that the '/' character in "dd/MM/yyyy" is not a literal character: it represents the date separator of the current user's culture. Therefore, if the current culture uses yyyy-MM-dd dates, then when you call toString it will give you a date such as "31-12-2016" (using dashes instead of slashes). To force it to use slashes, you need to escape that character:

DateTime.Now.ToString("dd/MM/yyyy")     --> "19-12-2016" for a Japanese user
DateTime.Now.ToString("dd/MM/yyyy")     --> "19/12/2016" for a UK user
DateTime.Now.ToString("dd\\/MM\\/yyyy") --> "19/12/2016" independent of region

How can I generate an MD5 hash?

The MessageDigest class can provide you with an instance of the MD5 digest.

When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes() it will use the platform default. (Not all platforms use the same defaults)

import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);

If you have a lot of data take a look at the .update(byte[]) method which can be called repeatedly. Then call .digest() to obtain the resulting hash.

Making a mocked method return an argument that was passed to it

I had a very similar problem. The goal was to mock a service that persists Objects and can return them by their name. The service looks like this:

public class RoomService {
    public Room findByName(String roomName) {...}
    public void persist(Room room) {...}
}

The service mock uses a map to store the Room instances.

RoomService roomService = mock(RoomService.class);
final Map<String, Room> roomMap = new HashMap<String, Room>();

// mock for method persist
doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            Room room = (Room) arguments[0];
            roomMap.put(room.getName(), room);
        }
        return null;
    }
}).when(roomService).persist(any(Room.class));

// mock for method findByName
when(roomService.findByName(anyString())).thenAnswer(new Answer<Room>() {
    @Override
    public Room answer(InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0 && arguments[0] != null) {
            String key = (String) arguments[0];
            if (roomMap.containsKey(key)) {
                return roomMap.get(key);
            }
        }
        return null;
    }
});

We can now run our tests on this mock. For example:

String name = "room";
Room room = new Room(name);
roomService.persist(room);
assertThat(roomService.findByName(name), equalTo(room));
assertNull(roomService.findByName("none"));

List and kill at jobs on UNIX

at -l to list jobs, which gives return like this:

age2%> at -l
11      2014-10-21 10:11 a hoppent
10      2014-10-19 13:28 a hoppent

atrm 10 kills job 10

Or so my sysadmin told me, and it

Is there a destructor for Java?

The finalize() function is the destructor.

However, it should not be normally used because it is invoked after the GC and you can't tell when that will happen (if ever).

Moreover, it takes more than one GC to deallocate objects that have finalize().

You should try to clean up in the logical places in your code using the try{...} finally{...} statements!

How to find sitemap.xml path on websites?

According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:

  • Informing each search engine of the location through their provided interface
  • Adding url to the robots.txt file
  • Submiting url to search engines through http

So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.

Getting a directory name from a filename

Just use this: ExtractFilePath(your_path_file_name)

how to use php DateTime() function in Laravel 5

If you just want to get the current UNIX timestamp I'd just use time()

$timestamp = time(); 

Euclidean distance of two vectors

try using this:

sqrt(sum((x1-x2)^2))

EditText onClickListener in Android

As Dillon Kearns suggested, setting focusable to false works fine. But if your goal is to cancel the keyboard when EditText is clicked, you might want to use:

mEditText.setInputType(0);

How can I display a messagebox in ASP.NET?

This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!

protected void Addstaff_Click(object sender, EventArgs e)    
    {   
 if (intClassCapcity < intCurrentstaffNumber)     
                {                  
            MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");    
        }    
else    
    {   
            sqlClassList.Insert();    
    }    
}

private void MsgBox(string sMessage)    
    {    
        string msg = "<script language=\"javascript\">";    
        msg += "alert('" + sMessage + "');";    
        msg += "</script>";    
        Response.Write(msg);    
    }

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

how to add value to a tuple?

In Python, you can't. Tuples are immutable.

On the containing list, you could replace tuple ('1', '2', '3', '4') with a different ('1', '2', '3', '4', '1234') tuple though.

Configuring Git over SSH to login once

Try ssh-add, you need ssh-agent to be running and holding your private key

(Ok, responding to the updated question, you first run ssh-keygen to generate a public and private key as Jefromi explained. You put the public key on the server. You should use a passphrase, if you don't you have the equivalent of a plain-text password in your private key. But when you do, then you need as a practical matter ssh-agent as explained below.)

You want to be running ssh-agent in the background as you log in. Once you log in, the idea is to run ssh-add once and only once, in order to give the agent your passphrase, to decode your key. The agent then just sits in memory with your key unlocked and loaded, ready to use every time you ssh somewhere.

All ssh-family commands1 will then consult the agent and automatically be able to use your private key.

On OSX (err, macOS), GNOME and KDE systems, ssh-agent is usually launched automatically for you. I will go through the details in case, like me, you also have a Cygwin or other windows environment where this most certainly is not done for you.

Start here: man ssh-agent.

There are various ways to automatically run the agent. As the man page explains, you can run it so that it is a parent of all your login session's other processes. That way, the environment variables it provides will automatically be in all your shells. When you (later) invoke ssh-add or ssh both will have access to the agent because they all have the environment variables with magic socket pathnames or whatever.

Alternatively, you can run the agent as an ordinary child, save the environment settings in a file, and source that file in every shell when it starts.

My OSX and Ubuntu systems automatically do the agent launch setup, so all I have to do is run ssh-add once. Try running ssh-add and see if it works, if so, then you just need to do that once per reboot.

My Cygwin system needed it done manually, so I did this in my .profile and I have .bashrc source .profile:

. .agent > /dev/null
ps -p $SSH_AGENT_PID | grep ssh-agent > /dev/null || {
        ssh-agent > .agent
        . .agent > /dev/null
}

The .agent file is created automatically by the script; it contains the environment variables definitions and exports. The above tries to source the .agent file, and then tries to ps(1) the agent. If it doesn't work it starts an agent and creates a new agent file. You can also just run ssh-add and if it fails start an agent.


1. And even local and remote sudo with the right pam extension.

Can someone explain how to append an element to an array in C programming?

You can have a counter (freePosition), which will track the next free place in an array of size n.

Stateless vs Stateful

Stateless means there is no memory of the past. Every transaction is performed as if it were being done for the very first time.

Stateful means that there is memory of the past. Previous transactions are remembered and may affect the current transaction.

Stateless:

// The state is derived by what is passed into the function

function int addOne(int number)
{
    return number + 1;
}

Stateful:

// The state is maintained by the function

private int _number = 0; //initially zero

function int addOne()
{
   _number++;
   return _number;
}

Refer from: https://softwareengineering.stackexchange.com/questions/101337/whats-the-difference-between-stateful-and-stateless

Getting only response header from HTTP POST using curl

The other answers require the response body to be downloaded. But there's a way to make a POST request that will only fetch the header:

curl -s -I -X POST http://www.google.com

An -I by itself performs a HEAD request which can be overridden by -X POST to perform a POST (or any other) request and still only get the header data.

How to upload a file to directory in S3 bucket using boto

Try this...

import boto
import boto.s3
import sys
from boto.s3.key import Key

AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''

bucket_name = AWS_ACCESS_KEY_ID.lower() + '-dump'
conn = boto.connect_s3(AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY)


bucket = conn.create_bucket(bucket_name,
    location=boto.s3.connection.Location.DEFAULT)

testfile = "replace this with an actual filename"
print 'Uploading %s to Amazon S3 bucket %s' % \
   (testfile, bucket_name)

def percent_cb(complete, total):
    sys.stdout.write('.')
    sys.stdout.flush()


k = Key(bucket)
k.key = 'my test file'
k.set_contents_from_filename(testfile,
    cb=percent_cb, num_cb=10)

[UPDATE] I am not a pythonist, so thanks for the heads up about the import statements. Also, I'd not recommend placing credentials inside your own source code. If you are running this inside AWS use IAM Credentials with Instance Profiles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html), and to keep the same behaviour in your Dev/Test environment, use something like Hologram from AdRoll (https://github.com/AdRoll/hologram)

Clear contents of cells in VBA using column reference

As Gary's Student mentioned, you would need to remove the dot before Cells to make the code work as you originally wrote it. I can't be sure, since you only included the one line of code, but the error you got when you deleted the dots might have something to do with how you defined your variables.

I ran your line of code with the variables defined as integers and it worked:

Sub TestClearLastColumn()

    Dim LastColData As Long
        Set LastColData = Range("A1").End(xlToRight).Column

    Dim LastRowData As Long
        Set LastRowData = Range("A1").End(xlDown).Row

    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents

End Sub

I don't think a With statement is appropriate to the line of code you shared, but if you were to use one, the With would be at the start of the line that defines the object you are manipulating. Here is your code rewritten using an unnecessary With statement:

With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
    .ClearContents
End With

With statements are designed to save you from retyping code and to make your coding easier to read. It becomes useful and appropriate if you do more than one thing with an object. For example, if you wanted to also turn the column red and add a thick black border, you might use a With statement like this:

With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
    .ClearContents
    .Interior.Color = vbRed
    .BorderAround Color:=vbBlack, Weight:=xlThick
End With

Otherwise you would have to declare the range for each action or property, like this:

    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).Interior.Color = vbRed
    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).BorderAround Color:=vbBlack, Weight:=xlThick

I hope this gives you a sense for why Gary's Student believed the compiler might be expecting a With (even though it was inappropriate) and how and when a With can be useful in your code.

Convert Current date to integer

Do you need something like this(without time)?

public static Integer toJulianDate(Date pDate) {
if (pDate == null) {
  return null;
}
Calendar lCal = Calendar.getInstance();
lCal.setTime(pDate);
int lYear = lCal.get(Calendar.YEAR);
int lMonth = lCal.get(Calendar.MONTH) + 1;
int lDay = lCal.get(Calendar.DATE);
int a = (14 - lMonth) / 12;
int y = lYear + 4800 - a;
int m = lMonth + 12 * a - 3;
return lDay + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;
}

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

_x000D_
_x000D_
// Example using a function expression
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: function() {
      console.log('Inside `bar`:', this.foo);
    },
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Example using a arrow function
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.

This makes arrow functions useful if you need to access the this of the current environment:

// currently common pattern
var that = this;
getData(function(data) {
  that.data = data;
});

// better alternative with arrow functions
getData(data => {
  this.data = data;
});

Note that this also means that is not possible to set an arrow function's this with .bind or .call.

If you are not very familiar with this, consider reading

2. Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).

Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.

If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.


Knowing this, we can state the following.

Replaceable:

  • Functions that don't use this or arguments.
  • Functions that are used with .bind(this)

Not replaceable:

  • Constructor functions
  • Function / methods added to a prototype (because they usually use this)
  • Variadic functions (if they use arguments (see below))

Lets have a closer look at this using your examples:

Constructor function

This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.

Prototype methods

Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:

class User {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
}

Object methods

Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:

const obj = {
  getName() {
    // ...
  },
};

Callbacks

It depends. You should definitely replace it if you are aliasing the outer this or are using .bind(this):

// old
setTimeout(function() {
  // ...
}.bind(this), 500);

// new
setTimeout(() => {
  // ...
}, 500);

But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!

Variadic functions

Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.

// old
function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// new
const sum = (...args) => {
  // ...
};

Related question:

Further resources:

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Add "-O file.tgz" or "-O file.tar.gz" at the end wget command and extract "file.tgz" or "file.tar.gz"

Here is the sample code for google colab-

!wget -q  --trust-server-names  https://downloads.apache.org/spark/spark-3.0.0/spark-3.0.0-bin-hadoop2.7.tgz  -O file.tgz 
print("Download completed successfully !!!")
!tar zxvf  file.tgz 

Note- Please ensure that http path for tgz is valid and file is not corrupted

X-Frame-Options: ALLOW-FROM in firefox and chrome

ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options

You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I had the same problem with one of my apps, which is how I ended up finding this. In my case, I uploaded two of my apps at the same time, using Xcode 7.1. One of the apps passed through processing within an hour. The other one was still in processing almost 24 hours later. To get past this issue, I created a new archive with an incremented build number, and uploaded it using the application loader. I did not turn off bitcode. The version that I uploaded using the application loader took less than 20 minutes to get through processing, and I've been able to submit my app for review. The version I submitted prior to this is still stuck in processing.

At least in the case of my app, using application loader appears to have solved the issue.

Hibernate Group by Criteria Object

Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.

For example :

SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name

Its equivalent criteria object is :

List result = session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).list();

hash function for string

There are a number of existing hashtable implementations for C, from the C standard library hcreate/hdestroy/hsearch, to those in the APR and glib, which also provide prebuilt hash functions. I'd highly recommend using those rather than inventing your own hashtable or hash function; they've been optimized heavily for common use-cases.

If your dataset is static, however, your best solution is probably to use a perfect hash. gperf will generate a perfect hash for you for a given dataset.

How to get character array from a string?

You can also use Array.from.

_x000D_
_x000D_
var m = "Hello world!";
console.log(Array.from(m))
_x000D_
_x000D_
_x000D_

This method has been introduced in ES6.

Reference

Array.from

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

Script to Change Row Color when a cell changes text

Realise this is an old thread, but after seeing lots of scripts like this I noticed that you can do this just using conditional formatting.

Assuming the "Status" was Column D:

Highlight cells > right click > conditional formatting. Select "Custom Formula Is" and set the formula as

=RegExMatch($D2,"Complete")

or

=OR(RegExMatch($D2,"Complete"),RegExMatch($D2,"complete"))

Edit (thanks to Frederik Schøning)

=RegExMatch($D2,"(?i)Complete") then set the range to cover all the rows e.g. A2:Z10. This is case insensitive, so will match complete, Complete or CoMpLeTe.

You could then add other rules for "Not Started" etc. The $ is very important. It denotes an absolute reference. Without it cell A2 would look at D2, but B2 would look at E2, so you'd get inconsistent formatting on any given row.

Tomcat 8 Maven Plugin for Java 8

Yes you can,

In your pom.xml, add the tomcat plugin. (You can use this for both Tomcat 7 and 8):

pom.xml

<!-- Tomcat plugin -->  
<plugin>  
 <groupId>org.apache.tomcat.maven</groupId>  
 <artifactId>tomcat7-maven-plugin</artifactId>  
 <version>2.2</version>  
 <configuration>  
  <url>http:// localhost:8080/manager/text</url>  
  <server>TomcatServer</server>    *(From maven > settings.xml)*
  <username>*yourtomcatusername*</username>  
  <password>*yourtomcatpassword*</password>   
 </configuration>   
</plugin>   

tomcat-users.xml

<tomcat-users>
    <role rolename="manager-gui"/>  
        <role rolename="manager-script"/>   
        <user username="admin" password="password" roles="manager-gui,manager-script" />  
</tomcat-users>

settings.xml (maven > conf)

<servers>  
    <server>
       <id>TomcatServer</id>
       <username>admin</username>
       <password>password</password>
    </server>
</servers>  

* deploy/re-deploy

mvn tomcat7:deploy OR mvn tomcat7:redeploy

Tried this on (Both Ubuntu and Windows 8/10):
* Jdk 7 & Tomcat 7
* Jdk 7 & Tomcat 8
* Jdk 8 & Tomcat 7
* Jdk 8 & Tomcat 8
* Jdk 8 & Tomcat 9

Tested on Both Jdk 7/8 & Tomcat 7/8. (Works with Tomcat 8.5 and 9)

Note:
Tomcat manager should be running or properly setup, before you can use it with maven.

Good Luck!

How to remove gem from Ruby on Rails application?

How about something like:

gem dependency devise --pipe | cut -d \  -f 1 | xargs gem uninstall -a

(this assumes that you're not using bundler - but I guess you're not since removing from your bundle gemspec would solve the problem)

How to open Android Device Monitor in latest Android Studio 3.1

From Android Studio 3.1 Device Monitor available from the command line only.

In Android Studio 3.1, the Device Monitor serves less of a role than it previously did. In many cases, the functionality available through the Device Monitor is now provided by new and improved tools.

See the Device Monitor documentation for instructions for invoking the Device Monitor from the command line and for details of the tools available through the Device Monitor.

To start the standalone Device Monitor application, enter the following on the command line in the android-sdk/tools/ directory:

monitor

Java: parse int value from a char

By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.

String str = "123";

int a=str.charAt(1)-'0';

What version of Java is running in Eclipse?

try this :

public class vm
{
  public static void main(String[] args)
  {
      System.getProperty("sun.arch.data.model") 
  }
}

compile and run. it will return either 32 or 64 as per your java version . . .

Convert hex string (char []) to int?

So, after a while of searching, and finding out that strtol is quite slow, I've coded my own function. It only works for uppercase on letters, but adding lowercase functionality ain't a problem.

int hexToInt(PCHAR _hex, int offset = 0, int size = 6)
{
    int _result = 0;
    DWORD _resultPtr = reinterpret_cast<DWORD>(&_result);
    for(int i=0;i<size;i+=2)
    {
        int _multiplierFirstValue = 0, _addonSecondValue = 0;

        char _firstChar = _hex[offset + i];
        if(_firstChar >= 0x30 && _firstChar <= 0x39)
            _multiplierFirstValue = _firstChar - 0x30;
        else if(_firstChar >= 0x41 && _firstChar <= 0x46)
            _multiplierFirstValue = 10 + (_firstChar - 0x41);

        char _secndChar = _hex[offset + i + 1];
        if(_secndChar >= 0x30 && _secndChar <= 0x39)
            _addonSecondValue = _secndChar - 0x30;
        else if(_secndChar >= 0x41 && _secndChar <= 0x46)
            _addonSecondValue = 10 + (_secndChar - 0x41);

        *(BYTE *)(_resultPtr + (size / 2) - (i / 2) - 1) = (BYTE)(_multiplierFirstValue * 16 + _addonSecondValue);
    }
    return _result;
}

Usage:

char *someHex = "#CCFF00FF";
int hexDevalue = hexToInt(someHex, 1, 8);

1 because the hex we want to convert starts at offset 1, and 8 because it's the hex length.

Speedtest (1.000.000 calls):

strtol ~ 0.4400s
hexToInt ~ 0.1100s

Android Studio: Add jar as library?

Step 1 : Now under your app folder you should see libs, if you don't see it, then create it .

Step 2 : Drag & Drop the .jar file here, you may be get a prompt "This file does not belong to the project", just click OK Button .

Step 3 : Now you should see the jar file under libs folder, right click on the jar file and select "Add as library", Click OK for prompt "Create Library"

Step 4 : Now this jar has been added.

enter image description here

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

Key hash for Android-Facebook app

In Android Studio just click on right sidebar panel "Gradle" to show gardel panel then: -YOURAPPNAME --Task ---Android ----(double click) signingReport (to start Gradle Daemon)

then you will see result:

Config: debug
Store: C:\Users\username\.android\debug.keystore
Alias: AndroidDebugKey
MD5: C8:46:01:EA:36:02:D1:21:1B:23:19:91:D4:32:CB:AC
SHA1: 38:AB:4C:01:01:D7:62:E0:61:D1:9F:52:04:0C:E5:07:4E:E4:9B:39
SHA-256: 1B:8C:DC:35:48:10:01:2C:1F:BD:01:64:F1:01:06:01:60:01:A6:8B:10:15:2E:BF:7B:C4:FD:38:4C:C1:74:01
Valid until: Saturday, February 12, 2050

copy SHA1:

38:AB:4C:01:01:D7:62:E0:68:D1:9F:52:04:0C:E5:07:4E:E4:9B:39

go to this PAGE

Paste SHA1 and generate your Facebook key hash code.

Convert SVG image to PNG with PHP

$command = 'convert -density 300 ';
                        if(Input::Post('height')!='' && Input::Post('width')!=''){
                            $command.='-resize '.Input::Post('width').'x'.Input::Post('height').' ';
                        }
                        $command.=$svg.' '.$source;
                        exec($command);
                        @unlink($svg);

or using : potrace demo :Tool4dev.com

Numpy: find index of the elements within range

s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]

dic={}

for i in range(0,len(s),10):
    dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)

for keys,values in dic.items():
    print(keys)
    print(values)

Output:

(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]  

MySQL: Error dropping database (errno 13; errno 17; errno 39)

in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.

The thread has exited with code 0 (0x0) with no unhandled exception

I have also faced this problem and the solution is:

  1. open Solution Explore
  2. double click on Program.cs file

I added this code again and my program ran accurately:

Application.Run(new PayrollSystem()); 
//File name this code removed by me accidentally.

Convert NSData to String?

I believe your "P" as the dataWithBytes param

NSData *keydata = [NSData dataWithBytes:P length:len];

should be "buf"

NSData *keydata = [NSData dataWithBytes:buf length:len];

since i2d_PrivateKey puts the pointer to the output buffer p at the end of the buffer and waiting for further input, and buf is still pointing to the beginning of your buffer.

The following code works for me where pkey is a pointer to an EVP_PKEY:

unsigned char *buf, *pp;
int len = i2d_PrivateKey(pkey, NULL);
buf = OPENSSL_malloc(len); 
pp = buf;
i2d_PrivateKey(pkey, &pp);

NSData* pkeyData = [NSData dataWithBytes:(const void *)buf length:len];
DLog(@"Private key in hex (%d): %@", len, pkeyData);

You can use an online converter to convert your binary data into base 64 (http://tomeko.net/online_tools/hex_to_base64.php?lang=en) and compare it to the private key in your cert file after using the following command and checking the output of mypkey.pem:

openssl pkcs12 -in myCert.p12 -nocerts -nodes -out mypkey.pem

I referenced your question and this EVP function site for my answer.

Directing print output to a .txt file

Another method without having to update your Python code at all, would be to redirect via the console.

Basically, have your Python script print() as usual, then call the script from the command line and use command line redirection. Like this:

$ python ./myscript.py > output.txt

Your output.txt file will now contain all output from your Python script.

Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py)

Check if a file is executable

Testing files, directories and symlinks

The solutions given here fail on either directories or symlinks (or both). On Linux, you can test files, directories and symlinks with:

if [[ -f "$file" && -x $(realpath "$file") ]]; then .... fi

On OS X, you should be able to install coreutils with homebrew and use grealpath.

Defining an isexec function

You can define a function for convenience:

isexec() {
    if [[ -f "$1" && -x $(realpath "$1") ]]; then
        true;
    else
        false;
    fi;
}

Or simply

isexec() { [[ -f "$1" && -x $(realpath "$1") ]]; }

Then you can test using:

if `isexec "$file"`; then ... fi

What are the default access modifiers in C#?

Simplest answer is the following.....

All members in C# always take the LEAST accessible modifier possible by default.

That is why all top level classes in an assembly are "internal" by default, which means they are public to the assembly they are in, but private or excluded from access to outside assemblies. The only other option for a top level class is public which is more accessible. For nested types its all private except for a few rare exceptions like members of enums and interfaces which can only be public. Some examples. In the case of top level classes and interfaces, the defaults are:

class Animal same as internal class Animal

interface Animal same as public interface Animal

In the case of nested classes and interfaces (inside types), the defaults are:

class Animal same as private class Animal

interface Animal same as private interface Animal

If you just assume the default is always the most private, then you do not need to use an accessors until you need to change the default. Easy.

Oracle get previous day records

how about sysdate?

SELECT field,datetime_field 
FROM database
WHERE datetime_field > (sysdate-1)

pass post data with window.location.href

Using window.location.href it's not possible to send a POST request.

What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

What's the difference between :: (double colon) and -> (arrow) in PHP?

When the left part is an object instance, you use ->. Otherwise, you use ::.

This means that -> is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while :: is usually used to access static members (though in a few special cases, it's used to access instance members).

In general, :: is used for scope resolution, and it may have either a class name, parent, self, or (in PHP 5.3) static to its left. parent refers to the scope of the superclass of the class where it's used; self refers to the scope of the class where it's used; static refers to the "called scope" (see late static bindings).

The rule is that a call with :: is an instance call if and only if:

  • the target method is not declared as static and
  • there is a compatible object context at the time of the call, meaning these must be true:
    1. the call is made from a context where $this exists and
    2. the class of $this is either the class of the method being called or a subclass of it.

Example:

class A {
    public function func_instance() {
        echo "in ", __METHOD__, "\n";
    }
    public function callDynamic() {
        echo "in ", __METHOD__, "\n";
        B::dyn();
    }

}

class B extends A {
    public static $prop_static = 'B::$prop_static value';
    public $prop_instance = 'B::$prop_instance value';

    public function func_instance() {
        echo "in ", __METHOD__, "\n";
        /* this is one exception where :: is required to access an
         * instance member.
         * The super implementation of func_instance is being
         * accessed here */
        parent::func_instance();
        A::func_instance(); //same as the statement above
    }

    public static function func_static() {
        echo "in ", __METHOD__, "\n";
    }

    public function __call($name, $arguments) {
        echo "in dynamic $name (__call)", "\n";
    }

    public static function __callStatic($name, $arguments) {
        echo "in dynamic $name (__callStatic)", "\n";
    }

}

echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";

echo '$b->func_instance():', "\n", $b->func_instance(), "\n";

/* This is more tricky
 * in the first case, a static call is made because $this is an
 * instance of A, so B::dyn() is a method of an incompatible class
 */
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
 * instance of B (despite the fact we are in a method of A), so
 * B::dyn() is a method of a compatible class (namely, it's the
 * same class as the object's)
 */
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";

Output:

B::$prop_static: B::$prop_static value
B::func_static(): in B::func_static

$b->prop_instance: B::$prop_instance value
$b->func_static(): in B::func_static

$b->func_instance():
in B::func_instance
in A::func_instance
in A::func_instance

$a->dyn():
in A::callDynamic
in dynamic dyn (__callStatic)

$b->dyn():
in A::callDynamic
in dynamic dyn (__call)

jQuery: how to get which button was clicked upon form submission?

Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.

$('form.form-js').submit(function(event){
    var frm = $(this);
    var btn = $(document.activeElement);
    if(
        btn.length &&
        frm.has(btn) &&
        btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
        btn.is('[name]')
    ){
        frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
    }

    // Handle the form submit here

    $('#form-js-temp').remove();
});

Side note: I personally add the class form-js on all forms that are submitted via JavaScript.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

This works for me

  1. Stop the ng server(ctrl+c)

  2. Run Again

    npm start / ng serve --open
    

regular expression to validate datetime format (MM/DD/YYYY)

The answer marked is perfect but for one scenario, where in the dd and mm are actually single digits. the following regex is perfect in this case:

_x000D_
_x000D_
    function validateDate(testdate) {_x000D_
        var date_regex = /^(0?[1-9]|1[0-2])\/(0?[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;_x000D_
        return date_regex.test(testdate);_x000D_
    }
_x000D_
_x000D_
_x000D_

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

What's the difference between a mock & stub?

Stub helps us to run test. How? It gives values which helps to run test. These values are itself not real and we created these values just to run the test. For example we create a HashMap to give us values which are similar to values in database table. So instead of directly interacting with database we interact with Hashmap.

Mock is an fake object which runs the test. where we put assert.

How can I add a key/value pair to a JavaScript object?

You can either add it this way:

arr['key3'] = value3;

or this way:

arr.key3 = value3;

The answers suggesting keying into the object with the variable key3 would only work if the value of key3 was 'key3'.

Difference between InvariantCulture and Ordinal string comparison

It does matter, for example - there is a thing called character expansion

var s1 = "Strasse";
var s2 = "Straße";

s1.Equals(s2, StringComparison.Ordinal);           //false
s1.Equals(s2, StringComparison.InvariantCulture);  //true

With InvariantCulture the ß character gets expanded to ss.

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

How to increase application heap size in Eclipse?

In the run configuration you want to customize (just click on it) open the tab Arguments and add -Xmx2048min the VM arguments section. You might want to set the -Xms as well (small heap size).

How do I find files with a path length greater than 260 characters in Windows?

do a dir /s /b > out.txt and then add a guide at position 260

In powershell cmd /c dir /s /b |? {$_.length -gt 260}

Spark Dataframe distinguish columns with duplicated name

Suppose the DataFrames you want to join are df1 and df2, and you are joining them on column 'a', then you have 2 methods

Method 1

df1.join(df2,'a','left_outer')

This is an awsome method and it is highly recommended.

Method 2

df1.join(df2,df1.a == df2.a,'left_outer').drop(df2.a)

Why can't I define a static method in a Java interface?

I think java does not have static interface methods because you do not need them. You may think you do, but... How would you use them? If you want to call them like

MyImplClass.myMethod()

then you do not need to declare it in the interface. If you want to call them like

myInstance.myMethod()

then it should not be static. If you are actually going to use first way, but just want to enforce each implementation to have such static method, then it is really a coding convention, not a contract between instance that implements an interface and calling code.

Interfaces allow you to define contract between instance of class that implement the interface and calling code. And java helps you to be sure that this contract is not violated, so you can rely on it and don't worry what class implements this contract, just "someone who signed a contract" is enough. In case of static interfaces your code

MyImplClass.myMethod()

does not rely on the fact that each interface implementation has this method, so you do not need java to help you to be sure with it.

How do I reload a page without a POSTDATA warning in Javascript?

This worked

<button onclick="window.location.href=window.location.href; return false;">Continue</button>

The reason it didn't work without the

return false;
is that previously it treated that as a form submit button. With an explicit return false on it, it doesn't do the form submit and just does the reload of the same page that was a result of a previous POST to that page.

How do I retrieve query parameters in Spring Boot?

Use @RequestParam

@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){

    Item i = itemDao.findOne(itemid);              
    String itemName = i.getItemName();
    String price = i.getPrice();
    return i;
}

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

Double border with different color

I use outline a css 2 property that simply works. Check this out, is simple and even easy to animate:

_x000D_
_x000D_
.double-border {_x000D_
  display: block;_x000D_
  clear: both;_x000D_
  background: red;_x000D_
  border: 5px solid yellow;_x000D_
  outline: 5px solid blue;_x000D_
  transition: 0.7s all ease-in;_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
}_x000D_
.double-border:hover {_x000D_
  background: yellow;_x000D_
  outline-color: red;_x000D_
  border-color: blue;_x000D_
}
_x000D_
<div class="double-border"></div>
_x000D_
_x000D_
_x000D_

git - Server host key not cached

Had the same issue, and forget to connect to SSH on port where is actuall repository, not just general SSH port, then the host key is different!

c# foreach (property in object)... Is there a simple way of doing this?

Sure, no problem:

foreach(object item in sequence)
{
    if (item == null) continue;
    foreach(PropertyInfo property in item.GetType().GetProperties())
    {
        // do something with the property
    }
}

Error: could not find function "%>%"

One needs to install magrittr as follows

install.packages("magrittr")

Then, in one's script, don't forget to add on top

library(magrittr)

For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?

Note that the same operator would also work with the library dplyr, as it imports from magrittr.

dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)

Convert List<DerivedClass> to List<BaseClass>

To quote the great explanation of Eric

What happens? Do you want the list of giraffes to contain a tiger? Do you want a crash? or do you want the compiler to protect you from the crash by making the assignment illegal in the first place? We choose the latter.

But what if you want to choose for a runtime crash instead of a compile error? You would normally use Cast<> or ConvertAll<> but then you will have 2 problems: It will create a copy of the list. If you add or remove something in the new list, this won't be reflected in the original list. And secondly, there is a big performance and memory penalty since it creates a new list with the existing objects.

I had the same problem and therefore I created a wrapper class that can cast a generic list without creating an entirely new list.

In the original question you could then use:

class Test
{
    static void Main(string[] args)
    {
        A a = new C(); // OK
        IList<A> listOfA = new List<C>().CastList<C,A>(); // now ok!
    }
}

and here the wrapper class (+ an extention method CastList for easy use)

public class CastedList<TTo, TFrom> : IList<TTo>
{
    public IList<TFrom> BaseList;

    public CastedList(IList<TFrom> baseList)
    {
        BaseList = baseList;
    }

    // IEnumerable
    IEnumerator IEnumerable.GetEnumerator() { return BaseList.GetEnumerator(); }

    // IEnumerable<>
    public IEnumerator<TTo> GetEnumerator() { return new CastedEnumerator<TTo, TFrom>(BaseList.GetEnumerator()); }

    // ICollection
    public int Count { get { return BaseList.Count; } }
    public bool IsReadOnly { get { return BaseList.IsReadOnly; } }
    public void Add(TTo item) { BaseList.Add((TFrom)(object)item); }
    public void Clear() { BaseList.Clear(); }
    public bool Contains(TTo item) { return BaseList.Contains((TFrom)(object)item); }
    public void CopyTo(TTo[] array, int arrayIndex) { BaseList.CopyTo((TFrom[])(object)array, arrayIndex); }
    public bool Remove(TTo item) { return BaseList.Remove((TFrom)(object)item); }

    // IList
    public TTo this[int index]
    {
        get { return (TTo)(object)BaseList[index]; }
        set { BaseList[index] = (TFrom)(object)value; }
    }

    public int IndexOf(TTo item) { return BaseList.IndexOf((TFrom)(object)item); }
    public void Insert(int index, TTo item) { BaseList.Insert(index, (TFrom)(object)item); }
    public void RemoveAt(int index) { BaseList.RemoveAt(index); }
}

public class CastedEnumerator<TTo, TFrom> : IEnumerator<TTo>
{
    public IEnumerator<TFrom> BaseEnumerator;

    public CastedEnumerator(IEnumerator<TFrom> baseEnumerator)
    {
        BaseEnumerator = baseEnumerator;
    }

    // IDisposable
    public void Dispose() { BaseEnumerator.Dispose(); }

    // IEnumerator
    object IEnumerator.Current { get { return BaseEnumerator.Current; } }
    public bool MoveNext() { return BaseEnumerator.MoveNext(); }
    public void Reset() { BaseEnumerator.Reset(); }

    // IEnumerator<>
    public TTo Current { get { return (TTo)(object)BaseEnumerator.Current; } }
}

public static class ListExtensions
{
    public static IList<TTo> CastList<TFrom, TTo>(this IList<TFrom> list)
    {
        return new CastedList<TTo, TFrom>(list);
    }
}

Create a pointer to two-dimensional array

You want a pointer to the first element, so;

static uint8_t l_matrix[10][20];

void test(){
   uint8_t *matrix_ptr = l_matrix[0]; //wrong idea 
}

ssh: connect to host github.com port 22: Connection timed out

Quick workaround: try switching to a different network

I experienced this problem while on a hotspot (3/4G connection). Switching to a different connection (WiFi) resolved it, but it's just a workaround - I didn't get the chance to get to the bottom of the issue so the other answers might be more interesting to determine the underlying issue

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

You can do this with jquery like this:

        $("#elemenId").keydown(function (e) {
            if(e.key == "F12"){
                console.log(e.key);
            }

        });

Get bitcoin historical data

I have written a java example for this case:

Use json.org library to retrieve JSONObjects and JSONArrays. The example below uses blockchain.info's data which can be obtained as JSONObject.

    public class main 
    {
        public static void main(String[] args) throws MalformedURLException, IOException
        {
            JSONObject data = getJSONfromURL("https://blockchain.info/charts/market-price?format=json");
            JSONArray data_array = data.getJSONArray("values");

            for (int i = 0; i < data_array.length(); i++)
            {
                JSONObject price_point = data_array.getJSONObject(i);

                //  Unix time
                int x = price_point.getInt("x");

                //  Bitcoin price at that time
                double y = price_point.getDouble("y");

                //  Do something with x and y.
            }

        }

        public static JSONObject getJSONfromURL(String URL)
        {
            try
            {
                URLConnection uc;
                URL url = new URL(URL);
                uc = url.openConnection();
                uc.setConnectTimeout(10000);
                uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                uc.connect();

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(uc.getInputStream(), 
                        Charset.forName("UTF-8")));

                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1)
                {
                    sb.append((char)cp);
                }

                String jsonText = (sb.toString());            

                return new JSONObject(jsonText.toString());
            } catch (IOException ex)
            {
                return null;
            }
        }
    }

When should I use Async Controllers in ASP.NET MVC?

As you know, MVC supports asynchronous controllers and you should take advantage of it. In case your Controller, performs a lengthy operation, (it might be a disk based I/o or a network call to another remote service), if the request is handled in synchronous manner, the IIS thread is busy the whole time. As a result, the thread is just waiting for the lengthy operation to complete. It can be better utilized by serving other requests while the operation requested in first is under progress. This will help in serving more concurrent requests. Your webservice will be highly scalable and will not easily run into C10k problem. It is a good idea to use async/await for db queries. and yes you can use them as many number of times as you deem fit.

Take a look here for excellent advise.

iPhone UITextField - Change placeholder text color

Easy and pain-free, could be an easy alternative for some.

_placeholderLabel.textColor

Not suggested for production, Apple may reject your submission.

How to open a website when a Button is clicked in Android application?

I just need one line to show a website in my app:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://match4app.com")));

Difference between natural join and inner join

A Natural Join is where 2 tables are joined on the basis of all common columns.

common column : is a column which has same name in both tables + has compatible datatypes in both the tables. You can use only = operator

A Inner Join is where 2 tables are joined on the basis of common columns mentioned in the ON clause.

common column : is a column which has compatible datatypes in both the tables but need not have the same name. You can use only any comparision operator like =, <=, >=, <, >, <>

How to downgrade the installed version of 'pip' on windows?

If downgrading from pip version 10 because of PyCharm manage.py or other python errors:

python -m pip install pip==9.0.1

How to change mysql to mysqli?

2020+ Answer

I've created a tool called Rector, that handles instant upgrades. There is also mysql ? mysqli set.

It handles:

  • function renaming

  • constant renaming

  • switched arguments

  • non-1:1 function calls changes, e.g.

      $data = mysql_db_name($result, $row);
    

    ?

      mysqli_data_seek($result, $row);
      $fetch = mysql_fetch_row($result);
      $data = $fetch[0];
    

How to use Rector?

1. Install it via Composer

composer require rector/rector --dev

// or in case of composer conflicts
composer require rector/rector-prefixed --dev

2. Create rector.php in project root directory with the Mysql to Mysqli set

<?php

use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {

    $parameters->set(Option::SETS, [
        SetList::MYSQL_TO_MYSQLI,
    ]);
};

3. Let Rector run on e.g. /src directory to only show the diffs

vendor/bin/rector process src --dry-run

4. Let Rector change the code

vendor/bin/rector process src

I've already run it on 2 big PHP projects and it works perfectly.

TortoiseSVN icons overlay not showing after updating to Windows 10

The following steps worked for me:

  1. TortoiseSVN -> Settings -> IconOverlays -> Icon Set
  2. Choose "Win10" icon set
  3. Restart computer.

Remove a specific character using awk or sed

Use sed's substitution: sed 's/"//g'

s/X/Y/ replaces X with Y.

g means all occurrences should be replaced, not just the first one.

Text Editor which shows \r\n?

In vi(m), check out:

:help 'list'
:help 'listchars' 

How do I install cURL on Windows?

You can also use CygWin and install the cURL package. It works very well and flawlessly!!

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

What is the target platform of your application? I think you should set the platform to x86, do not set it to Any CPU.

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: http://jsfiddle.net/pjBzY/22/ (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.


jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        </div>
        <div class="col-sm-6 my-column">
            Col 2
        </div>
    </div>
</div>

and the CSS

.row {
    border: blue 1px solid;
}
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
}
.my-column:first-child {
    background-color: red;
}

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;
}

How do I return a string from a regex match in python?

Considering there might be several img tags I would recommend re.findall:

import re

with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
    for line in f_in:
        for img in re.findall('<img[^>]+>', line):
            print >> f_out, "yo it's a {}".format(img)

How to get a variable value if variable name is stored as string?

X=foo
Y=X
eval "Z=\$$Y"

sets Z to "foo"

Take care using eval since this may allow accidential excution of code through values in ${Y}. This may cause harm through code injection.

For example

Y="\`touch /tmp/eval-is-evil\`"

would create /tmp/eval-is-evil. This could also be some rm -rf /, of course.

When do I use super()?

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

Time calculation in php (add 10 hours)?

$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

see DateTime Class (PHP 5 >= 5.2.0)

Mercurial — revert back to old version and continue from there

I'd install Tortoise Hg (a free GUI for Mercurial) and use that. You can then just right-click on a revision you might want to return to - with all the commit messages there in front of your eyes - and 'Revert all files'. Makes it intuitive and easy to roll backwards and forwards between versions of a fileset, which can be really useful if you are looking to establish when a problem first appeared.

How to convert unix timestamp to calendar date moment.js

I fixed it like this example.

$scope.myCalendar = new Date(myUnixDate*1000);
<input date-time ng-model="myCalendar" format="DD/MM/YYYY" />

Remove the title bar in Windows Forms

I am sharing my code. form1.cs:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BorderExp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

    }

    private void ExitClick(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void MaxClick(object sender, EventArgs e)
    {
        if (WindowState ==FormWindowState.Normal)
        {
            this.WindowState = FormWindowState.Maximized;
        }
        else
        {
            this.WindowState = FormWindowState.Normal;
        }
    }

    private void MinClick(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Minimized;
       }
    }
    }

Now, the designer:-

namespace BorderExp
 {
   partial class Form1
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.button1 = new System.Windows.Forms.Button();
        this.button2 = new System.Windows.Forms.Button();
        this.button3 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // button1
        // 
        this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.button1.BackColor = System.Drawing.SystemColors.ButtonFace;
        this.button1.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.button1.FlatAppearance.BorderSize = 0;
        this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
        this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button1.Location = new System.Drawing.Point(376, 1);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(27, 26);
        this.button1.TabIndex = 0;
        this.button1.Text = "X";
        this.button1.UseVisualStyleBackColor = false;
        this.button1.Click += new System.EventHandler(this.ExitClick);
        // 
        // button2
        // 
        this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.button2.BackColor = System.Drawing.SystemColors.ButtonFace;
        this.button2.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.button2.FlatAppearance.BorderSize = 0;
        this.button2.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
        this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button2.Location = new System.Drawing.Point(343, 1);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(27, 26);
        this.button2.TabIndex = 1;
        this.button2.Text = "[]";
        this.button2.UseVisualStyleBackColor = false;
        this.button2.Click += new System.EventHandler(this.MaxClick);
        // 
        // button3
        // 
        this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.button3.BackColor = System.Drawing.SystemColors.ButtonFace;
        this.button3.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.button3.FlatAppearance.BorderSize = 0;
        this.button3.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
        this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button3.Location = new System.Drawing.Point(310, 1);
        this.button3.Name = "button3";
        this.button3.Size = new System.Drawing.Size(27, 26);
        this.button3.TabIndex = 2;
        this.button3.Text = "___";
        this.button3.UseVisualStyleBackColor = false;
        this.button3.Click += new System.EventHandler(this.MinClick);
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
        this.ClientSize = new System.Drawing.Size(403, 320);
        this.ControlBox = false;
        this.Controls.Add(this.button3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.button1);
        this.Name = "Form1";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Form1";
        this.Load += new System.EventHandler(this.Form1_Load);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Button button3;
    }
   }

the screenshot:- NoBorderForm

How do you delete a column by name in data.table?

Suppose your dt has columns col1, col2, col3, col4, col5, coln.

To delete a subset of them:

vx <- as.character(bquote(c(col1, col2, col3, coln)))[-1]
DT[, paste0(vx):=NULL]

Extract MSI from EXE

The only way to do that is running the exe and collect the MSI. The thing you must take care of is that if you are tranforming the MSI using MST they might get lost.

I use this batch commandline:

SET TMP=c:\msipath

MD "%TMP%"

SET TEMP=%TMP%

start /d "c:\install" install.exe /L1033

PING 1.1.1.1 -n 1 -w 10000 >NUL

for /R "%TMP%" %%f in (*.msi) do copy "%%f" "%TMP%"

taskkill /F /IM msiexec.exe /T

Count number of occurences for each unique value

I know there are many other answers, but here is another way to do it using the sort and rle functions. The function rle stands for Run Length Encoding. It can be used for counts of runs of numbers (see the R man docs on rle), but can also be applied here.

test.data = rep(c(1, 2, 2, 2), 25)
rle(sort(test.data))
## Run Length Encoding
##   lengths: int [1:2] 25 75
##   values : num [1:2] 1 2

If you capture the result, you can access the lengths and values as follows:

## rle returns a list with two items.
result.counts <- rle(sort(test.data))
result.counts$lengths
## [1] 25 75
result.counts$values
## [1] 1 2

Add CSS class to a div in code behind

For a non ASP.NET control, i.e. HTML controls like div, table, td, tr, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:

ASPX page

<head>
    <style type="text/css">
        .top_rounded
        {
            height: 75px;
            width: 75px;
            border: 2px solid;
            border-radius: 5px;
            -moz-border-radius: 5px; /* Firefox 3.6 and earlier */
            border-color: #9c1c1f;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="myDiv">This is my div</div>
    </form>
</body>

CS page

myDiv.Attributes.Add("class", "top_rounded");

When should I use double or single quotes in JavaScript?

Examining the pros and cons

In favor of single quotes

  • Less visual clutter.
  • Generating HTML: HTML attributes are usually delimited by double quotes.

_x000D_
_x000D_
elem.innerHTML = '<a href="' + url + '">Hello</a>';
_x000D_
_x000D_
_x000D_ However, single quotes are just as legal in HTML.

_x000D_
_x000D_
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
_x000D_
_x000D_
_x000D_

Furthermore, inline HTML is normally an anti-pattern. Prefer templates.

  • Generating JSON: Only double quotes are allowed in JSON.

_x000D_
_x000D_
myJson = '{ "hello world": true }';
_x000D_
_x000D_
_x000D_

Again, you shouldn’t have to construct JSON this way. JSON.stringify() is often enough. If not, use templates.

In favor of double quotes

  • Doubles are easier to spot if you don't have color coding. Like in a console log or some kind of view-source setup.
  • Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them. C and Java use double quotes for strings and single quotes for characters.
  • If you want code to be valid JSON, you need to use double quotes.

In favor of both

There is no difference between the two in JavaScript. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:

_x000D_
_x000D_
    "He said: \"Let's go!\""_x000D_
    'He said: "Let\'s go!"'_x000D_
    "He said: \"Let\'s go!\""_x000D_
    'He said: \"Let\'s go!\"'
_x000D_
_x000D_
_x000D_

Single quotes for internal strings and double for external. That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.). Obviously, you should avoid putting the latter in your code, but that can’t always be done.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

Passing a variable from node.js to html

I figured it out I was able to pass a variable like this

<script>var name = "<%= name %>";</script>
console.log(name);

npm not working after clearing cache

"As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use

npm cache verify

instead."

Why should I prefer to use member initialization lists?

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

Execute action when back bar button of UINavigationController is pressed

Try this .

self.navigationItem.leftBarButtonItem?.target = "methodname"
func methodname ( ) {            
  //    enter code here
}

Try on this too.

override func viewWillAppear(animated: Bool) {
  //empty your array
}

Send file using POST from a Python script

Yes. You'd use the urllib2 module, and encode using the multipart/form-data content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:

user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', response.read ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files)

        logging.info ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if file_matcher.search (file_path):
                matching_filenames.append (file_path)
            else:
                logging.info ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
        else:
            logging.error ('No such path: %r' % path)

    logging.info ('Done!')

How can I take a screenshot/image of a website using Python?

import subprocess

def screenshots(url, name):
    subprocess.run('webkit2png -F -o {} {} -D ./screens'.format(name, url), 
      shell=True)

Creating an iframe with given HTML dynamically

Do this

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

console.log(frame_win);
...

getIframeWindow is defined here

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

How to convert rdd object to dataframe in spark

Note: This answer was originally posted here

I am posting this answer because I would like to share additional details about the available options that I did not find in the other answers


To create a DataFrame from an RDD of Rows, there are two main options:

1) As already pointed out, you could use toDF() which can be imported by import sqlContext.implicits._. However, this approach only works for the following types of RDDs:

  • RDD[Int]
  • RDD[Long]
  • RDD[String]
  • RDD[T <: scala.Product]

(source: Scaladoc of the SQLContext.implicits object)

The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of scala.Product).

So, to use this approach for an RDD[Row], you have to map it to an RDD[T <: scala.Product]. This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:

val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => (val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

or

case class MyClass(val1: String, ..., valN: Long = 0L)
val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => MyClass(val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

The main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option:


2) You can use createDataFrame(rowRDD: RDD[Row], schema: StructType) as in the accepted answer, which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.

How do I update Node.js?

If you have Homebrew installed (only for macOS):

$ brew upgrade node

HTTP Error 503. The service is unavailable. App pool stops on accessing website

If you have McAfee HIPS and if you see the following error in event viewer application log:

The Module DLL C:\Windows\System32\inetsrv\HipIISEngineStub.dll failed to load.
The data is the error.

Then the following resolved the issue in my case: https://kc.mcafee.com/corporate/index?page=content&id=KB72677&actp=LIST

Quote from the page:

  1. Click Start, Run, type explorer and click OK.
  2. Navigate to: %windir%\system32\inetsrv\config
  3. Open the file applicationHost.config as Administrator for editing in Notepad.
  4. Edit the <globalModules> section and remove the following line:
    <add name="MfeEngine" image="%windir%\System32\inetsrv\HipIISEngineStub.dll" />

  5. Edit the <modules> section and remove the following line:
    <add name="MfeEngine" />

  6. After you have finished editing the applicationHost.config file, save the file, then restart the IIS server using iisreset or by restarting the system.

How can I check the size of a file in a Windows batch script?

Create a one line batch file GetFileSize.bat containing

GetFileSize=%~z1

then call it

call GetFileSize  myfile.txt
if (%GetFileSize) == ()     goto No_File
if (%GetFileSize) == (0)    goto No_Data
if (%GetFileSize) GTR 1000  goto Too_Much_Data
rem Etc.

You can even create your test file on the fly to eliminate the pesky required file, note the double percent in the echo statement:

echo set GetFileSize=%%~z1 > %temp%\GetFileSize.bat
call %temp%\GetFileSize  myfile.txt
if (%GetFileSize) GTR 1000  goto Too_Much_Data
rem etc

This latter solution is antispaghetti. So nice. However, more disk writes. Check use count.

Adding an image to a PDF using iTextSharp and scale it properly

I solved it using the following:

foreach (var image in images)
{
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);

    if (pic.Height > pic.Width)
    {
        //Maximum height is 800 pixels.
        float percentage = 0.0f;
        percentage = 700 / pic.Height;
        pic.ScalePercent(percentage * 100);
    }
    else
    {
        //Maximum width is 600 pixels.
        float percentage = 0.0f;
        percentage = 540 / pic.Width;
        pic.ScalePercent(percentage * 100);
    }

    pic.Border = iTextSharp.text.Rectangle.BOX;
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
    pic.BorderWidth = 3f;
    document.Add(pic);
    document.NewPage();
}

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

Multi-dimensional arrays in Bash

Expanding on Paul's answer - here's my version of working with associative sub-arrays in bash:

declare -A SUB_1=(["name1key"]="name1val" ["name2key"]="name2val")
declare -A SUB_2=(["name3key"]="name3val" ["name4key"]="name4val")
STRING_1="string1val"
STRING_2="string2val"
MAIN_ARRAY=(
  "${SUB_1[*]}"
  "${SUB_2[*]}"
  "${STRING_1}"
  "${STRING_2}"
)
echo "COUNT: " ${#MAIN_ARRAY[@]}
for key in ${!MAIN_ARRAY[@]}; do
    IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}
    echo "VALUE: " ${val[@]}
    if [[ ${#val[@]} -gt 1 ]]; then
        for subkey in ${!val[@]}; do
            subval=${val[$subkey]}
            echo "SUBVALUE: " ${subval}
        done
    fi
done

It works with mixed values in the main array - strings/arrays/assoc. arrays

The key here is to wrap the subarrays in single quotes and use * instead of @ when storing a subarray inside the main array so it would get stored as a single, space separated string: "${SUB_1[*]}"

Then it makes it easy to parse an array out of that when looping through values with IFS=' ' read -a val <<< ${MAIN_ARRAY[$key]}

The code above outputs:

COUNT:  4
VALUE:  name1val name2val
SUBVALUE:  name1val
SUBVALUE:  name2val
VALUE:  name4val name3val
SUBVALUE:  name4val
SUBVALUE:  name3val
VALUE:  string1val
VALUE:  string2val

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I have broken my head over this issue, and finally here's what worked for me:-

Step1 : Uninstall Entity framework using Nuget package manager

Step2: Delete Entityframework element from App.config

Step3: Reinstall desired version of Entity Framework.

Step4: delete Migrations table and Migrations folder.

Step5: Enable Migrations and Add Migration and Update database

Fast way to get the min/max values among properties of object

Here's a solution that allows you to return the key as well and only does one loop. It sorts the Object's entries (by val) and then returns the first and last one.

Additionally, it returns the sorted Object which can replace the existing Object so that future sorts will be faster because it will already be semi-sorted = better than O(n). It's important to note that Objects retain their order in ES6.

_x000D_
_x000D_
const maxMinVal = (obj) => {_x000D_
  const sortedEntriesByVal = Object.entries(obj).sort(([, v1], [, v2]) => v1 - v2);_x000D_
_x000D_
  return {_x000D_
    min: sortedEntriesByVal[0],_x000D_
    max: sortedEntriesByVal[sortedEntriesByVal.length - 1],_x000D_
    sortedObjByVal: sortedEntriesByVal.reduce((r, [k, v]) => ({ ...r, [k]: v }), {}),_x000D_
  };_x000D_
};_x000D_
_x000D_
const obj = {_x000D_
  a: 4, b: 0.5, c: 0.35, d: 5_x000D_
};_x000D_
_x000D_
console.log(maxMinVal(obj));
_x000D_
_x000D_
_x000D_

XAMPP: Couldn't start Apache (Windows 10)

  • Go to the start menu, and type Turn Windows features on or off
  • Uncheck Internet Information Services
  • Press OK

how to make a jquery "$.post" request synchronous

jQuery < 1.8

May I suggest that you use $.ajax() instead of $.post() as it's much more customizable.

If you are calling $.post(), e.g., like this:

$.post( url, data, success, dataType );

You could turn it into its $.ajax() equivalent:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async:false
});

Please note the async:false at the end of the $.ajax() parameter object.

Here you have a full detail of the $.ajax() parameters: jQuery.ajax() – jQuery API Documentation.


jQuery >=1.8 "async:false" deprecation notice

jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:

  • use a plugin e.g. BlockUI;
  • manually add an overlay before calling $.ajax(), and then remove it when the AJAX .done() callback is called.

Please have a look at this answer for an example.

Cloning a private Github repo

If the newly used computer has different credentials running this command

git clone https://github.com/username/reponame.git

directly will not work. Git will attempt to use the stored credentials and will not prompt you for the username and the password. Since the credentials mismatch, git will output Repository not found and the clone operation fails. The way I solved it was by deleting the old credentials, since I don't use them anymore, and ran the the above mentioned command again and entered the required username and password and cloned the private repo.

scale fit mobile web content using viewport meta tag

I think this should help you.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

Tell me if it works.

P/s: here is some media query for standard devices. http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

Why does my Spring Boot App always shutdown immediately after starting?

I initialized a new SPring boot project in IntelliJIdea with Spring Boot dev tools, but in pom.xml I had only dependency

 ...
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter</artifactId>
 </dependency>
 ...

You need to have also artifact spring-boot-starter-web. Just add this dependency to pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Difference between StringBuilder and StringBuffer

Check the internals of synchronized append method of StringBuffer and non-synchronized append method of StringBuilder.

StringBuffer:

public StringBuffer(String str) {
    super(str.length() + 16);
    append(str);
}

public synchronized StringBuffer append(Object obj) {
    super.append(String.valueOf(obj));
    return this;
}

public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
}

StringBuilder:

public StringBuilder(String str) {
    super(str.length() + 16);
    append(str);
}

public StringBuilder append(Object obj) {
    return append(String.valueOf(obj));
}

public StringBuilder append(String str) {
    super.append(str);
    return this;
}

Since append is synchronized, StringBuffer has performance overhead compared to StrinbBuilder in multi-threading scenario. As long as you are not sharing buffer among multiple threads, use StringBuilder, which is fast due to absence of synchronized in append methods.

Sample random rows in dataframe

Select a Random sample from a tibble type in R:

library("tibble")    
a <- your_tibble[sample(1:nrow(your_tibble), 150),]

nrow takes a tibble and returns the number of rows. The first parameter passed to sample is a range from 1 to the end of your tibble. The second parameter passed to sample, 150, is how many random samplings you want. The square bracket slicing specifies the rows of the indices returned. Variable 'a' gets the value of the random sampling.

Read all contacts' phone numbers in android

This code shows how to get all phone numbers for each contact.

ContentResolver cr = getActivity().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(cur.getColumnIndex(
                  ContactsContract.Contacts._ID));
        String name = cur.getString(cur.getColumnIndex(
                  ContactsContract.Contacts.DISPLAY_NAME));
        if (Integer.parseInt(cur.getString(cur.getColumnIndex(
                   ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
             Cursor pCur = cr.query(
                      ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                      null, 
                      ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                      new String[]{id}, null);
             while (pCur.moveToNext()) {
                  int phoneType = pCur.getInt(pCur.getColumnIndex(
                      ContactsContract.CommonDataKinds.Phone.TYPE));
                  String phoneNumber = pCur.getString(pCur.getColumnIndex(
                      ContactsContract.CommonDataKinds.Phone.NUMBER));
                  switch (phoneType) {
                        case Phone.TYPE_MOBILE:
                            Log.e(name + "(mobile number)", phoneNumber);
                            break;
                        case Phone.TYPE_HOME:
                            Log.e(name + "(home number)", phoneNumber);
                            break;
                        case Phone.TYPE_WORK:
                            Log.e(name + "(work number)", phoneNumber);
                            break;
                        case Phone.TYPE_OTHER:
                            Log.e(name + "(other number)", phoneNumber);
                            break;                                  
                        default:
                            break;
                  }
              } 
              pCur.close();
        }
    }
}

Owl Carousel, making custom navigation

Complete tutorial here

Demo link

enter image description here

JavaScript

$('.owl-carousel').owlCarousel({
    margin: 10,
    nav: true,
    navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
    responsive: {
        0: {
            items: 1
        },
        600: {
            items: 3
        },
        1000: {
            items: 5
        }
    }
});

CSS Style for navigation

.owl-carousel .nav-btn{
  height: 47px;
  position: absolute;
  width: 26px;
  cursor: pointer;
  top: 100px !important;
}

.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}

.owl-carousel .prev-slide{
  background: url(nav-icon.png) no-repeat scroll 0 0;
  left: -33px;
}
.owl-carousel .next-slide{
  background: url(nav-icon.png) no-repeat scroll -24px 0px;
  right: -33px;
}
.owl-carousel .prev-slide:hover{
 background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}   

setInterval in a React app

Thanks @dotnetom, @greg-herbowicz

If it returns "this.state is undefined" - bind timer function:

constructor(props){
    super(props);
    this.state = {currentCount: 10}
    this.timer = this.timer.bind(this)
}

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

Get type of a generic parameter in Java with reflection

Use:

Class<?> typeOfTheList = aListWithTypeSpiderMan.toArray().getClass().getComponentType();

Optional Parameters in Web Api Attribute Routing

Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-

When we mark a parameter as optional in the action uri using ? character then we must provide default values to the parameters in the method signature as shown below:

MyMethod(string name = "someDefaultValue", int? Id = null)

Way to get all alphabetic chars in an array in PHP?

To contribute, yesterday, PEZ's answer in this post, https://stackoverflow.com/a/431930/9710921 helped me to create an array to manage Excel columns for data exportations, like that:

public static function makeAlphas() : array {
    $alphas = $cells = range('A', 'Z');
    foreach($alphas as $alpha) {
        foreach($alphas as $beta) {
            $cells[] = $alpha.$beta;
        }
    }
    return $cells;
}

// Output
// array:702 ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ", "DK", "DL", "DM", "DN", "DO", "DP", "DQ", "DR", "DS", "DT", "DU", "DV", "DW", "DX", "DY", "DZ", "EA", "EB", "EC", "ED", "EE", "EF", "EG", "EH", "EI", "EJ", "EK", "EL", "EM", "EN", "EO", "EP", "EQ", "ER", "ES", "ET", "EU", "EV", "EW", "EX", "EY", "EZ", "FA", "FB", "FC", "FD", "FE", "FF", "FG", "FH", "FI", "FJ", "FK", "FL", "FM", "FN", "FO", "FP", "FQ", "FR", "FS", "FT", "FU", "FV", "FW", "FX", "FY", "FZ", "GA", "GB", "GC", "GD", "GE", "GF", "GG", "GH", "GI", "GJ", "GK", "GL", "GM", "GN", "GO", "GP", "GQ", "GR", "GS", "GT", "GU", "GV", "GW", "GX", "GY", "GZ", "HA", "HB", "HC", "HD", "HE", "HF", "HG", "HH", "HI", "HJ", "HK", "HL", "HM", "HN", "HO", "HP", "HQ", "HR", "HS", "HT", "HU", "HV", "HW", "HX", "HY", "HZ", "IA", "IB", "IC", "ID", "IE", "IF", "IG", "IH", "II", "IJ", "IK", "IL", "IM", "IN", "IO", "IP", "IQ", "IR", "IS", "IT", "IU", "IV", "IW", "IX", "IY", "IZ", "JA", "JB", "JC", "JD", "JE", "JF", "JG", "JH", "JI", "JJ", "JK", "JL", "JM", "JN", "JO", "JP", "JQ", "JR", "JS", "JT", "JU", "JV", "JW", "JX", "JY", "JZ", "KA", "KB", "KC", "KD", "KE", "KF", "KG", "KH", "KI", "KJ", "KK", "KL", "KM", "KN", "KO", "KP", "KQ", "KR", "KS", "KT", "KU", "KV", "KW", "KX", "KY", "KZ", "LA", "LB", "LC", "LD", "LE", "LF", "LG", "LH", "LI", "LJ", "LK", "LL", "LM", "LN", "LO", "LP", "LQ", "LR", "LS", "LT", "LU", "LV", "LW", "LX", "LY", "LZ", "MA", "MB", "MC", "MD", "ME", "MF", "MG", "MH", "MI", "MJ", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NB", "NC", "ND", "NE", "NF", "NG", "NH", "NI", "NJ", "NK", "NL", "NM", "NN", "NO", "NP", "NQ", "NR", "NS", "NT", "NU", "NV", "NW", "NX", "NY", "NZ", "OA", "OB", "OC", "OD", "OE", "OF", "OG", "OH", "OI", "OJ", "OK", "OL", "OM", "ON", "OO", "OP", "OQ", "OR", "OS", "OT", "OU", "OV", "OW", "OX", "OY", "OZ", "PA", "PB", "PC", "PD", "PE", "PF", "PG", "PH", "PI", "PJ", "PK", "PL", "PM", "PN", "PO", "PP", "PQ", "PR", "PS", "PT", "PU", "PV", "PW", "PX", "PY", "PZ", "QA", "QB", "QC", "QD", "QE", "QF", "QG", "QH", "QI", "QJ", "QK", "QL", "QM", "QN", "QO", "QP", "QQ", "QR", "QS", "QT", "QU", "QV", "QW", "QX", "QY", "QZ", "RA", "RB", "RC", "RD", "RE", "RF", "RG", "RH", "RI", "RJ", "RK", "RL", "RM", "RN", "RO", "RP", "RQ", "RR", "RS", "RT", "RU", "RV", "RW", "RX", "RY", "RZ", "SA", "SB", "SC", "SD", "SE", "SF", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SP", "SQ", "SR", "SS", "ST", "SU", "SV", "SW", "SX", "SY", "SZ", "TA", "TB", "TC", "TD", "TE", "TF", "TG", "TH", "TI", "TJ", "TK", "TL", "TM", "TN", "TO", "TP", "TQ", "TR", "TS", "TT", "TU", "TV", "TW", "TX", "TY", "TZ", "UA", "UB", "UC", "UD", "UE", "UF", "UG", "UH", "UI", "UJ", "UK", "UL", "UM", "UN", "UO", "UP", "UQ", "UR", "US", "UT", "UU", "UV", "UW", "UX", "UY", "UZ", "VA", "VB", "VC", "VD", "VE", "VF", "VG", "VH", "VI", "VJ", "VK", "VL", "VM", "VN", "VO", "VP", "VQ", "VR", "VS", "VT", "VU", "VV", "VW", "VX", "VY", "VZ", "WA", "WB", "WC", "WD", "WE", "WF", "WG", "WH", "WI", "WJ", "WK", "WL", "WM", "WN", "WO", "WP", "WQ", "WR", "WS", "WT", "WU", "WV", "WW", "WX", "WY", "WZ", "XA", "XB", "XC", "XD", "XE", "XF", "XG", "XH", "XI", "XJ", "XK", "XL", "XM", "XN", "XO", "XP", "XQ", "XR", "XS", "XT", "XU", "XV", "XW", "XX", "XY", "XZ", "YA", "YB", "YC", "YD", "YE", "YF", "YG", "YH", "YI", "YJ", "YK", "YL", "YM", "YN", "YO", "YP", "YQ", "YR", "YS", "YT", "YU", "YV", "YW", "YX", "YY", "YZ", "ZA", "ZB", "ZC", "ZD", "ZE", "ZF", "ZG", "ZH", "ZI", "ZJ", "ZK", "ZL", "ZM", "ZN", "ZO", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZW", "ZX", "ZY", "ZZ",];

Thanks PEZ!

Getting the location from an IP address

A pure Javascript example, using the services of https://geolocation-db.com They provide a JSON and JSONP-callback solution.

No jQuery required!

<!DOCTYPE html>
<html>
<head>
<title>Geo City Locator by geolocation-db.com</title>
</head>
<body>
    <div>Country: <span id="country"></span></div>
    <div>State: <span id="state"></span></div>
    <div>City: <span id="city"></span></div>
    <div>Postal: <span id="postal"></span></div>
    <div>Latitude: <span id="latitude"></span></div>
    <div>Longitude: <span id="longitude"></span></div>
    <div>IP address: <span id="ipv4"></span></div>                             
</body>
<script>

    var country = document.getElementById('country');
    var state = document.getElementById('state');
    var city = document.getElementById('city');
    var postal = document.getElementById('postal');
    var latitude = document.getElementById('latitude');
    var longitude = document.getElementById('longitude');
    var ip = document.getElementById('ipv4');

    function callback(data)
    {
        country.innerHTML = data.country_name;
        state.innerHTML = data.state;
        city.innerHTML = data.city;
        postal.innerHTML = data.postal;
        latitude.innerHTML = data.latitude;
        longitude.innerHTML = data.longitude;
        ip.innerHTML = data.IPv4;
    }

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://geoilocation-db.com/json/geoip.php?jsonp=callback';
    var h = document.getElementsByTagName('script')[0];
    h.parentNode.insertBefore(script, h);

</script> 
</html>

How to open my files in data_folder with pandas using relative path?

import pandas as pd
df = pd.read_csv('C:/data_folder/data.csv')

Java image resize, maintain aspect ratio

Load image:

BufferedImage bufferedImage = ImageIO.read(file);   

Resize it:

private BufferedImage resizeAndCrop(BufferedImage bufferedImage, Integer width, Integer height) {

    Mode mode = (double) width / (double) height >= (double) bufferedImage.getWidth() / (double) bufferedImage.getHeight() ? Scalr.Mode.FIT_TO_WIDTH
            : Scalr.Mode.FIT_TO_HEIGHT;

    bufferedImage = Scalr.resize(bufferedImage, Scalr.Method.ULTRA_QUALITY, mode, width, height);

    int x = 0;
    int y = 0;

    if (mode == Scalr.Mode.FIT_TO_WIDTH) {
        y = (bufferedImage.getHeight() - height) / 2;
    } else if (mode == Scalr.Mode.FIT_TO_HEIGHT) {
        x = (bufferedImage.getWidth() - width) / 2;
    }

    bufferedImage = Scalr.crop(bufferedImage, x, y, width, height);

    return bufferedImage;
}

Using Scalr library:

<dependency>
    <groupId>org.imgscalr</groupId>
    <artifactId>imgscalr-lib</artifactId>
    <version>4.2</version>
</dependency>

How to check certificate name and alias in keystore files?

You can run from Java code.

try {

        File file = new File(keystore location);
        InputStream is = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "password";
        keystore.load(is, password.toCharArray());


        Enumeration<String> enumeration = keystore.aliases();
        while(enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias name: " + alias);
            Certificate certificate = keystore.getCertificate(alias);
            System.out.println(certificate.toString());

        }

    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(null != is)
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

Certificate class holds all information about the keystore.

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);

@prateek Hope this is what you looking for!

Angularjs if-then-else construction in expression

I am trying to check if a key exist in an array in angular way and landed here on this question. In my Angularjs 1.4 ternary operator worked like below

{{ CONDITION ? TRUE : FALSE }}

hence for the array key exist i did a simple JS check

Solution 1 : {{ array['key'] !== undefined ? array['key'] : 'n/a' }}

Solution 2 : {{ "key" in array ? array['key'] : 'n/a' }}

Best way to Bulk Insert from a C# DataTable

If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

Or also with SQL Server, you can write it to a .csv and use BULK INSERT

If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

If using Oracle, you can use the array binding feature of ODP.NET

If SQLite: