Programs & Examples On #Eclipse mat

How do I remove my IntelliJ license in 2019.3?

For Windows : Using batch program.

Write this code in a text file and save it.

REM Delete eval folder with licence key and options.xml which contains a reference  to it
for %%I in ("WebStorm", "IntelliJ", "CLion", "Rider", "GoLand", "PhpStorm") do (
  for /d %%a in ("%USERPROFILE%\.%%I*") do (
    rd /s /q "%%a/config/eval"
    del /q "%%a\config\options\other.xml"
  )
)

REM Delete registry key and jetbrains folder (not sure if needet but however)
rmdir /s /q "%APPDATA%\JetBrains"
reg delete "HKEY_CURRENT_USER\Software\JavaSoft" /f

Now rename the file fileName.txt to fileName.bat

Close phpstorm if running. Disconnect internet. Then run the file. Open phpstorm again. If nothing goes wrong you will see the magic.

worst case : If phpstorm still shows "License Expired", at first uninstall and then apply the above technique.

Sleep function in C++

Prior to C++11, there was no portable way to do this.

A portable way is to use Boost or Ace library. There is ACE_OS::sleep(); in ACE.

Attaching click event to a JQuery object not yet added to the DOM

You have to append it. Create the element with:

var $div = $("<div>my div</div>");
$div.click(function(){alert("clicked")})
return $div;

Then if you append it will work.

Take a look at your example here and a simple version here.

TypeError: sequence item 0: expected string, int found

The answers by cval and Priyank Patel work great. However, be aware that some values could be unicode strings and therefore may cause the str to throw a UnicodeEncodeError error. In that case, replace the function str by the function unicode.

For example, assume the string Libië (Dutch for Libya), represented in Python as the unicode string u'Libi\xeb':

print str(u'Libi\xeb')

throws the following error:

Traceback (most recent call last):
  File "/Users/tomasz/Python/MA-CIW-Scriptie/RecreateTweets.py", line 21, in <module>
    print str(u'Libi\xeb')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 4: ordinal not in range(128)

The following line, however, will not throw an error:

print unicode(u'Libi\xeb') # prints Libië

So, replace:

values = ','.join([str(i) for i in value_list])

by

values = ','.join([unicode(i) for i in value_list])

to be safe.

Checking cin input stream produces an integer

I prefer to use <limits> to check for an int until it is passed.

#include <iostream>
#include <limits> //std::numeric_limits

using std::cout, std::endl, std::cin;

int main() {
    int num;
    while(!(cin >> num)){  //check the Input format for integer the right way
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Invalid input.  Reenter the number: ";
      };

    cout << "output= " << num << endl;

    return 0;
}

Delete specified file from document directory

I want to delete my sqlite db from document directory.I delete the sqlite db successfully by below answer

NSString *strFileName = @"sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
    NSLog(@"The file name is - %@",[filename pathExtension]);
    if ([[filename pathExtension] isEqualToString:strFileName]) {
       [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        NSLog(@"The sqlite is deleted successfully");
    }
}

How do I run Visual Studio as an administrator by default?

@Kumar

"W7 prompts everytime to run this program "devenv.exe" , anyway to get rid of that ?"

Yes. You can prevent Windows from prompting you by going to Control Panel/User Accounts/Change User Account Control settings and move the slider down.

ClassCastException, casting Integer to Double

Changing an integer to a double

int abc=12; //setting up integer "abc"

System.out.println((double)abc); 

The code will output integer "abc" as a double, which means that it will display as "12.0". Notice how there is a decimal place, indicating that this precision digit has been stored.

Same with double if you want to change it back,

double number=13.94;

System.out.println((int)number); 

This code will print on one line, "number" as an integer. The output will be "13". Notice that the value has not been rounded up, the data has actually been omitted.

How to set an environment variable in a running docker container

For a somewhat narrow use case, docker issue 8838 mentions this sort-of-hack:

You just stop docker daemon and change container config in /var/lib/docker/containers/[container-id]/config.json (sic)

This solution updates the environment variables without the need to delete and re-run the container, having to migrate volumes and remembering parameters to run.

However, this requires a restart of the docker daemon. And, until issue issue 2658 is addressed, this includes a restart of all containers.

How to create and download a csv file from php script?

That is the function that I used for my project, and it works as expected.

function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
    header( 'Content-Type: application/csv' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '";' );

    // clean output buffer
    ob_end_clean();

    $handle = fopen( 'php://output', 'w' );

    // use keys as column titles
    fputcsv( $handle, array_keys( $array['0'] ) );

    foreach ( $array as $value ) {
        fputcsv( $handle, $value , $delimiter );
    }

    fclose( $handle );

    // flush buffer
    ob_flush();

    // use exit to get rid of unexpected output afterward
    exit();
}

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The servlet API .jar file must not be embedded inside the webapp since, obviously, the container already has these classes in its classpath: it implements the interfaces contained in this jar.

The dependency should be in the provided scope, rather than the default compile scope, in your Maven pom:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Is there any way to prevent input type="number" getting negative values?

Just adding another way of doing this (using Angular) if you don't wanna dirt the HTML with even more code:

You only have to subscribe to the field valueChanges and set the Value as an absolute value (taking care of not emitting a new event because that will cause another valueChange hence a recursive call and trigger a Maximum call size exceeded error)

HTML CODE

<form [formGroup]="myForm">
    <input type="number" formControlName="myInput"/>
</form>

TypeScript CODE (Inside your Component)

formGroup: FormGroup;

ngOnInit() { 
    this.myInput.valueChanges 
    .subscribe(() => {
        this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
    });
}

get myInput(): AbstractControl {
    return this.myForm.controls['myInput'];
}

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

How to add a button to UINavigationBar?

Why not use the following: (from Draw custom Back button on iPhone Navigation Bar)

// Add left
UINavigationItem *previousItem = [[UINavigationItem alloc] initWithTitle:@"Back title"];
UINavigationItem *currentItem = [[UINavigationItem alloc] initWithTitle:@"Main Title"];
[self.navigationController.navigationBar setItems:[NSArray arrayWithObjects:previousItem, currentItem, nil] animated:YES];

// set the delegate to self
[self.navigationController.navigationBar setDelegate:self];

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

Python argparse command line flags without arguments

Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

How to change legend size with matplotlib.pyplot

On my install, FontProperties only changes the text size, but it's still too large and spaced out. I found a parameter in pyplot.rcParams: legend.labelspacing, which I'm guessing is set to a fraction of the font size. I've changed it with

pyplot.rcParams.update({'legend.labelspacing':0.25})

I'm not sure how to specify it to the pyplot.legend function - passing

prop={'labelspacing':0.25}

or

prop={'legend.labelspacing':0.25}

comes back with an error.

How do I abort/cancel TPL Tasks?

You can abort a task like a thread if you can cause the task to be created on its own thread and call Abort on its Thread object. By default, a task runs on a thread pool thread or the calling thread - neither of which you typically want to abort.

To ensure the task gets its own thread, create a custom scheduler derived from TaskScheduler. In your implementation of QueueTask, create a new thread and use it to execute the task. Later, you can abort the thread, which will cause the task to complete in a faulted state with a ThreadAbortException.

Use this task scheduler:

class SingleThreadTaskScheduler : TaskScheduler
{
    public Thread TaskThread { get; private set; }

    protected override void QueueTask(Task task)
    {
        TaskThread = new Thread(() => TryExecuteTask(task));
        TaskThread.Start();
    }

    protected override IEnumerable<Task> GetScheduledTasks() => throw new NotSupportedException(); // Unused
    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => throw new NotSupportedException(); // Unused
}

Start your task like this:

var scheduler = new SingleThreadTaskScheduler();
var task = Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.LongRunning, scheduler);

Later, you can abort with:

scheduler.TaskThread.Abort();

Note that the caveat about aborting a thread still applies:

The Thread.Abort method should be used with caution. Particularly when you call it to abort a thread other than the current thread, you do not know what code has executed or failed to execute when the ThreadAbortException is thrown, nor can you be certain of the state of your application or any application and user state that it is responsible for preserving. For example, calling Thread.Abort may prevent static constructors from executing or prevent the release of unmanaged resources.

Remove credentials from Git

For macOS users :

This error appears when you are using multiple Git accounts on the same machine.

Please follow below steps to remove the github.com credentials.

  1. Go to Finder
  2. Go to Applications
  3. Go to Utilities Folder
  4. Open Keychain Access
  5. Select the github.com and Right click on it

Delete "github.com"

Try again to Push or Pull to git and it will ask for the credentials. Enter valid credentials for repository account. Done

Critical t values in R

The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:

abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))

Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value

abs(qt(0.01/2, 40)) # 99% confidence, 2 sided

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Command to run a .bat file

You can use Cmd command to run Batch file.

Here is my way =>

cmd /c ""Full_Path_Of_Batch_Here.cmd" "

More information => cmd /?

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

You must setup postgresql-server-dev-X.Y, where X.Y. your's servers version, and it will install libpq-dev and other servers variables at modules for server side developing. In my case it was

apt-get install postgresql-server-dev-9.5

Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libmysqlclient18 mysql-common Use 'apt-get autoremove' to remove them. The following extra packages will be installed:
libpq-dev Suggested packages: postgresql-doc-10 The following NEW packages will be installed: libpq-dev postgresql-server-dev-9.5

In your's case

sudo apt-get install postgresql-server-dev-X.Y
sudo apt-get install python-psycopg2

What's the main difference between Java SE and Java EE?

First, J2SE and J2EE have been renamed. They're now Java SE and Java EE.

Essentially, Java SE is your standard Java designed for end-users. That's what you'd develop to for desktop applications. Java EE is the enterprise edition, designed for server programming, such as SOA and web applications.

Adding an arbitrary line to a matplotlib plot in ipython notebook

Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate() function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.

ax.annotate("",
            xy=(0.2, 0.2), xycoords='data',
            xytext=(0.8, 0.8), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                      connectionstyle="arc3, rad=0"),
            )

In the documentation it says you can draw only an arrow with an empty string as the first argument.

From the OP's example:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
              xy=(70, 90), xycoords='data',
              xytext=(90, 200), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

plt.show()

Example inline image

Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..

Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.

# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              edgecolor = "red",
                              linewidth=5,
                              alpha=0.65,
                              connectionstyle="arc3,rad=0."), 
              )

You can also add curve to the connecting line by adjusting the connectionstyle.

Remove CSS from a Div using JQuery

You can remove specific css that is on the element like this:

$(this).css({'background-color' : '', 'font-weight' : ''});

Although I agree with karim that you should probably be using CSS classes.

How to change RGB color to HSV?

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just calculations.

found via Google

How to access site running apache server over lan without internet connection

  1. Open the "internet protocol properties" section on computer_2.
  2. Enter the ip address (192.168.1.2) of computer_1 in "Preferred DNS server" text box and click ok and close the dialog box.

Now try to open the website again on computer_2.

How to import JSON File into a TypeScript file?

For Angular 7+,

1) add a file "typings.d.ts" to the project's root folder (e.g., src/typings.d.ts):

declare module "*.json" {
    const value: any;
    export default value;
}

2) import and access JSON data either:

import * as data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data.default);
    }

}

or:

import data from 'path/to/jsonData/example.json';
...
export class ExampleComponent {
    constructor() {
        console.log(data);
    }

}

How to customise file type to syntax associations in Sublime Text?

for ST3

$language = "language u wish"

if exists,

go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

else

create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

and set

{ "extensions": [ "yourextension" ] }

This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

Create table (structure) from existing table

Its probably also worth mentioning that you can do the following:

Right click the table you want to duplicate > Script Table As > Create To > New Query Editor Window

Then, where is says the name of the table you just right clicked in the script that has been generated, change the name to what ever you want your new table to be called and click Execute

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

http://www.sdid.com/products.shtml

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

How to disable sort in DataGridView?

If you want statically make columns not sortable. You can do this way

  1. Open the EditColumns window of the DataGridView control.
  2. Select the column you want to make not sortable on the left side pane.
  3. In the right side properties pane, select the Sort Mode property and select "Not Sortable" in that.

Maven package/install without test (skip tests)

just mvn clean install -DskipTests

Select single item from a list

Use the FirstOrDefault selector.

var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var firstEven = list.FirstOrDefault(n => n % 2 == 0);

if (firstEven == 0)
    Console.WriteLine("no even number");
else 
    Console.WriteLine("first even number is {0}", firstEven);

Just pass in a predicate to the First or FirstOrDefault method and it'll happily go round' the list and picks the first match for you.

If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.

Hope this helps :-)

Send Mail to multiple Recipients in java

InternetAddress.Parse is going to be your friend! See the worked example below:

String to = "[email protected], [email protected], [email protected]";
String toCommaAndSpaces = "[email protected] [email protected], [email protected]";
  1. Parse a comma-separated list of email addresses. Be strict. Require comma separated list.
  2. If strict is true, many (but not all) of the RFC822 syntax rules for emails are enforced.

    msg.setRecipients(Message.RecipientType.CC,
    InternetAddress.parse(to, true));
    
  3. Parse comma/space-separated list. Cut some slack. We allow spaces seperated list as well, plus invalid email formats.

    msg.setRecipients(Message.RecipientType.BCC,
    InternetAddress.parse(toCommaAndSpaces, false));
    

res.sendFile absolute path

you can use send instead of sendFile so you wont face with error! this works will help you!

fs.readFile('public/index1.html',(err,data)=>{
if(err){
  consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');

for telling browser that your response is type of PDF

res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');

if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.

res.send(data)

Pass variables to Ruby script via command line

You should try console_runner gem. This gem makes your pure Ruby code executable from command-line. All you need is to add YARD annotations to your code:

# @runnable This tool can talk to you. Run it when you are lonely.
#   Written in Ruby.  
class MyClass

    def initialize
      @hello_msg = 'Hello' 
      @bye_msg = 'Good Bye' 
    end

    # @runnable Say 'Hello' to you.
    # @param [String] name Your name
    # @param [Hash] options options
    # @option options [Boolean] :second_meet Have you met before?
    # @option options [String] :prefix Your custom prefix
    def say_hello(name, options = {})
      second_meet = nil
      second_meet = 'Nice to see you again!' if options['second_meet']
      prefix = options['prefix']
      message = @hello_msg + ', '
      message += "#{prefix} " if prefix
      message += "#{name}. "
      message += second_meet if second_meet
      puts message
    end

end

Then run it from console:

$ c_run /projects/example/my_class.rb  say_hello -n John --second-meet --prefix Mr. 
-> Hello, Mr. John. Nice to see you again!

How do I undo the most recent local commits in Git?

In order to remove some files from a Git commit, use the “git reset” command with the “–soft” option and specify the commit before HEAD.

$ git reset --soft HEAD~1

When running this command, you will be presented with the files from the most recent commit (HEAD) and you will be able to commit them.

Now that your files are in the staging area, you can remove them (or unstage them) using the “git reset” command again.

$ git reset HEAD <file>

Note: this time, you are resetting from HEAD as you simply want to exclude files from your staging area

If you are simply not interested in this file any more, you can use the “git rm” command in order to delete the file from the index (also called the staging area).

$ git rm --cached <file>

When you are done with the modifications, you can simply commit your changes again with the “–amend” option.

$ git commit --amend

To verify that the files were correctly removed from the repository, you can run the “git ls-files” command and check that the file does not appear in the file (if it was a new one of course)

$ git ls-files

 <file1>
 <file2>

Remove File From Commit using Git Restore

Since Git 2.23, there is a new way to remove files from commit, but you will have to make sure that you are using a Git version greater or equal than 2.23.

$ git --version

Git version 2.24.1

Note: Git 2.23 was released in August 2019 and you may not have this version already available on your computer.

To install newer versions of Git, you can check this tutorial. To remove files from commits, use the “git restore” command, specify the source using the “–source” option and the file to be removed from the repository.

For example, in order to remove the file named “myfile” from the HEAD, you would write the following command

$ git restore --source=HEAD^ --staged  -- <file>

As an example, let’s pretend that you edited a file in your most recent commit on your “master” branch.

The file is correctly committed but you want to remove it from your Git repository.

To remove your file from the Git repository, you want first to restore it.

$ git restore --source=HEAD^ --staged  -- newfile

$ git status

On branch master

Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)

Changes to be committed:

 (use "git restore --staged <file>..." to unstage)
    modified:   newfile

Changes not staged for commit:

 (use "git add <file>..." to update what will be committed)
 (use "git restore <file>..." to discard changes in working directory)
      modified:   newfile

As you can see, your file is back to the staging area.

From there, you have two choices, you can choose to edit your file in order to re-commit it again, or to simply delete it from your Git repository.

Remove File from Git Repository

In this section, we are going to describe the steps in order to remove the file from your Git repository.

First, you need to unstage your file as you won’t be able to remove it if it is staged.

To unstage a file, use the “git reset” command and specify the HEAD as source.

$ git reset HEAD newfile

When your file is correctly unstaged, use the “git rm” command with the “–cached” option in order to remove this file from the Git index (this won’t delete the file on disk)

$ git rm --cached newfile

rm 'newfile'

Now if you check the repository status, you will be able to see that Git staged a deletion commit.

$ git status

On branch master

Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits)

Changes to be committed:

 (use "git restore --staged <file>..." to unstage)
    deleted:    newfile

Now that your file is staged, simply use the “git commit” with the “–amend” option in order to amend the most recent commit from your repository.

`$ git commit --amend

 [master 90f8bb1] Commit from HEAD
  Date: Fri Dec 20 03:29:50 2019 -0500
  1 file changed, 2 deletions(-)
  delete mode 100644 newfile

`As you can see, this won’t create a new commit but it will essentially modify the most recent commit in order to include your changes.

Remove Specific File from Git Commit

In some cases, you don’t want all the files to be staged again: you only one to modify one very specific file of your repository.

In order to remove a specific file from a Git commit, use the “git reset” command with the “–soft” option, specify the commit before HEAD and the file that you want to remove.

$ git reset HEAD^ -- <file>

When you are done with the modifications, your file will be back in the staging area.

First, you can choose to remove the file from the staging area by using the “git reset” command and specify that you want to reset from the HEAD.

$ git reset HEAD <file>

Note: it does not mean that you will lose the changes on this file, just that the file will be removed from the staging area.

If you want to completely remove the file from the index, you will have to use the “git rm” command with the “–cached” option.

$ git reset HEAD <file>

In order to make sure that your file was correctly removed from the staging area, use the “git ls-files” command to list files that belong to the index.

$ git ls-files

When you are completely done with your modifications, you can amend the commit you removed the files from by using the “git commit” command with the “–amend” option.

$ git commit --amend

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

What does the following Oracle error mean: invalid column index

I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.

How to get the PID of a process by giving the process name in Mac OS X ?

You can use the pgrep command like in the following example

$ pgrep Keychain\ Access
44186

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

Is there any way to change input type="date" format?

i found a way to change format ,its a tricky way, i just changed the appearance of the date input fields using just a CSS code.

_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {_x000D_
  color: #fff;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-year-field{_x000D_
  position: absolute !important;_x000D_
  border-left:1px solid #8c8c8c;_x000D_
  padding: 2px;_x000D_
  color:#000;_x000D_
  left: 56px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-month-field{_x000D_
  position: absolute !important;_x000D_
  border-left:1px solid #8c8c8c;_x000D_
  padding: 2px;_x000D_
  color:#000;_x000D_
  left: 26px;_x000D_
}_x000D_
_x000D_
_x000D_
input[type="date"]::-webkit-datetime-edit-day-field{_x000D_
  position: absolute !important;_x000D_
  color:#000;_x000D_
  padding: 2px;_x000D_
  left: 4px;_x000D_
  _x000D_
}
_x000D_
<input type="date" value="2019-12-07">
_x000D_
_x000D_
_x000D_

What is class="mb-0" in Bootstrap 4?

Bootstrap has a wide range of responsive margin and padding utility classes. They work for all breakpoints:

xs (<=576px), sm (>=576px), md (>=768px), lg (>=992px) or xl (>=1200px))

The classes are used in the format:

{property}{sides}-{size} for xs & {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

m - sets margin

p - sets padding


t - sets margin-top or padding-top

b - sets margin-bottom or padding-bottom

l - sets margin-left or padding-left

r - sets margin-right or padding-right

x - sets both padding-left and padding-right or margin-left and margin-right

y - sets both padding-top and padding-bottom or margin-top and margin-bottom

blank - sets a margin or padding on all 4 sides of the element


0 - sets margin or padding to 0

1 - sets margin or padding to .25rem (4px if font-size is 16px)

2 - sets margin or padding to .5rem (8px if font-size is 16px)

3 - sets margin or padding to 1rem (16px if font-size is 16px)

4 - sets margin or padding to 1.5rem (24px if font-size is 16px)

5 - sets margin or padding to 3rem (48px if font-size is 16px)

auto - sets margin to auto

See more at Bootstrap 4.5 - Spacing

Read more in w3schools

Enum Naming Convention - Plural

Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0. It makes more sense to say Version.1_0 since there is only one 1_0 Version.

A div with auto resize when changing window width\height

In this scenario, the outer <div> has a width and height of 90%. The inner div> has a width of 100% of its parent. Both scale when re-sizing the window.

HTML

<div>
    <div>Hello there</div>
</div>

CSS

html, body {
    width: 100%;
    height: 100%;
}

body > div {
    width: 90%;
    height: 100%;
    background: green;
}

body > div > div {
    width: 100%;
    background: red;
}

Demo

Try before buy

How to properly add include directories with CMake

CMake is more like a script language if comparing it with other ways to create Makefile (e.g. make or qmake). It is not very cool like Python, but still.

There are no such thing like a "proper way" if looking in various opensource projects how people include directories. But there are two ways to do it.

  1. Crude include_directories will append a directory to the current project and all other descendant projects which you will append via a series of add_subdirectory commands. Sometimes people say that such approach is legacy.

  2. A more elegant way is with target_include_directories. It allows to append a directory for a specific project/target without (maybe) unnecessary inheritance or clashing of various include directories. Also allow to perform even a subtle configuration and append one of the following markers for this command.

PRIVATE - use only for this specified build target

PUBLIC - use it for specified target and for targets which links with this project

INTERFACE -- use it only for targets which links with the current project

PS:

  1. Both commands allow to mark a directory as SYSTEM to give a hint that it is not your business that specified directories will contain warnings.

  2. A similar answer is with other pairs of commands target_compile_definitions/add_definitions, target_compile_options/CMAKE_C_FLAGS

How do I join two SQLite tables in my Android application?

You need rawQuery method.

Example:

private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";

db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});

Use ? bindings instead of putting values into raw sql query.

How to tell if a connection is dead in python

Short answer:

use a non-blocking recv(), or a blocking recv() / select() with a very short timeout.

Long answer:

The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.

TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, close.

Of these, the timeout can not really be detected, TCP might only tell you the time has not expired yet. But even if it told you that, the time might still expire right after.

Also remember that using shutdown() either you or your peer (the other end of the connection) may close only the incoming byte stream, and keep the outgoing byte stream running, or close the outgoing stream and keep the incoming one running.

So strictly speaking, you want to check if the read stream is closed, or if the write stream is closed, or if both are closed.

Even if the connection was "dropped", you should still be able to read any data that is still in the network buffer. Only after the buffer is empty will you receive a disconnect from recv().

Checking if the connection was dropped is like asking "what will I receive after reading all data that is currently buffered ?" To find that out, you just have to read all data that is currently bufferred.

I can see how "reading all buffered data", to get to the end of it, might be a problem for some people, that still think of recv() as a blocking function. With a blocking recv(), "checking" for a read when the buffer is already empty will block, which defeats the purpose of "checking".

In my opinion any function that is documented to potentially block the entire process indefinitely is a design flaw, but I guess it is still there for historical reasons, from when using a socket just like a regular file descriptor was a cool idea.

What you can do is:

  • set the socket to non-blocking mode, but than you get a system-depended error to indicate the receive buffer is empty, or the send buffer is full
  • stick to blocking mode but set a very short socket timeout. This will allow you to "ping" or "check" the socket with recv(), pretty much what you want to do
  • use select() call or asyncore module with a very short timeout. Error reporting is still system-specific.

For the write part of the problem, keeping the read buffers empty pretty much covers it. You will discover a connection "dropped" after a non-blocking read attempt, and you may choose to stop sending anything after a read returns a closed channel.

I guess the only way to be sure your sent data has reached the other end (and is not still in the send buffer) is either:

  • receive a proper response on the same socket for the exact message that you sent. Basically you are using the higher level protocol to provide confirmation.
  • perform a successful shutdow() and close() on the socket

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket.send() and if it returns 0 you can no longer send data on that socket. But if it returns non-zero, you have already sent something, good luck with that :)

Also here I have not considered OOB (out-of-band) socket data here as a means to approach your problem, but I think OOB was not what you meant.

Powershell script to locate specific file/file name?

In findFileByFilename.ps1 I have:

# https://stackoverflow.com/questions/3428044/powershell-script-to-locate-specific-file-file-name
$filename = Read-Host 'What is the filename to find?'
gci . -recurse -filter $filename -file -ErrorAction SilentlyContinue
# tested works from pwd recursively.

This works great for me. I understand it.

I put it in a folder on my PATH.

I invoke it with:

> findFileByFilename.ps1

Maven error :Perhaps you are running on a JRE rather than a JDK?

Here's my automatic solution...

This will follow your javac executable's symlink (setup by yum and/or alternatives --config java) backwards to find the JAVA_HOME. (Toss this in your in your /etc/profile):

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac$::')

If you wanted a stable path (refreshed on boot) launch something like this:

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac$::')
ln -sfn "${JAVA_HOME}" /usr/lib/jvm/jdk-current

I'm kinda shocked the latter still isn't baked into alternatives.

lexical or preprocessor issue file not found occurs while archiving?

This happened to me after I renamed a file. For some reason it was still looking for the file with the old name. What I did was create the file that it was complaining about and added to the project. Then I did a Project->clean, then Project->Build and verified the error was gone. Then I selected the newly added files and deleted them. This removed all references and I no longer see the error.

How can I adjust DIV width to contents

One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

Get pandas.read_csv to read empty values as empty string instead of nan

I added a ticket to add an option of some sort here:

https://github.com/pydata/pandas/issues/1450

In the meantime, result.fillna('') should do what you want

EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values, empty strings will stay empty strings in the result

How to list all the files in a commit?

Simplest form:

git show --stat (hash)

That's easier to remember and it will give you all the information you need.

If you really want only the names of the files you could add the --name-only option.

git show --stat --name-only (hash)

What's the difference between Cache-Control: max-age=0 and no-cache?

max-age
    When an intermediate cache is forced, by means of a max-age=0 directive, to revalidate 
its own cache entry, and the client has supplied its own validator in the request, the 
supplied validator might differ from the validator currently stored with the cache entry. 
In this case, the cache MAY use either validator in making its own request without 
affecting semantic transparency. 

    However, the choice of validator might affect performance. The best approach is for the 
intermediate cache to use its own validator when making its request. If the server replies 
with 304 (Not Modified), then the cache can return its now validated copy to the client 
with a 200 (OK) response. If the server replies with a new entity and cache validator, 
however, the intermediate cache can compare the returned validator with the one provided in 
the client's request, using the strong comparison function. If the client's validator is 
equal to the origin server's, then the intermediate cache simply returns 304 (Not 
Modified). Otherwise, it returns the new entity with a 200 (OK) response. 

    If a request includes the no-cache directive, it SHOULD NOT include min-fresh, 
max-stale, or max-age. 

courtesy: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4

Don't accept this as answer - I will have to read it to understand the true usage of it :)

Set width of a "Position: fixed" div relative to parent div

fixed position is a bit tricky (indeed impossible), but position: sticky is doing the trick beautifully:

<div class='container'>
  <header>This is the header</header>
  <section>
    ... long lorem ipsum
  </section>
</div>


body {
  text-align: center;  
}

.container {
  text-align: left;
  max-width: 30%;
  margin: 0 auto;
}


header {
  line-height: 2rem;
  outline: 1px solid red;
  background: #fff;
  padding: 1rem;

  position: sticky;
  top: 0;
}

see the codepen sample

Error "The connection to adb is down, and a severe error has occurred."

AndroidSDK ? Platform Tools ? Kill did not work.

But after restarting my computer, it worked.

Python Database connection Close

According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.

To close your connection when you call close() you should set pooling to False:

import pyodbc

pyodbc.pooling = False

Regular Expression to select everything before and up to a particular text

((\n.*){0,3})(.*)\W*\.txt

This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Replace characters from a column of a data frame R

If your variable data1$c is a factor, it's more efficient to change the labels of the factor levels than to create a new vector of characters:

levels(data1$c) <- sub("_", "-", levels(data1$c))


            a b   c
1  0.73945260 a A-B
2  0.75998815 b A-B
3  0.19576725 c A-B
4  0.85932140 d A-B
5  0.80717115 e A-C
6  0.09101492 f A-C
7  0.10183586 g A-C
8  0.97742424 h A-C
9  0.21364521 i A-C
10 0.02389782 j A-C

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

NameError: name 'reduce' is not defined in Python

You can add

from functools import reduce

before you use the reduce.

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

How to install mysql-connector via pip

For Windows

pip install mysql-connector

For Ubuntu /Linux

sudo apt-get install python3-pymysql

Calculate difference between two dates (number of days)?

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    DateTime d = Calendar1.SelectedDate;
    // int a;
    TextBox2.Text = d.ToShortDateString();
    string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
    string s1 =  Convert.ToDateTime(Label7.Text).ToShortDateString();
    DateTime dt = Convert.ToDateTime(s).Date;
    DateTime dt1 = Convert.ToDateTime(s1).Date;
    if (dt <= dt1)
    {
        Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
    }
    else
    {
        string diff = dt.Subtract(dt1).ToString();
        Response.Write(diff);
        Label18.Text = diff;
        Session["diff"] = Label18.Text;
    }
}   

Javascript: open new page in same window

<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

How to set label size in Bootstrap

In Bootstrap 3 they do not have separate classes for different styles of labels.

http://getbootstrap.com/components/

However, you can customize bootstrap classes that way. In your css file

.lb-sm {
  font-size: 12px;
}

.lb-md {
  font-size: 16px;
}

.lb-lg {
  font-size: 20px;
}

Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
_x000D_
_x000D_

They might add size classes for labels in future Bootstrap versions.

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Is it possible to display inline images from html in an Android TextView?

KOTLIN

There is also the possibility to use sufficientlysecure.htmltextview.HtmlTextView

Use like below in gradle files:

Project gradle file:

repositories {
    jcenter()
}

App gradle file:

dependencies {
implementation 'org.sufficientlysecure:html-textview:3.9'
}

Inside xml file replace your textView with:

<org.sufficientlysecure.htmltextview.HtmlTextView
      android:id="@+id/allNewsBlockTextView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="2dp"
      android:textColor="#000"
      android:textSize="18sp"
      app:htmlToString="@{detailsViewModel.selectedText}" />

Last line above is if you use Binding adapters where the code will be like:

@BindingAdapter("htmlToString")
fun bindTextViewHtml(textView: HtmlTextView, htmlValue: String) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setHtml(
        htmlValue,
        HtmlHttpImageGetter(textView, "n", true)
    );
    } else {
        textView.setHtml(
        htmlValue,
        HtmlHttpImageGetter(textView, "n", true)
        );
    }
}

More info from github page and a big thank you to the authors!!!!!

How can I add new item to the String array?

You can't. A Java array has a fixed length. If you need a resizable array, use a java.util.ArrayList<String>.

BTW, your code is invalid: you don't initialize the array before using it.

How do I make background-size work in IE?

you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:

.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}

Postgres manually alter sequence

Use select setval('payments_id_seq', 21, true);

setval contains 3 parameters:

  • 1st parameter is sequence_name
  • 2nd parameter is Next nextval
  • 3rd parameter is optional.

The use of true or false in 3rd parameter of setval is as follows:

SELECT setval('payments_id_seq', 21);           // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true);     // Same as above 
SELECT setval('payments_id_seq', 21, false);    // Next nextval will return 21

The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:

SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;

where table_name is the name of the table, id is the primary key of the table

Capture keyboardinterrupt in Python without try-except

If someone is in search for a quick minimal solution,

import signal

# The code which crashes program on interruption

signal.signal(signal.SIGINT, call_this_function_if_interrupted)

# The code skipped if interrupted

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

How can I get the executing assembly version?

Product Version may be preferred if you're using versioning via GitVersion or other versioning software.

To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:

using System.Diagnostics;
using System.Reflection;

//...

var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion

enter image description here

c# replace \" characters

Replace(@"\""", "")

You have to use double-doublequotes to escape double-quotes within a verbatim string.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

Convert RGBA PNG to RGB with PIL

Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG support for sorl thumbnails.

from PIL import Image

png = Image.open(object.logo.path)
png.load() # required for png.split()

background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

background.save('foo.jpg', 'JPEG', quality=80)

Result @80%

enter image description here

Result @ 50%
enter image description here

Concatenating variables and strings in React

exampleData=

        const json1 = [
            {id: 1, test: 1},
            {id: 2, test: 2},
            {id: 3, test: 3},
            {id: 4, test: 4},
            {id: 5, test: 5}
        ];

        const json2 = [
            {id: 3, test: 6},
            {id: 4, test: 7},
            {id: 5, test: 8},
            {id: 6, test: 9},
            {id: 7, test: 10}
        ];

example1=


        const finalData1 = json1.concat(json2).reduce(function (index, obj) {
            index[obj.id] = Object.assign({}, obj, index[obj.id]);
            return index;
        }, []).filter(function (res, obj) {
            return obj;
        });

example2=

        let hashData = new Map();

        json1.concat(json2).forEach(function (obj) {
            hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
        });

        const finalData2 = Array.from(hashData.values());

I recommend second example , it is faster.

How do I get a UTC Timestamp in JavaScript?

I actually think Date values in js are far better than say the C# DateTime objects. The C# DateTime objects have a Kind property, but no strict underlying time zone as such, and time zone conversions are difficult to track if you are converting between two non UTC and non local times. In js, all Date values have an underlying UTC value which is passed around and known regardless of the offest or time zone conversions that you do. My biggest complaint about the Date object is the amount of undefined behaviour that browser implementers have chosen to include, which can confuse people who attack dates in js with trial and error than reading the spec. Using something like iso8601.js solves this varying behaviour by defining a single implementation of the Date object.

By default, the spec says you can create dates with an extended ISO 8601 date format like

var someDate = new Date('2010-12-12T12:00Z');

So you can infer the exact UTC time this way.

When you want to pass the Date value back to the server you would call

someDate.toISOString();

or if you would rather work with a millisecond timestamp (number of milliseconds from the 1st January 1970 UTC)

someDate.getTime();

ISO 8601 is a standard. You can't be confused about what a date string means if you include the date offset. What this means for you as a developer is that you never have to deal with local time conversions yourself. The local time values exist purely for the benefit of the user, and date values by default display in their local time. All the local time manipulations allow you to display something sensible to the user and to convert strings from user input. It's good practice to convert to UTC as soon as you can, and the js Date object makes this fairly trivial.

On the downside there is not a lot of scope for forcing the time zone or locale for the client (that I am aware of), which can be annoying for website-specific settings, but I guess the reasoning behind this is that it's a user configuration that shouldn't be touched.

So, in short, the reason there isn't a lot of native support for time zone manipulation is because you simply don't want to be doing it.

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

convert json ipython notebook(.ipynb) to .py file

  1. Go to https://jupyter.org/
  2. click on nbviewer
  3. Enter the location of your file and render it.
  4. Click on view as code (shown as < />)

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

If you still need to use the HTTP Module you need to configure it (.NET 4.0 framework) as follows:

<system.webServer>
   <modules runAllManagedModulesForAllRequests="true">
       <add name="MyModule" type="[Namespace].[Class], [assembly]"/>
   </modules>
   <validation validateIntegratedModeConfiguration="false"/>
</system.webServer>

How would I check a string for a certain letter in Python?

in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

In this case string is nothing but a list of characters:

dog = "xdasds"
if "x" in dog:
     print "Yes!"

You can check a substring too:

>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>> 
>>> 
>>> 'xa' in "xdasds"
False

Think collection:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>> 

You can also test the set membership over user defined classes.

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

How to print color in console using System.out.println?

You could do this using ANSI escape sequences. I've actually put together this class in Java for anyone that would like a simple workaround for this. It allows for more than just color codes.

https://gist.github.com/nathan-fiscaletti/9dc252d30b51df7d710a

(Ported from: https://github.com/nathan-fiscaletti/ansi-util)

Example Use:

StringBuilder sb = new StringBuilder();

System.out.println(
    sb.raw("Hello, ")
      .underline("John Doe")
      .resetUnderline()
      .raw(". ")
      .raw("This is ")
      .color16(StringBuilder.Color16.FG_RED, "red")
      .raw(".")
);

How to write to Console.Out during execution of an MSTest test

Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.

[TestMethod]
public void TestMethod1()
{
    Debug.WriteLine("Time {0}", DateTime.Now);
    System.Threading.Thread.Sleep(30000);
    Debug.WriteLine("Time {0}", DateTime.Now);
}

Output

enter image description here

Character Limit in HTML

There are 2 main solutions:

The pure HTML one:

<input type="text" id="Textbox" name="Textbox" maxlength="10" />

The JavaScript one (attach it to a onKey Event):

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.

how to kill hadoop jobs

Depending on the version, do:

version <2.3.0

Kill a hadoop job:

hadoop job -kill $jobId

You can get a list of all jobId's doing:

hadoop job -list

version >=2.3.0

Kill a hadoop job:

yarn application -kill $ApplicationId

You can get a list of all ApplicationId's doing:

yarn application -list

int *array = new int[n]; what is this function actually doing?

The new operator is allocating space for a block of n integers and assigning the memory address of that block to the int* variable array.

The general form of new as it applies to one-dimensional arrays appears as follows:

array_var = new Type[desired_size];

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Matrix multiplication using arrays

static int b[][]={{21,21},{22,22}};

static int a[][] ={{1,1},{2,2}};

public static void mul(){
    int c[][] = new int[2][2];

    for(int i=0;i<b.length;i++){
        for(int j=0;j<b.length;j++){
            c[i][j] =0;
        }   
    }

    for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
            for(int k=0;k<b.length;k++){
            c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
            }
        }
    }

    for(int i=0;i<c.length;i++){
        for(int j=0;j<c.length;j++){
            System.out.print(c[i][j]);
        }   
        System.out.println("\n");
    }
}

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

How to get a thread and heap dump of a Java process on Windows that's not running in a console

You could run jconsole (included with Java 6's SDK) then connect to your Java application. It will show you every Thread running and its stack trace.

Easy way of running the same junit test over and over?

With IntelliJ, you can do this from the test configuration. Once you open this window, you can choose to run the test any number of times you want,.

enter image description here

when you run the test, intellij will execute all tests you have selected for the number of times you specified.

Example running 624 tests 10 times: enter image description here

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got the same error, what worked for me is:

  1. Fix references error.
  2. Close Visual Studio.
  3. Delete Packages.
  4. Delete .vs folder.
  5. Run Project Again.
  6. Rebuild Project.

What is the difference between `sorted(list)` vs `list.sort()`?

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

OpenMP set_num_threads() is not working

I was facing the same problem . Solution is given below

Right click on Source Program > Properties > Configuration Properties > C/C++ > Language > Now change Open MP support flag to Yes....

You will get the desired result.

How do I wrap text in a pre tag?

The Best Cross Browser Way worked for me to get line breaks and shows exact code or text: (chrome, internet explorer, Firefox)

CSS:

xmp{ white-space:pre-wrap; word-wrap:break-word; }

HTML:

<xmp> your text or code </xmp>

Bootstrap - Removing padding or margin when screen size is smaller

Heres what I do for Bootstrap 3/4

Use container-fluid instead of container.

Add this to my CSS

@media (min-width: 1400px) {
    .container-fluid{
        max-width: 1400px;
    }   
}

This removes margins below 1400px width screen

How do you install an APK file in the Android emulator?

(TESTED ON MACOS)

The first step is to run the emulator

emulator -avd < avd_name>

then use adb to install the .apk

adb install < path to .apk file>

If adb throws error like APK already exists or something alike. Run the adb shell while emulator is running

adb shell

cd data/app

adb uninstall < apk file without using .apk>

If adb and emulator are commands not found do following

export PATH=$PATH://android-sdk-macosx/platform-tools://android-sdk-macosx/android-sdk-macosx/tools:

For future use put the above line at the end of .bash_profile

vi ~/.bash_profile

Maven does not find JUnit tests to run

In my case we are migration multimodule application to Spring Boot. Unfortunately maven didnt execute all tests anymore in the modules. The naming of the Test Classes didnt change, we are following the naming conventions.

At the end it helped, when I added the dependency surefire-junit47 to the plugin maven-surefire-plugin. But I could not explain, why, it was trial and error:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<dependencies>
  <dependency>
    <groupId>org.apache.maven.surefire</groupId>
    <artifactId>surefire-junit47</artifactId>
    <version>${maven-surefire-plugin.version}</version>
  </dependency>
</dependencies>

Difference between Date(dateString) and new Date(dateString)

You're not getting an "invalid date" error. Rather, the value of temp is "Invalid Date".

Is your date string in a valid format? If you're using Firefox, check Date.parse

In Firefox javascript console:

>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000

I would try a different date string format.

Zebi, are you using Internet Explorer?

Spring MVC @PathVariable with dot (.) is getting truncated

One pretty easy way to work around this issue is to append a trailing slash ...

e.g.:

use :

/somepath/filename.jpg/

instead of:

/somepath/filename.jpg

How to create a windows service from java app

Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.

Require .NET runtime installed.

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.

I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure replaced by $ ./configure --enable-shared (first make sure to delete all the folders and files including the .so files from the previous attempt).

Apparently this works because https://stackoverflow.com/a/13812368/10593190.

How to enable CORS in AngularJs

I had a similar problem and for me it boiled down to adding the following HTTP headers at the response of the receiving end:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

You may prefer not to use the * at the end, but only the domainname of the host sending the data. Like *.example.com

But this is only feasible when you have access to the configuration of the server.

Single vs Double quotes (' vs ")

It makes no difference to the html but if you are generating html dynamically with another programming language then one way may be easier than another.

For example in Java the double quote is used to indicate the start and end of a String, so if you want to include a doublequote within the String you have to escape it with a backslash.

String s = "<a href=\"link\">a Link</a>"

You don't have such a problem with the single quote, therefore use of the single quote makes for more readable code in Java.

String s = "<a href='link'>a Link</a>"

Especially if you have to write html elements with many attributes.(Note I usually use a library such as jhtml to write html in Java, but not always practical to do so)

How to post data to specific URL using WebClient in C#

There is a built in method called UploadValues that can send HTTP POST (or any kind of HTTP methods) AND handles the construction of request body (concatenating parameters with "&" and escaping characters by url encoding) in proper form data format:

using(WebClient client = new WebClient())
{
    var reqparm = new System.Collections.Specialized.NameValueCollection();
    reqparm.Add("param1", "<any> kinds & of = ? strings");
    reqparm.Add("param2", "escaping is already handled");
    byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
    string responsebody = Encoding.UTF8.GetString(responsebytes);
}

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Does the class org.apache.maven.shared.filtering.MavenFilteringException exist in file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar?

The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.

I'm also wondering where the version 1.0-beta-2 comes from; I have 1.0 on my disk. Try version 2.3 of the WAR plugin.

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

HTTP Error 404 when running Tomcat from Eclipse

I had this or a similar problem after installing Tomcat.

The other answers didn't quite work, but got me on the right path. I answered this at https://stackoverflow.com/a/20762179/3128838 after discovering a YouTube video showing the exact problem I was having.

How to convert datetime to integer in python

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

def to_integer(dt_time):
    return 10000*dt_time.year + 100*dt_time.month + dt_time.day

E.g.

In [1]: import datetime

In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
:    return 10000*dt_time.year + 100*dt_time.month + dt_time.day
:    # Or take the appropriate chars from a string date representation.
:--

In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

Simple C example of doing an HTTP POST and consuming the response

A message has a header part and a message body separated by a blank line. The blank line is ALWAYS needed even if there is no message body. The header starts with a command and has additional lines of key value pairs separated by a colon and a space. If there is a message body, it can be anything you want it to be.

Lines in the header and the blank line at the end of the header must end with a carraige return and linefeed pair (see HTTP header line break style) so that's why those lines have \r\n at the end.

A URL has the form of http://host:port/path?query_string

There are two main ways of submitting a request to a website:

  • GET: The query string is optional but, if specified, must be reasonably short. Because of this the header could just be the GET command and nothing else. A sample message could be:

    GET /path?query_string HTTP/1.0\r\n
    \r\n
    
  • POST: What would normally be in the query string is in the body of the message instead. Because of this the header needs to include the Content-Type: and Content-Length: attributes as well as the POST command. A sample message could be:

    POST /path HTTP/1.0\r\n
    Content-Type: text/plain\r\n
    Content-Length: 12\r\n
    \r\n
    query_string
    

So, to answer your question: if the URL you are interested in POSTing to is http://api.somesite.com/apikey=ARG1&command=ARG2 then there is no body or query string and, consequently, no reason to POST because there is nothing to put in the body of the message and so nothing to put in the Content-Type: and Content-Length:

I guess you could POST if you really wanted to. In that case your message would look like:

POST /apikey=ARG1&command=ARG2 HTTP/1.0\r\n
\r\n

So to send the message the C program needs to:

  • create a socket
  • lookup the IP address
  • open the socket
  • send the request
  • wait for the response
  • close the socket

The send and receive calls won't necessarily send/receive ALL the data you give them - they will return the number of bytes actually sent/received. It is up to you to call them in a loop and send/receive the remainder of the message.

What I did not do in this sample is any sort of real error checking - when something fails I just exit the program. Let me know if it works for you:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        80;
    char *host =        "api.somesite.com";
    char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }

    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]);
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    return 0;
}

Like the other answer pointed out, 4096 bytes is not a very big response. I picked that number at random assuming that the response to your request would be short. If it can be big you have two choices:

  • read the Content-Length: header from the response and then dynamically allocate enough memory to hold the whole response.
  • write the response to a file as the pieces arrive

Additional information to answer the question asked in the comments:

What if you want to POST data in the body of the message? Then you do need to include the Content-Type: and Content-Length: headers. The Content-Length: is the actual length of everything after the blank line that separates the header from the body.

Here is a sample that takes the following command line arguments:

  • host
  • port
  • command (GET or POST)
  • path (not including the query data)
  • query data (put into the query string for GET and into the body for POST)
  • list of headers (Content-Length: is automatic if using POST)

So, for the original question you would run:

a.out api.somesite.com 80 GET "/apikey=ARG1&command=ARG2"

And for the question asked in the comments you would run:

a.out api.somesite.com 80 POST / "name=ARG1&value=ARG2" "Content-Type: application/x-www-form-urlencoded"

Here is the code:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    int i;

    /* first where are we going to send it? */
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total, message_size;
    char *message, response[4096];

    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }

    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(argv[4]);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
        message_size+=strlen("%s %s HTTP/1.0\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(argv[4]);                         /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }

    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/",                 /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"");                 /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/");                /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            strlen(argv[4])>0?argv[4]:"/");                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }

    /* What are we going to send? */
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    free(message);
    return 0;
}

How do I set up curl to permanently use a proxy?

You can make a alias in your ~/.bashrc file :

alias curl="curl -x <proxy_host>:<proxy_port>"

Another solution is to use (maybe the better solution) the ~/.curlrc file (create it if it does not exist) :

proxy = <proxy_host>:<proxy_port>

React img tag issue with url and class

var Hello = React.createClass({
    render: function() {
      return (
        <div className="divClass">
           <img src={this.props.url} alt={`${this.props.title}'s picture`}  className="img-responsive" />
           <span>Hello {this.props.name}</span>
        </div>
      );
    }
});

assign function return value to some variable using javascript

AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status is undefined when it is returned.

Effectively, your code works as follows:

function doSomething(someargums) {
     return status;
}

var response = doSomething();

And then some time later, your AJAX request is completing; but it's already too late

You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.

Where you previously may have had

var response = doSomething();

alert(response);

You should do:

function doSomething() {  
    $.ajax({
           url:'action.php',
           type: "POST",
           data: dataString,
           success: function (txtBack) { 
            alert(txtBack);
           })
    }); 
};

dropzone.js - how to do something after ALL files are uploaded

The accepted answer is not necessarily correct. queuecomplete will be called even when the selected file is larger than the max file size.

The proper event to use is successmultiple or completemultiple.

Reference: http://www.dropzonejs.com/#event-successmultiple

How to calculate the bounding box for a given lat/lng location?

Here is an simple implementation using javascript which is based on the conversion of latitude degree to kms where 1 degree latitude ~ 111.2 km.

I am calculating bounds of the map from a given latitude, longitude and radius in kilometers.

function getBoundsFromLatLng(lat, lng, radiusInKm){
     var lat_change = radiusInKm/111.2;
     var lon_change = Math.abs(Math.cos(lat*(Math.PI/180)));
     var bounds = { 
         lat_min : lat - lat_change,
         lon_min : lng - lon_change,
         lat_max : lat + lat_change,
         lon_max : lng + lon_change
     };
     return bounds;
}

CSS How to set div height 100% minus nPx

Here is a working css, tested under Firefox / IE7 / Safari / Chrome / Opera.

* {margin:0px;padding:0px;overflow:hidden}
div {position:absolute}
div#header {top:0px;left:0px;right:0px;height:60px}
div#wrapper {top:60px;left:0px;right:0px;bottom:0px;}
div#left {top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}
div#right {top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}

"overflow-y" is not w3c-approved, but every major browser supports it. Your two divs #left and #right will display a vertical scrollbar if their content is too high.

For this to work under IE7, you have to trigger the standards-compliant mode by adding a DOCTYPE :

_x000D_
_x000D_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"_x000D_
            "http://www.w3.org/TR/html4/strict.dtd">_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
<style type="text/css">_x000D_
 *{margin:0px;padding:0px;overflow:hidden}_x000D_
 div{position:absolute}_x000D_
 div#header{top:0px;left:0px;right:0px;height:60px}_x000D_
 div#wrapper{top:60px;left:0px;right:0px;bottom:0px;}_x000D_
 div#left{top:0px;bottom:0px;left:0px;width:50%;overflow-y:auto}_x000D_
 div#right{top:0px;bottom:0px;right:0px;width:50%;overflow-y:auto}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div id="header"></div>_x000D_
<div id="wrapper">_x000D_
  <div id="left"><div style="height:1000px">high content</div></div>_x000D_
  <div id="right"></div>_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to convert number to words in java

import java.util.*;

public class NumberToWord {
    public void numberToword(int n, String ch) {
        String one[] = {" ", " one", " two", " three", " four", " five", " six", " seven", " eight", " Nine", " ten", " eleven", " twelve", " thirteen", " fourteen", "fifteen", " sixteen", " seventeen", " eighteen", " nineteen"
        };
        String ten[] = {" ", " ", " twenty", " thirty", " forty", " fifty", " sixty", "seventy", " eighty", " ninety"};
        if (n > 19) {
            System.out.print(ten[n / 10] + " " + one[n % 10]);
        } else {
            System.out.print(one[n]);
        }
        if (n > 0) {
            System.out.print(ch);
        }
    }
    public static void main(String[] args) {
        int n = 0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter an integer number: ");
        n = s.nextInt();
        if (n <= 0) {
            System.out.print("Enter numbers greater than 0");
        } else {
            NumberToWord a = new NumberToWord();
            System.out.print("After conversion number in words is :");
            a.numberToword((n / 1000000000), " Hundred");
            a.numberToword((n / 10000000) % 100, " crore");
            a.numberToword(((n / 100000) % 100), " lakh");
            a.numberToword(((n / 1000) % 100), " thousand");
            a.numberToword(((n / 100) % 10), " hundred");
            a.numberToword((n % 100), " ");
        }
    }
}

Input type "number" won't resize

Rather than set the length, set the max and min values for the number input.

The input box then resizes to fit the longest valid value.

If you want to allow a 3-digit number then set 999 as the max

 <input type="number" name="quantity" min="0" max="999">

AngularJs: How to check for changes in file input fields?

No binding support for File Upload control

https://github.com/angular/angular.js/issues/1375

<div ng-controller="form-cntlr">
        <form>
             <button ng-click="selectFile()">Upload Your File</button>
             <input type="file" style="display:none" 
                id="file" name='file' onchange="angular.element(this).scope().fileNameChanged(this)" />
        </form>  
    </div>

instead of

 <input type="file" style="display:none" 
    id="file" name='file' ng-Change="fileNameChanged()" />

can you try

<input type="file" style="display:none" 
    id="file" name='file' onchange="angular.element(this).scope().fileNameChanged()" />

Note: this requires the angular application to always be in debug mode. This will not work in production code if debug mode is disabled.

and in your function changes instead of

$scope.fileNameChanged = function() {
   alert("select file");
}

can you try

$scope.fileNameChanged = function() {
  console.log("select file");
}

Below is one working example of file upload with drag drop file upload may be helpful http://jsfiddle.net/danielzen/utp7j/

Angular File Upload Information

URL for AngularJS File Upload in ASP.Net

http://cgeers.com/2013/05/03/angularjs-file-upload/

AngularJs native multi-file upload with progress with NodeJS

http://jasonturim.wordpress.com/2013/09/12/angularjs-native-multi-file-upload-with-progress/

ngUpload - An AngularJS Service for uploading files using iframe

http://ngmodules.org/modules/ngUpload

iOS: Convert UTC NSDate to local Timezone

I write this Method to convert date time to our LocalTimeZone

-Here (NSString *)TimeZone parameter is a server timezone

-(NSString *)convertTimeIntoLocal:(NSString *)defaultTime :(NSString *)TimeZone
{
    NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
    [serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]];
    [serverFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *theDate = [serverFormatter dateFromString:defaultTime];
    NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
    [userFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [userFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *dateConverted = [userFormatter stringFromDate:theDate];
    return dateConverted;
}

Replace Both Double and Single Quotes in Javascript String

You don't escape quotes in regular expressions

this.Vals.replace(/["']/g, "")

Center image horizontally within a div

#artiststhumbnail a img {
    display:block;
    margin:auto;
}

Here's my solution in: http://jsfiddle.net/marvo/3k3CC/2/

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Git: How to rebase to a specific commit?

Use the "onto" option:

git rebase --onto master^ D^ D

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

Open the terminal in visual studio?

New in the most recent version of Visual Studio, there is View --> Terminal, which will open a PowerShell instance as a VS dockable window, rather than a floating PowerShell or cmd instance from the Developer Command Prompt.

View then Terminal

C# event with custom arguments

You declare a delegate for the parameters:

public enum MyEvents { Event1 }

public delegate void MyEventHandler(MyEvents e);

public static event MyEventHandler EventTriggered;

Although all events in the framework takes a parameter that is or derives from EventArgs, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.

How do I make a matrix from a list of vectors in R?

t(sapply(a, '[', 1:max(sapply(a, length))))

where 'a' is a list. Would work for unequal row size

How do I draw a set of vertical lines in gnuplot?

alternatively you can also do this:

p '< echo "x y"' w impulse

x and y are the coordinates of the point to which you draw a vertical bar

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

What is private bytes, virtual bytes, working set?

There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.

Long story short:

if I call

p=malloc(1000);
free(p);

then the Private Bytes reflect only the allocation, not the deallocation.

if I call

p=malloc(>512k);
free(p);

then the Private Bytes correctly reflect the allocation and the deallocation.

How do I convert an existing callback API to promises?

The Q library by kriskowal includes callback-to-promise functions. A method like this:

obj.prototype.dosomething(params, cb) {
  ...blah blah...
  cb(error, results);
}

can be converted with Q.ninvoke

Q.ninvoke(obj,"dosomething",params).
then(function(results) {
});

Redirecting to a page after submitting form in HTML

What you could do is, a validation of the values, for example:

if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.

_x000D_
_x000D_
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");

// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");

// Form
let contactForm = document.getElementById("form");

// Event listener
contactForm.addEventListener("submit", function (e) {
  let messageName = [];
  let messageAddress = [];
  
    if (fullname.value === "" || fullname.value === null) {
    messageName.push("* This field is required");
  }

  if (address.value === "" || address.value === null) {
    messageAddress.push("* This field is required");
  }

  // Statement to shows the errors
  if (messageName.length || messageAddress.length > 0) {
    e.preventDefault();
    errorElement.innerText = messageName;
    errorElementAddress.innerText = messageAddress;
  }
  
   // if the values length is filled and it's greater than 2 then redirect to this page
    if (
    (fullname.value.length > 2,
    address.value.length > 2)
  ) {
    e.preventDefault();
    window.location.assign("https://www.google.com");
  }

});
_x000D_
.error {
  color: #000;
}

.input-container {
  display: flex;
  flex-direction: column;
  margin: 1rem auto;
}
_x000D_
<html>
  <body>
    <form id="form" method="POST">
    <div class="input-container">
    <label>Full name:</label>
      <input type="text" id="fullname" name="fullname">
      <div class="error" id="name_error"></div>
      </div>
      
      <div class="input-container">
      <label>Address:</label>
      <input type="text" id="address" name="address">
      <div class="error" id="address_error"></div>
      </div>
      <button type="submit" id="submit_button" value="Submit request" >Submit</button>
    </form>
  </body>
</html>
_x000D_
_x000D_
_x000D_

CMD command to check connected USB devices

you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.

Rails: Check output of path helper from console

For Rails 5.2.4.1, I had to

app.extend app._routes.named_routes.path_helpers_module
app.whatever_path

Validate phone number using javascript

/^1?\s?(\([0-9]{3}\)[- ]?|[0-9]{3}[- ]?)[0-9]{3}[- ]?[0-9]{4}$/

This will validate all US style numbers, with or without the 1, and with or without parenthesis on area code(but if used, used properly. I.E. (902-455-4555 will not work since there is no closing parenthesis. it also allows for either - or a space between sets if wanted.) It will work for the examples provided by op.

How can I build XML in C#?

It depends on the scenario. XmlSerializer is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, XDocument, etc. are also very friendly. If the size is very large, then XmlWriter is your friend.

For an XDocument example:

Console.WriteLine(
    new XElement("Foo",
        new XAttribute("Bar", "some & value"),
        new XElement("Nested", "data")));

Or the same with XmlDocument:

XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);

If you are writing a large stream of data, then any of the DOM approaches (such as XmlDocument/XDocument, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from CSV, you might consider XmlWriter; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):

XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();

Finally, via XmlSerializer:

[Serializable]
public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
    public string Nested { get; set; }
}
...
Foo foo = new Foo
{
    Bar = "some & value",
    Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);

This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with XmlSerializer is that it doesn't like to serialize immutable types : everything must have a public getter and setter (unless you do it all yourself by implementing IXmlSerializable, in which case you haven't gained much by using XmlSerializer).

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

How to run code after some delay in Flutter?

import 'dart:async';   
Timer timer;

void autoPress(){
  timer = new Timer(const Duration(seconds:2),(){
    print("This line will print after two seconds");
 });
}

autoPress();

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

For me it was a Firewall issue.

First you have to add the port (such as 1444 and maybe 1434) but also

C:\Program Files (x86)\Microsoft SQL Server\90\Shared\sqlbrowser.exe

and

%ProgramFiles%\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\Binn\SQLAGENT.EXE

The second time I got this issue is when I came back to the firewall, the paths were not correct and I needed to update form 12 to 13! Simply clicking on browse in the Programs and Services tab helped to realise this.

Finally, try running the command

EXEC xp_readerrorlog 0,1,"could not register the Service Principal Name",Null

For me, it returned the error reason

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

Fastest way to serialize and deserialize .NET objects

Yet another serializer out there that claims to be super fast is netserializer.

The data given on their site shows performance of 2x - 4x over protobuf, I have not tried this myself, but if you are evaluating various options, try this as well

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

Is there a better alternative than this to 'switch on type'?

Should work with

case type _:

like:

int i = 1;
bool b = true;
double d = 1.1;
object o = i; // whatever you want

switch (o)
{
    case int _:
        Answer.Content = "You got the int";
        break;
    case double _:
        Answer.Content = "You got the double";
        break;
    case bool _:
        Answer.Content = "You got the bool";
        break;
}

How to set JAVA_HOME for multiple Tomcat instances?

For Debian distro we can override the setting via defaults

/etc/default/tomcat6

Set the JAVA_HOME pointing to the java version you want.

JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64

Facebook Graph API error code list

I was looking for the same thing and I just found this list

https://developers.facebook.com/docs/reference/api/errors/

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

You will have to edit 2 files - 1. httpd-vhosts.conf & 2. httpd-xampp.conf

NOTE : Make sure u backup files ( httpd-xampp.conf ) and ( httpd-vhosts.conf ) , Both Files are located in Drive:\xampp\apache\conf\extra

Open httpd-vhosts.conf file and in the bottom of the file change it

<VirtualHost *:80>
DocumentRoot “E:/xampp/htdocs/”
ServerName localhost
<Directory E:/xampp/htdocs/>.
Require all granted 
</Directory>
</VirtualHost>

Here E:/xampp is my project workspace, you can change it as per your settings

and Second Change is on httpd-xampp.conf file and in the bottom of the file change it

#
# New XAMPP security concept
#
<LocationMatch “^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))”>
Order deny,allow
Allow from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

How to measure elapsed time in Python?

Here is a tiny timer class that returns "hh:mm:ss" string:

class Timer:
  def __init__(self):
    self.start = time.time()

  def restart(self):
    self.start = time.time()

  def get_time_hhmmss(self):
    end = time.time()
    m, s = divmod(end - self.start, 60)
    h, m = divmod(m, 60)
    time_str = "%02d:%02d:%02d" % (h, m, s)
    return time_str

Usage:

# Start timer
my_timer = Timer()

# ... do something

# Get time string:
time_hhmmss = my_timer.get_time_hhmmss()
print("Time elapsed: %s" % time_hhmmss )

# ... use the timer again
my_timer.restart()

# ... do something

# Get time:
time_hhmmss = my_timer.get_time_hhmmss()

# ... etc

phpMyAdmin + CentOS 6.0 - Forbidden

Non of the above mentioned solutions worked for me. Below is what finally worked:

#yum update
#yum install phpmyadmin

Be advised, phpmyadmin was working a few hours earlier. I don't know what happened.

After this, going to the browser, I got an error that said ./config.inic.php can't be accessed

#cd /usr/share/phpmyadmin/
#stat -c %a config.inic.php
#640
#chmod 644 config.inic.php

This shows that the file permissions were 640, then I changed them to 644. Finially, it worked.

Remember to restart httpd.

#service httpd restart

Android Google Maps API V2 Zoom to Current Location

    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

                CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);

        }
    });

Initialize 2D array

How about something like this:

for (int row = 0; row < 3; row ++)
    for (int col = 0; col < 3; col++)
        table[row][col] = (char) ('1' + row * 3 + col);

The following complete Java program:

class Test {
    public static void main(String[] args) {
        char[][] table = new char[3][3];
        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                table[row][col] = (char) ('1' + row * 3 + col);

        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                System.out.println (table[row][col]);
    }
}

outputs:

1
2
3
4
5
6
7
8
9

This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from '0').

The expression '1' + row * 3 + col (where you vary row and col between 0 and 2 inclusive) simply gives you a character from 1 to 9.

Obviously, this won't give you the character 10 (since that's two characters) if you go further but it works just fine for the 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:

String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
    for (int col = 0; col < 5; col++)
        table[row][col] = String.format("%d", row * 5 + col + 1);

How to Find the Default Charset/Encoding in Java?

I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

TypeError: $(...).on is not a function

This problem is solved, in my case, by encapsulating my jQuery in:

(function($) {
//my jquery 
})(jQuery);

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

Check if object exists in JavaScript

Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:

Things like: exists("blabla"), or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

How to save a spark DataFrame as csv on disk?

I had similar problem. I needed to write down csv file on driver while I was connect to cluster in client mode.

I wanted to reuse the same CSV parsing code as Apache Spark to avoid potential errors.

I checked spark-csv code and found code responsible for converting dataframe into raw csv RDD[String] in com.databricks.spark.csv.CsvSchemaRDD.

Sadly it is hardcoded with sc.textFile and the end of relevant method.

I copy-pasted that code and removed last lines with sc.textFile and returned RDD directly instead.

My code:

/*
  This is copypasta from com.databricks.spark.csv.CsvSchemaRDD
  Spark's code has perfect method converting Dataframe -> raw csv RDD[String]
  But in last lines of that method it's hardcoded against writing as text file -
  for our case we need RDD.
 */
object DataframeToRawCsvRDD {

  val defaultCsvFormat = com.databricks.spark.csv.defaultCsvFormat

  def apply(dataFrame: DataFrame, parameters: Map[String, String] = Map())
           (implicit ctx: ExecutionContext): RDD[String] = {
    val delimiter = parameters.getOrElse("delimiter", ",")
    val delimiterChar = if (delimiter.length == 1) {
      delimiter.charAt(0)
    } else {
      throw new Exception("Delimiter cannot be more than one character.")
    }

    val escape = parameters.getOrElse("escape", null)
    val escapeChar: Character = if (escape == null) {
      null
    } else if (escape.length == 1) {
      escape.charAt(0)
    } else {
      throw new Exception("Escape character cannot be more than one character.")
    }

    val quote = parameters.getOrElse("quote", "\"")
    val quoteChar: Character = if (quote == null) {
      null
    } else if (quote.length == 1) {
      quote.charAt(0)
    } else {
      throw new Exception("Quotation cannot be more than one character.")
    }

    val quoteModeString = parameters.getOrElse("quoteMode", "MINIMAL")
    val quoteMode: QuoteMode = if (quoteModeString == null) {
      null
    } else {
      QuoteMode.valueOf(quoteModeString.toUpperCase)
    }

    val nullValue = parameters.getOrElse("nullValue", "null")

    val csvFormat = defaultCsvFormat
      .withDelimiter(delimiterChar)
      .withQuote(quoteChar)
      .withEscape(escapeChar)
      .withQuoteMode(quoteMode)
      .withSkipHeaderRecord(false)
      .withNullString(nullValue)

    val generateHeader = parameters.getOrElse("header", "false").toBoolean
    val headerRdd = if (generateHeader) {
      ctx.sparkContext.parallelize(Seq(
        csvFormat.format(dataFrame.columns.map(_.asInstanceOf[AnyRef]): _*)
      ))
    } else {
      ctx.sparkContext.emptyRDD[String]
    }

    val rowsRdd = dataFrame.rdd.map(row => {
      csvFormat.format(row.toSeq.map(_.asInstanceOf[AnyRef]): _*)
    })

    headerRdd union rowsRdd
  }

}

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

My colleagues made a URL Rewrite rule, which reduced all URLs to a StaticFileHandler; mapped to a file path at the root of my Application physical folder.

(i.e. an over-aggressive URL rewrite means that my Controllers/Actions were not working)

Check your applications' URL Rewrite rules to confirm they do what you expect.

Pandas How to filter a Series

From pandas version 0.18+ filtering a series can also be done as below

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

pd.Series(test).where(lambda x : x!=1).dropna()

Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements

How to control the line spacing in UILabel

As a quick-dirty-smart-simple workaround:

For UILabels that don't have much lines you can instead use stackViews.

  1. For each line write a new label.
  2. Embed them into a StackView.(select both labels-->Editor-->Embed In -->StackView
  3. Adjust the Spacing of the StackView to your desired amount

Be sure to stack them vertically. This solution also works for custom fonts.

enter image description here

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Override intranet compatibility mode IE8

Had the same problem. It worked by using

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />

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

Following block should work:

    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}

Python convert csv to xlsx

With my library pyexcel,

 $ pip install pyexcel pyexcel-xlsx

you can do it in one command line:

from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2 
import glob


merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")

Each csv will have its own sheet and the name will be their file name.

How do I ignore a directory with SVN?

Solved with Eclipse in the next way:

First of all, do a synchronisation of your folder to the project:

team -> synchronise

In the next view, team view, you can see all resources that you can commit to the SVN server.

So, select the resource folder of the resource that you want to ignore, and then you can ignore it using

team -> add to svn:ignore.

After that, in the confirmation window, do select the first option: "ignore by name".

For instance, If I want to ignore the target folder and their .class resources, I'll do synchronise, and in the synchronise view, I'll select the target folder. After that, I'll select

team->add

to svn:ignore and then I'll confirm the first option in the confirm window.

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

Checking if a variable is an integer in PHP

/!\ Best anwser is not correct, is_numeric() returns true for integer AND all numeric forms like "9.1"

For integer only you can use the unfriendly preg_match('/^\d+$/', $var) or the explicit and 2 times faster comparison :

if ((int) $var == $var) {
    // $var is an integer
}

PS: i know this is an old post but still the third in google looking for "php is integer"

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Cannot lower case button text in android studio

in XML Code
add this line android:textAllCaps="false" like bellow code

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_1_name"
        android:id="@+id/button2"
        android:layout_marginTop="140dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
       ** android:textAllCaps="false" ** />

or

in Java code (programmatically)
add this line to your button setAllCaps(false)

Button btn = (Button) findViewById(R.id.button2);
btn.setAllCaps(false);

How to add one column into existing SQL Table

What about something like:

Alter Table Products
Add LastUpdate varchar(200) null

Do you need something more complex than this?

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

Is it possible to have placeholders in strings.xml for runtime values?

Yes! you can do so without writing any Java/Kotlin code, only XML by using this small library I created, which does so at buildtime, so your app won't be affected by it: https://github.com/LikeTheSalad/android-string-reference

Usage

Your strings:

<resources>
    <string name="app_name">My App Name</string>
    <string name="template_welcome_message">Welcome to ${app_name}</string>
</resources>

The generated string after building:

<!--resolved.xml-->
<resources>
    <string name="welcome_message">Welcome to My App Name</string>
</resources>

How to solve a pair of nonlinear equations using Python?

An alternative to fsolve is root:

import numpy as np
from scipy.optimize import root    

def your_funcs(X):

    x, y = X
    # all RHS have to be 0
    f = [x + y**2 - 4,
         np.exp(x) + x * y - 3]

    return f

sol = root(your_funcs, [1.0, 1.0])
print(sol.x)

This will print

[0.62034452 1.83838393]

If you then check

print(your_funcs(sol.x))

you obtain

[4.4508396968012676e-11, -1.0512035686360832e-11]

confirming that the solution is correct.

How can you strip non-ASCII characters from a string? (in C#)

This is not optimal performance-wise, but a pretty straight-forward Linq approach:

string strippedString = new string(
    yourString.Where(c => c <= sbyte.MaxValue).ToArray()
    );

The downside is that all the "surviving" characters are first put into an array of type char[] which is then thrown away after the string constructor no longer uses it.

1052: Column 'id' in field list is ambiguous

In your SELECT statement you need to preface your id with the table you want to choose it from.

SELECT tbl_names.id, name, section 
FROM tbl_names
INNER JOIN tbl_section 
   ON tbl_names.id = tbl_section.id

OR

SELECT tbl_section.id, name, section 
FROM tbl_names
INNER JOIN tbl_section 
   ON tbl_names.id = tbl_section.id

How to position three divs in html horizontally?

Most easiest way
I can see the question is answered , I'm giving this answer for the ones who is having this question in future


Its not good practise to code inline css , and also ID for all inner div's , always try to use class for styling .Using inline css is a very bad practise if you are trying to be a professional web designer.

here in your question I have given a wrapper class for the parent div and all the inside div's are child div's in css you can call inner div's using nth-child selector.

I want to point few things here

1 - Do not use inline css ( it is very bad practise )

2 - Try to use classes instead of id's because if you give an id you can use it only once, but if you use a class you can use it many times and also you can style of them using that class so you write less code.


codepen link for my answer

https://codepen.io/feizel/pen/JELGyB


_x000D_
_x000D_
            .wrapper{width:100%;}_x000D_
            .box{float:left; height:100px;}_x000D_
            .box:nth-child(1){_x000D_
               width:25%;_x000D_
               background-color:red; _x000D_
        _x000D_
            }_x000D_
            .box:nth-child(2){_x000D_
               width:50%;_x000D_
              background-color:green; _x000D_
            }_x000D_
            .box:nth-child(3){_x000D_
               width:25%;_x000D_
              background-color:yellow; _x000D_
            }
_x000D_
 _x000D_
    <div class="wrapper">_x000D_
        <div class="box">_x000D_
        Left Side Menu_x000D_
        </div>_x000D_
        <div class="box">_x000D_
        Random Content_x000D_
        </div>_x000D_
        <div class="box">_x000D_
        Right Side Menu_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

jQuery Set Cursor Position in Text Area

This worked for me on Safari 5 on Mac OSX, jQuery 1.4:

$("Selector")[elementIx].selectionStart = desiredStartPos; 
$("Selector")[elementIx].selectionEnd = desiredEndPos;

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Where is HttpContent.ReadAsAsync?

I have the same problem, so I simply get JSON string and deserialize to my class:

HttpResponseMessage response = await client.GetAsync("Products");
//get data as Json string 
string data = await response.Content.ReadAsStringAsync();
//use JavaScriptSerializer from System.Web.Script.Serialization
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
//deserialize to your class
products = JSserializer.Deserialize<List<Product>>(data);

WordPress - Check if user is logged in

Use the is_user_logged_in function:

if ( is_user_logged_in() ) {
   // your code for logged in user 
} else {
   // your code for logged out user 
}

Java: How to check if object is null?

drawable.equals(null)

The above line calls the "equals(...)" method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"

But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"

To check whether an object exists and it is not null, use the following

if(drawable == null) {
    ...
    ...
}

In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking

null == null

is valid.

How to check whether an object is a date?

You could check if a function specific to the Date object exists:

function getFormatedDate(date) {
    if (date.getMonth) {
        var month = date.getMonth();
    }
}

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

Open it in a hex editor and make sure that the first three bytes are a UTF8 BOM (EF BB BF)