Programs & Examples On #Web admin

Edit a text file on the console using Powershell

You could install Far Manager (a great OFM, by the way) and call its editor like that:

Far /e filename.txt

How to get file name from file path in android

We can find file name below code:

File file =new File(Path);
String filename=file.getName();

What is a .NET developer?

CLR, BCL and C#/VB.Net, ADO.NET, WinForms and/or ASP.NET. Most of the places that require additional .Net technologies, like WPF or WCF will call it out explicitly.

If statement with String comparison fails

To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:

In Java there are many string comparisons.

String s = "something", t = "maybe something else";
if (s == t)      // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t)    // ILLEGAL
if (s.compareTo(t) > 0) // also CORRECT>

Validating parameters to a Bash script

I would use bash's [[:

if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then 
    echo 'Please pass a number that corresponds to a directory'
    exit 1
fi

I found this faq to be a good source of information.

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

here's the solution which works for me on Linux

systemctl start docker.

How to use adb command to push a file on device without sd card

This might be the best answer you'll may read. Setup Android Studio Then just go to view & Open Device Explorer. Right-click on the folder & just upload a file.

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

How to change JFrame icon

Create a new ImageIcon object like this:

ImageIcon img = new ImageIcon(pathToFileOnDisk);

Then set it to your JFrame with setIconImage():

myFrame.setIconImage(img.getImage());

Also checkout setIconImages() which takes a List instead.

Write to file, but overwrite it if it exists

If your environment doesn't allow overwriting with >, use pipe | and tee instead as follows:

echo "text" | tee 'Users/Name/Desktop/TheAccount.txt'

Note this will also print to the stdout. In case this is unwanted, you can redirect the output to /dev/null as follows:

echo "text" | tee 'Users/Name/Desktop/TheAccount.txt' > /dev/null

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

it might save some time to somebody.

If you use GuzzleHttp and you face with this error message cURL error 60: SSL: no alternative certificate subject name matches target host name and you are fine with the 'insecure' solution (not recommended on production) then you have to add \GuzzleHttp\RequestOptions::VERIFY => false to the client configuration:

$this->client = new \GuzzleHttp\Client([
    'base_uri'                          => 'someAccessPoint',
    \GuzzleHttp\RequestOptions::HEADERS => [
        'User-Agent' => 'some-special-agent',
    ],
    'defaults'                          => [
        \GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5,
        \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true,
    ],
    \GuzzleHttp\RequestOptions::VERIFY  => false,
]);

which sets CURLOPT_SSL_VERIFYHOST to 0 and CURLOPT_SSL_VERIFYPEER to false in the CurlFactory::applyHandlerOptions() method

$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = false;

From the GuzzleHttp documentation

verify

Describes the SSL certificate verification behavior of a request.

  • Set to true to enable SSL certificate verification and use the default CA bundle > provided by operating system.
  • Set to false to disable certificate verification (this is insecure!).
  • Set to a string to provide the path to a CA bundle to enable verification using a custom certificate.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

React: trigger onChange if input value is changing by state?

you must do 4 following step :

  1. create event

    var event = new Event("change",{
        detail: {
            oldValue:yourValueVariable,
            newValue:!yourValueVariable
        },
        bubbles: true,
        cancelable: true
    });
    event.simulated = true;
    let tracker = this.yourComponentDomRef._valueTracker;
    if (tracker) {
        tracker.setValue(!yourValueVariable);
    }
    
  2. bind value to component dom

    this.yourComponentDomRef.value = !yourValueVariable;
    
  3. bind element onchange to react onChange function

     this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
    
  4. dispatch event

    this.yourComponentDomRef.dispatchEvent(event);
    

in above code yourComponentDomRef refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>

Initialize a string in C to empty string

It's a bit late but I think your issue may be that you've created a zero-length array, rather than an array of length 1.

A string is a series of characters followed by a string terminator ('\0'). An empty string ("") consists of no characters followed by a single string terminator character - i.e. one character in total.

So I would try the following:

string[1] = ""

Note that this behaviour is not the emulated by strlen, which does not count the terminator as part of the string length.

ECMAScript 6 arrow function that returns an object

Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions

Using jquery to delete all elements with a given id

As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:

var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');

for(var i = spans.length; i--;) {
    var span = spans[i];
    if(span.className.match(/\btheclass\b/)) {
        span.parentNode.removeChild(span);
    }
}

getElementsByTagName is the most cross-browser-compatible method that can be used here. getElementsByClassName would be much better, but is not supported by Internet Explorer <= IE 8.

Working Demo

Unable to verify leaf signature

I had an issue with my Apache configuration after installing a GoDaddy certificate on a subdomain. I originally thought it might be an issue with Node not sending a Server Name Indicator (SNI), but that wasn't the case. Analyzing the subdomain's SSL certificate with https://www.ssllabs.com/ssltest/ returned the error Chain issues: Incomplete.

After adding the GoDaddy provided gd_bundle-g2-g1.crt file via the SSLCertificateChainFile Apache directive, Node was able to connect over HTTPS and the error went away.

C++ - how to find the length of an integer

Being a computer nerd and not a maths nerd I'd do:

char buffer[64];
int len = sprintf(buffer, "%d", theNum);

How to set the env variable for PHP?

Follow this for Windows operating system with WAMP installed.

System > Advanced System Settings > Environment Variables
Click new

Variable name  : path
Variable value : c:\wamp\bin\php\php5.3.13\


Click ok

Type safety: Unchecked cast

You are getting this message because getBean returns an Object reference and you are casting it to the correct type. Java 1.5 gives you a warning. That's the nature of using Java 1.5 or better with code that works like this. Spring has the typesafe version

someMap=getApplicationContext().getBean<HashMap<String, String>>("someMap");

on its todo list.

Controlling number of decimal digits in print output in R

The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options value as a default.

As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.

Mathematica or Maple will allow you to give as many decimal places as your heart desires.

EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.

On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin (usually 2e-308).

Compare these two analyses.

x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1)  #Should throw an error

x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2)  #ok

In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.


As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr package.

mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")

These are slower and more memory intensive to use than regular (double precision) numeric vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.

Add Auto-Increment ID to existing table?

ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key FIRST

How to copy file from one location to another location?

Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original). Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.

 public static void main(String[] args) throws IOException {
                String destFolderPath = "D:/TestFile/abc";
                String fileName = "pqr.xlsx";
                String sourceFilePath= "D:/TestFile/xyz.xlsx";
                File f = new File(destFolderPath);
                if(f.mkdir()){
                    System.out.println("Directory created!!!!");
                }
                else {
                    System.out.println("Directory Exists!!!!");
                }
                f= new File(destFolderPath,fileName);
                if(f.createNewFile())   {

                    System.out.println("File Created!!!!");
                }   else {
                    System.out.println("File exists!!!!");
                }

                Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
                System.out.println("Copy done!!!!!!!!!!!!!!");


            }

get unique machine id

The following site uses System.Management to accomplish the same is a very sleek way in a console application

where is gacutil.exe?

  1. Open Developer Command prompt.
  2. type

where gacutil

How do I set multipart in axios with react?

Here's how I do file upload in react using axios

import React from 'react'
import axios, { post } from 'axios';

class SimpleReactFileUpload extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault() // Stop form submit
    this.fileUpload(this.state.file).then((response)=>{
      console.log(response.data);
    })
  }

  onChange(e) {
    this.setState({file:e.target.files[0]})
  }

  fileUpload(file){
    const url = 'http://example.com/file-upload';
    const formData = new FormData();
    formData.append('file',file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  post(url, formData,config)
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}



export default SimpleReactFileUpload

Source

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Like the answer above but here is using bootstrap 3 names and colours:

_x000D_
_x000D_
/*css to add back colours for badges and make use of the colours*/_x000D_
.badge-default {_x000D_
  background-color: #999999;_x000D_
}_x000D_
_x000D_
.badge-primary {_x000D_
  background-color: #428bca;_x000D_
}_x000D_
_x000D_
.badge-success {_x000D_
  background-color: #5cb85c;_x000D_
}_x000D_
_x000D_
.badge-info {_x000D_
  background-color: #5bc0de;_x000D_
}_x000D_
_x000D_
.badge-warning {_x000D_
  background-color: #f0ad4e;_x000D_
}_x000D_
_x000D_
.badge-danger {_x000D_
  background-color: #d9534f;_x000D_
}
_x000D_
_x000D_
_x000D_

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR

from the command prompt for more information.

What does %s and %d mean in printf in the C language?

%d is print as an int %s is print as a string %f is print as floating point

It should be noted that it is incorrect to say that this is different from Java. Printf stands for print format, if you do a formatted print in Java, this is exactly the same usage. This may allow you to solve interesting and new problems in both C and Java!

DataGridView changing cell background color

dataGridView1[row, col].Style.BackColor = System.Drawing.Color.Red;

Comparing strings in C# with OR in an if statement

try

if (testString.Equals(testString2)){
}

How to pretty-print a numpy.array without scientific notation and with given precision?

Unutbu gave a really complete answer (they got a +1 from me too), but here is a lo-tech alternative:

>>> x=np.random.randn(5)
>>> x
array([ 0.25276524,  2.28334499, -1.88221637,  0.69949927,  1.0285625 ])
>>> ['{:.2f}'.format(i) for i in x]
['0.25', '2.28', '-1.88', '0.70', '1.03']

As a function (using the format() syntax for formatting):

def ndprint(a, format_string ='{0:.2f}'):
    print [format_string.format(v,i) for i,v in enumerate(a)]

Usage:

>>> ndprint(x)
['0.25', '2.28', '-1.88', '0.70', '1.03']

>>> ndprint(x, '{:10.4e}')
['2.5277e-01', '2.2833e+00', '-1.8822e+00', '6.9950e-01', '1.0286e+00']

>>> ndprint(x, '{:.8g}')
['0.25276524', '2.283345', '-1.8822164', '0.69949927', '1.0285625']

The index of the array is accessible in the format string:

>>> ndprint(x, 'Element[{1:d}]={0:.2f}')
['Element[0]=0.25', 'Element[1]=2.28', 'Element[2]=-1.88', 'Element[3]=0.70', 'Element[4]=1.03']

How do I find out what License has been applied to my SQL Server installation?

I presume you mean via SSMS?

For a SQL Server Instance:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

For a SQL Server Installation:

Select @@Version

Bundle ID Suffix? What is it?

If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.

In Bundle ID Suffix you should write full name of bundle ID.

Example:

Bundle ID suffix = thebestapp (NOT CORRECT!!!!)

Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)

The reason for this is explained in the Developer Portal:

The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g. ABCDE12345), and an App ID Suffix (a Bundle ID search string, e.g. com.mycompany.appname). [emphasis added]

So in this case the suffix is the full string com.awesomeapps.thebestapp.

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

Making button go full-width?

Bootstrap v3 & v4

Use btn-block class on your button/element

Bootstrap v2

Use input-block-level class on your button/element

How to check if a string contains text from an array of substrings in JavaScript?

Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)

// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
    // array matches
    if (Array.isArray(b)) {
        return b.some(x => a.indexOf(x) > -1);
    }
    // string match
    return a.indexOf(b) > -1;
}

Example usage:

var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
    // 1 or more matches found
}

What is the syntax meaning of RAISERROR()

16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

Regular expression search replace in Sublime Text 2

Looking at Sublime Text Unofficial Documentation's article on Search and Replace, it looks like +(.+) is the capture group you might want... but I personally used (.*) and it worked well. To REPLACE in the way you are saying, you might like this conversation in the forums, specifically this post which says to simply use $1 to use the first captured group.

And since pictures are better than words...

Before: before find/replace

After: after find/replace

Check if a string has white space

This function checks for other types of whitespace, not just space (tab, carriage return, etc.)

import some from 'lodash/fp/some'
const whitespaceCharacters = [' ', '  ',
  '\b', '\t', '\n', '\v', '\f', '\r', `\"`, `\'`, `\\`,
  '\u0008', '\u0009', '\u000A', '\u000B', '\u000C',
'\u000D', '\u0020','\u0022', '\u0027', '\u005C',
'\u00A0', '\u2028', '\u2029', '\uFEFF']
const hasWhitespace = char => some(
  w => char.indexOf(w) > -1,
  whitespaceCharacters
)

console.log(hasWhitespace('a')); // a, false
console.log(hasWhitespace(' ')); // space, true
console.log(hasWhitespace(' ')); // tab, true
console.log(hasWhitespace('\r')); // carriage return, true

If you don't want to use Lodash, then here is a simple some implementation with 2 s:

const ssome = (predicate, list) =>
{
  const len = list.length;
  for(const i = 0; i<len; i++)
  {
    if(predicate(list[i]) === true) {
      return true;
    }
  }
  return false;
};

Then just replace some with ssome.

const hasWhitespace = char => some(
  w => char.indexOf(w) > -1,
  whitespaceCharacters
)

For those in Node, use:

const { some } = require('lodash/fp');

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

Cannot resolve symbol 'AppCompatActivity'

Add this dependency in project build .gradle.

Follow the example below.

dependencies {

    compile 'com.android.support:appcompat-v7:22.1.0'
}

How do I run a Java program from the command line on Windows?

Source: javaindos.

Let's say your file is in C:\mywork\

Run Command Prompt

C:\> cd \mywork

This makes C:\mywork the current directory.

C:\mywork> dir

This displays the directory contents. You should see filenamehere.java among the files.

C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin

This tells the system where to find JDK programs.

C:\mywork> javac filenamehere.java

This runs javac.exe, the compiler. You should see nothing but the next system prompt...

C:\mywork> dir

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

C:\mywork> java filenamehere

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

For some reason, there is no option in the create page dialogue to select a master page. I have tried both programatically declaring the MP and by updating the property in the Properties pane. – NoCarrier 13 mins ago

I believe its because i'm using a "web application" vs a "web site" – NoCarrier 9 mins ago

Chances are it is in the <@PAGE> tag where your problem is. That said, it doesnt make a difference if you are using a Web Application or not. To create a Child Page, right click on your master page in the Solution Explorer and choose Add Content Page.

How do I get a substring of a string in Python?

You've got it right there except for "end". It's called slice notation. Your example should read:

new_sub_string = myString[2:]

If you leave out the second parameter it is implicitly the end of the string.

Node Sass couldn't find a binding for your current environment

I had the same problem in a Windows environment, receiving the following error:

Error: Missing binding C:\Development{ProjectName}\node_modules\node-sass\vendor\win32-ia32-47\binding.node
Node Sass could not find a binding for your current environment: Windows 32-bit with Node.js 5.x
Found bindings for the following environments:
   - Windows 64-bit with Node.js 6.x

None of the npm commands listed in the other answers here (npm install, npm rebuild node-sass, etc.) worked.

Instead, I had to download the missing binding and place it in the appropriate destination folder.

The bindings can be found on git. Match the file with the folder name identified after /node_modules/node-sass/vendor/ in your error message ('darwin-x64-11' in your case, so you'd want the darwin-x64-11_binding.node file).

Create the missing folder in your project (/node_modules/node-sass/vendor/darwin-x64-11), copy the .node file to the new directory, and rename it to binding.node.

Node-sass release URL: https://github.com/sass/node-sass/releases

Check if a record exists in the database

The ExecuteScalar method should be used when you are really sure your query returns only one value like below:

SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'

If you want the whole row then the below code should more appropriate.

SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = @user)" , conn);
check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
   //User Exists
}
else
{
   //User NOT Exists
}

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Where do I find the Instagram media ID of a image

For a period I had to extract the Media ID myself quite frequently, so I wrote my own script (very likely it's based on some of the examples here). Together with other small scripts I used frequently, I started to upload them on www.findinstaid.com for my own quick access.

I added the option to enter a username to get the media ID of the 12 most recent posts, or to enter a URL to get the media ID of a specific post.

If it's convenient, everyone can use the link (I don't have any adds or any other monetary interests in the website - I only have a referral link on the 'Audit' tab to www.auditninja.io which I do also own, but also on this site, there are no adds or monetary interests - just hobby projects).

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Which comes first in a 2D array, rows or columns?

In c++ (distant, dusty memory) I think it was a little easier to look at the code and understand arrays than it is in Java sometimes. Both are row major. This illustration worked for me in helping to understand.

Given this code for a 2d array of strings...

    String[][] messages; 
    messages = new String[][] {
        {"CAT","DOG","YIN","BLACK","HIGH","DAY"},
        {"kitten","puppy","yang","white","low","night"} 
    };
    
    int row = messages.length;
    int col = messages[0].length;
    

Naming my ints as if it were a 2d array (row, col) we see the values.

row = (int) 2
col = (int) 6

The last two lines of code, where we try to determine size and set them to row and col does not look all that intuitive and its not necessarily right.

What youre really dealing with here is this (note new variable names to illustrate):

int numOfArraysIn = messages.length;
int numOfElementsIn0 = messages[0].length;
int numOfElementsIn1 = messages[1].length;

Where messages.length tells you messages holds two arrays. An array of arrays.

AND then messages[x].length yields the size of each of the individual arrays 0 1 inside messages.

numOfArraysIn = (int) 2
numOfElementsIn0 = (int) 6
numOfElementsIn1 = (int) 6

When we print with a for each loop....

for (String str : messages[0])
        System.out.print(str);
for (String str : messages[1])
        System.out.print(str);

CATDOGYINBLACKHIGHDAYkittenpuppyyangwhitelownight

Trying to drop the brackets and print like this gives an error

for (String str : messages)
        System.out.print(str);

incompatible types: String[] cannot be converted to String

The above is important to understand while setting up loops that use .length to limit the step thru the array.

disable textbox using jquery?

$(document).ready(function () {
   $("#txt1").attr("onfocus", "blur()");
});

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  $("#txt1").attr("onfocus", "blur()");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="txt1">
_x000D_
_x000D_
_x000D_

Programmatically extract contents of InstallShield setup.exe

On Linux there is unshield, which worked well for me (even if the GUI includes custom deterrents like license key prompts). It is included in the repositories of all major distributions (arch, suse, debian- and fedora-based) and its source is available at https://github.com/twogood/unshield

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

Losing Session State

Dont know is it related to your problem or not BUT Windows 2008 Server R2 or SP2 has changed its IIS settings, which leads to issue in session persistence. By default, it manages separate session variable for HTTP and HTTPS. When variables are set in HTTPS, these will be available only on HTTPS pages whenever switched.

To solve the issue, there is IIS setting. In IIS Manager, open up the ASP properties, expand Session Properties, and change New ID On Secure Connection to False.

Why do I get a SyntaxError for a Unicode escape in my file path?

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.

MySQL vs MySQLi when using PHP

I have abandoned using mysqli. It is simply too unstable. I've had queries that crash PHP using mysqli but work just fine with the mysql package. Also mysqli crashes on LONGTEXT columns. This bug has been raised in various forms since at least 2005 and remains broken. I'd honestly like to use prepared statements but mysqli just isn't reliable enough (and noone seems to bother fixing it). If you really want prepared statements go with PDO.

Use URI builder in Android or create URL with variables

Let's say that I want to create the following URL:

https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name

To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.myawesomesite.com")
    .appendPath("turtles")
    .appendPath("types")
    .appendQueryParameter("type", "1")
    .appendQueryParameter("sort", "relevance")
    .fragment("section-name");
String myUrl = builder.build().toString();

SVN Repository on Google Drive or DropBox

Here's one application that works for me. In our case...I wanted the Sales team to use SVN for certain docs (Price sheets and such)...but a bit over there head.

I setup an Auto SVN like this: - Created a REPO in my SVN server. - Checked out repo into a DB folder call AutoSVN. - I run EasySVN on my PC, which auto commits and updates the REPO.

With he 'Auto', there are no log comments, but not critical for these particular docs.

The Sales guys use the DB folder...and simply maintain the file name of those docs that need version control such as price sheets.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

hi it worked for me from the recommended link from Fredy Andersen

sudo install_name_tool -change libmysqlclient.16.dylib /usr/local/mysql /lib/libmysqlclient.16.dylib /Library/Ruby/Gems/1.8/gems/mysql2-0.2.6/lib/mysql2/mysql2.bundle

just had to change to my version of mysql, in the command, thanks

How to change app default theme to a different app theme?

To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml file.

Example:

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

<application 
    android:theme="@android:style/Theme.Holo.Light"/>

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

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

If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.

<uses-sdk
    android:minSdkVersion="14"/>

Node.js/Express.js App Only Works on Port 3000

The following works if you have something like this in your app.js:

http.createServer(app).listen(app.get('port'),
  function(){
    console.log("Express server listening on port " + app.get('port'));
});

Either explicitly hardcode your code to use the port you want, like:

app.set('port', process.env.PORT || 3000);

This code means set your port to the environment variable PORT or if that is undefined then set it to the literal 3000.

Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION and DEVELOPMENT and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.

$ PORT=8080 node app.js

In reference to your code example, you want something like this:

var express = require("express");
var app = express();

// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);

app.get('/', function(req, res){
    res.send('hello world');
});

// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));

VB.NET - Click Submit Button on Webbrowser page

This seems to work easily.


Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
        Dim MyDoc As New mshtml.HTMLDocument
        Dim DocElements As mshtml.IHTMLElementCollection = Nothing
        Dim LoginForm As mshtml.HTMLFormElement = Nothing

        ASPComplete = 0
        WB.Navigate(VitecLoginURI)
        BrowserLoop()

        MyDoc = WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each i As mshtml.IHTMLElement In DocElements

            Select Case i.name
                Case "seLogin$UserName"
                    i.value = UserID
                Case "seLogin$Password"
                    i.value = Pass
                Case Else
                    Exit Select
            End Select

            frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
        Next i

        'Old Method for Clicking submit
        'WB.Document.Forms("form1").InvokeMember("submit")


        'Better Method to click submit
        LoginForm = MyDoc.forms.item("form1")
        LoginForm.item("seLogin$LoginButton").click()
        ASPComplete = 0
        BrowserLoop()



        MyDoc= WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each j As mshtml.IHTMLElement In DocElements
            frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf

        Next j

        frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
        Return 1
End Function

c# dictionary How to add multiple values for single key?

You could use my implementation of a multimap, which derives from a Dictionary<K, List<V>>. It is not perfect, however it does a good job.

/// <summary>
/// Represents a collection of keys and values.
/// Multiple values can have the same key.
/// </summary>
/// <typeparam name="TKey">Type of the keys.</typeparam>
/// <typeparam name="TValue">Type of the values.</typeparam>
public class MultiMap<TKey, TValue> : Dictionary<TKey, List<TValue>>
{

    public MultiMap()
        : base()
    {
    }

    public MultiMap(int capacity)
        : base(capacity)
    {
    }

    /// <summary>
    /// Adds an element with the specified key and value into the MultiMap. 
    /// </summary>
    /// <param name="key">The key of the element to add.</param>
    /// <param name="value">The value of the element to add.</param>
    public void Add(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            valueList.Add(value);
        } else {
            valueList = new List<TValue>();
            valueList.Add(value);
            Add(key, valueList);
        }
    }

    /// <summary>
    /// Removes first occurence of an element with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the element to remove.</param>
    /// <param name="value">The value of the element to remove.</param>
    /// <returns>true if the an element is removed;
    /// false if the key or the value were not found.</returns>
    public bool Remove(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            if (valueList.Remove(value)) {
                if (valueList.Count == 0) {
                    Remove(key);
                }
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// Removes all occurences of elements with a specified key and value.
    /// </summary>
    /// <param name="key">The key of the elements to remove.</param>
    /// <param name="value">The value of the elements to remove.</param>
    /// <returns>Number of elements removed.</returns>
    public int RemoveAll(TKey key, TValue value)
    {
        List<TValue> valueList;
        int n = 0;

        if (TryGetValue(key, out valueList)) {
            while (valueList.Remove(value)) {
                n++;
            }
            if (valueList.Count == 0) {
                Remove(key);
            }
        }
        return n;
    }

    /// <summary>
    /// Gets the total number of values contained in the MultiMap.
    /// </summary>
    public int CountAll
    {
        get
        {
            int n = 0;

            foreach (List<TValue> valueList in Values) {
                n += valueList.Count;
            }
            return n;
        }
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific
    /// key / value pair.
    /// </summary>
    /// <param name="key">Key of the element to search for.</param>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TKey key, TValue value)
    {
        List<TValue> valueList;

        if (TryGetValue(key, out valueList)) {
            return valueList.Contains(value);
        }
        return false;
    }

    /// <summary>
    /// Determines whether the MultiMap contains an element with a specific value.
    /// </summary>
    /// <param name="value">Value of the element to search for.</param>
    /// <returns>true if the element was found; otherwise false.</returns>
    public bool Contains(TValue value)
    {
        foreach (List<TValue> valueList in Values) {
            if (valueList.Contains(value)) {
                return true;
            }
        }
        return false;
    }

}

Note that the Add method looks if a key is already present. If the key is new, a new list is created, the value is added to the list and the list is added to the dictionary. If the key was already present, the new value is added to the existing list.

ld.exe: cannot open output file ... : Permission denied

I had exactly the same problem right after switching off some (in my opinion unneccessary) Windows services. It turned out that when I switched ON again the "Application Experience" everything resumed working fine.

May be you simply have to turn on this service? To switch ON Application Experience:

  1. Click the Windows start buttonn.

  2. In the box labeled "Search programs and files" type services.msc and click the search button. A new window with title "Services" opens.

  3. Right click on "Application Experience" line and select "Properties" from popup menu.

  4. Change Startup type to "Automatic (delayed start)".

  5. Restart computer.

Application Experiences should prevent the problem in the future.

Can you style an html radio button to look like a checkbox?

appearance property doesn't work in all browser. You can do like the following-

_x000D_
_x000D_
input[type="radio"]{_x000D_
  display: none;_x000D_
}_x000D_
label:before{_x000D_
  content:url(http://strawberrycambodia.com/book/admin/templates/default/images/icons/16x16/checkbox.gif);_x000D_
}_x000D_
input[type="radio"]:checked+label:before{_x000D_
  content:url(http://www.treatment-abroad.ru/img/admin/icons/16x16/checkbox.gif);_x000D_
}
_x000D_
 _x000D_
  <input type="radio" name="gender" id="test1" value="male">_x000D_
  <label for="test1"> check 1</label>_x000D_
  <input type="radio" name="gender" value="female" id="test2">_x000D_
  <label for="test2"> check 2</label>_x000D_
  <input type="radio" name="gender" value="other" id="test3">_x000D_
  <label for="test3"> check 3</label>  
_x000D_
_x000D_
_x000D_

It works IE 8+ and other browsers

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

MySQL the right syntax to use near '' at line 1 error

INSERT INTO wp_bp_activity
            (
            user_id,
             component,
             `type`,
             `action`,
             content,
             primary_link,
             item_id,
             secondary_item_id,
             date_recorded,
             hide_sitewide,
             mptt_left,
             mptt_right
             )
             VALUES(
             1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
             )

Angular2 - Input Field To Accept Only Numbers

You can use angular2 directives. Plunkr

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
      if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+C
        (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+V
        (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||
        // Allow: Ctrl+X
        (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // let it happen, don't do anything
          return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
      }
  }
}

and you need to write the directive name in your input as an attribute

<input OnlyNumber="true" />

don't forget to write your directive in declarations array of your module.

By using regex you would still need functional keys

export class OnlyNumber {

  regexStr = '^[0-9]*$';
  constructor(private el: ElementRef) { }

  @Input() OnlyNumber: boolean;

  @HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (this.OnlyNumber) {
        if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+V
        (e.keyCode == 86 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
        // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
          // let it happen, don't do anything
          return;
        }
      let ch = String.fromCharCode(e.keyCode);
      let regEx =  new RegExp(this.regexStr);    
      if(regEx.test(ch))
        return;
      else
         e.preventDefault();
      }
  }
}

What does the "yield" keyword do?

To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.

Iterables

When you create a list, you can read its items one by one. Reading its items one by one is called iteration:

>>> mylist = [1, 2, 3]
>>> for i in mylist:
...    print(i)
1
2
3

mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:

>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
...    print(i)
0
1
4

Everything you can use "for... in..." on is an iterable; lists, strings, files...

These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.

Generators

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
...    print(i)
0
1
4

It is just the same except you used () instead of []. BUT, you cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.

Yield

yield is a keyword that is used like return, except the function will return a generator.

>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
>>> mygenerator = createGenerator() # create a generator
>>> print(mygenerator) # mygenerator is an object!
<generator object createGenerator at 0xb7555c34>
>>> for i in mygenerator:
...     print(i)
0
1
4

Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.

To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky :-)

Then, your code will continue from where it left off each time for uses the generator.

Now the hard part:

The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting yield. That can be because the loop has come to an end, or because you no longer satisfy an "if/else".


Your code explained

Generator:

# Here you create the method of the node object that will return the generator
def _get_child_candidates(self, distance, min_dist, max_dist):

    # Here is the code that will be called each time you use the generator object:

    # If there is still a child of the node object on its left
    # AND if the distance is ok, return the next child
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild

    # If there is still a child of the node object on its right
    # AND if the distance is ok, return the next child
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild

    # If the function arrives here, the generator will be considered empty
    # there is no more than two values: the left and the right children

Caller:

# Create an empty list and a list with the current object reference
result, candidates = list(), [self]

# Loop on candidates (they contain only one element at the beginning)
while candidates:

    # Get the last candidate and remove it from the list
    node = candidates.pop()

    # Get the distance between obj and the candidate
    distance = node._get_dist(obj)

    # If distance is ok, then you can fill the result
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)

    # Add the children of the candidate in the candidate's list
    # so the loop will keep running until it will have looked
    # at all the children of the children of the children, etc. of the candidate
    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))

return result

This code contains several smart parts:

  • The loop iterates on a list, but the list expands while the loop is being iterated :-) It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop. In this case, candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) exhaust all the values of the generator, but while keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.

  • The extend() method is a list object method that expects an iterable and adds its values to the list.

Usually we pass a list to it:

>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]

But in your code, it gets a generator, which is good because:

  1. You don't need to read the values twice.
  2. You may have a lot of children and you don't want them all stored in memory.

And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples, and generators! This is called duck typing and is one of the reasons why Python is so cool. But this is another story, for another question...

You can stop here, or read a little bit to see an advanced use of a generator:

Controlling a generator exhaustion

>>> class Bank(): # Let's create a bank, building ATMs
...    crisis = False
...    def create_atm(self):
...        while not self.crisis:
...            yield "$100"
>>> hsbc = Bank() # When everything's ok the ATM gives you as much as you want
>>> corner_street_atm = hsbc.create_atm()
>>> print(corner_street_atm.next())
$100
>>> print(corner_street_atm.next())
$100
>>> print([corner_street_atm.next() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
>>> hsbc.crisis = True # Crisis is coming, no more money!
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> wall_street_atm = hsbc.create_atm() # It's even true for new ATMs
>>> print(wall_street_atm.next())
<type 'exceptions.StopIteration'>
>>> hsbc.crisis = False # The trouble is, even post-crisis the ATM remains empty
>>> print(corner_street_atm.next())
<type 'exceptions.StopIteration'>
>>> brand_new_atm = hsbc.create_atm() # Build a new one to get back in business
>>> for cash in brand_new_atm:
...    print cash
$100
$100
$100
$100
$100
$100
$100
$100
$100
...

Note: For Python 3, useprint(corner_street_atm.__next__()) or print(next(corner_street_atm))

It can be useful for various things like controlling access to a resource.

Itertools, your best friend

The itertools module contains special functions to manipulate iterables. Ever wish to duplicate a generator? Chain two generators? Group values in a nested list with a one-liner? Map / Zip without creating another list?

Then just import itertools.

An example? Let's see the possible orders of arrival for a four-horse race:

>>> horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>>> print(races)
<itertools.permutations object at 0xb754f1dc>
>>> print(list(itertools.permutations(horses)))
[(1, 2, 3, 4),
 (1, 2, 4, 3),
 (1, 3, 2, 4),
 (1, 3, 4, 2),
 (1, 4, 2, 3),
 (1, 4, 3, 2),
 (2, 1, 3, 4),
 (2, 1, 4, 3),
 (2, 3, 1, 4),
 (2, 3, 4, 1),
 (2, 4, 1, 3),
 (2, 4, 3, 1),
 (3, 1, 2, 4),
 (3, 1, 4, 2),
 (3, 2, 1, 4),
 (3, 2, 4, 1),
 (3, 4, 1, 2),
 (3, 4, 2, 1),
 (4, 1, 2, 3),
 (4, 1, 3, 2),
 (4, 2, 1, 3),
 (4, 2, 3, 1),
 (4, 3, 1, 2),
 (4, 3, 2, 1)]

Understanding the inner mechanisms of iteration

Iteration is a process implying iterables (implementing the __iter__() method) and iterators (implementing the __next__() method). Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.

There is more about it in this article about how for loops work.

How to filter rows in pandas by regex

Multiple column search with dataframe:

frame[frame.filename.str.match('*.'+MetaData+'.*') & frame.file_path.str.match('C:\test\test.txt')]

Get keys from HashMap in Java

A HashMap contains more than one key. You can use keySet() to get the set of all keys.

team1.put("foo", 1);
team1.put("bar", 2);

will store 1 with key "foo" and 2 with key "bar". To iterate over all the keys:

for ( String key : team1.keySet() ) {
    System.out.println( key );
}

will print "foo" and "bar".

When do I need to use AtomicBoolean in Java?

Here is the notes (from Brian Goetz book) I made, that might be of help to you

AtomicXXX classes

  • provide Non-blocking Compare-And-Swap implementation

  • Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.

  • not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

ValueError: unconverted data remains: 02:05

The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.

Very Simple, Very Smooth, JavaScript Marquee

My text marquee for more text, and position absolute enabled

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};

$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();

function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();

    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};

if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

How do you serialize a model instance in Django?

If you're dealing with a list of model instances the best you can do is using serializers.serialize(), it gonna fit your need perfectly.

However, you are to face an issue with trying to serialize a single object, not a list of objects. That way, in order to get rid of different hacks, just use Django's model_to_dict (if I'm not mistaken, serializers.serialize() relies on it, too):

from django.forms.models import model_to_dict

# assuming obj is your model instance
dict_obj = model_to_dict( obj )

You now just need one straight json.dumps call to serialize it to json:

import json
serialized = json.dumps(dict_obj)

That's it! :)

Cannot access a disposed object - How to fix?

because the solution folder was inside OneDrive folder.

If you moving the solution folders out of the one drive folder made the errors go away.

best

What does "./" (dot slash) refer to in terms of an HTML file path location?

. is a shorthand for the current directory and is used in Linux and Unix to execute a compiled program in the current directory. That is why you don't see this used in Web Development much except by open source, non-Windows frameworks like Google Angular which was written by people stuck on open source platforms.

./ also resolves to the current directory and is atypical in Web but supported as a path in some open source frameworks. Because it resolves the same as no path to the current file directory its not used. Example: ./image.jpg = image.jpg. Again, this is a relic of Unix operating systems that need path resolutions like this to run executables and resolve paths for security reasons. Its not a typical web path. That is why this syntax is redundant.

../ is a traditional web path that goes one directory up

/ is the ROOT of your website

These path resolutions below are true...

./folder= folder this is always true in web path resolution

./file.html = file.html this is always true in web path resolution

./ = {no path} an empty path is the same as ./ in the web world

{no path} = / an empty path is the same as the web root if your file is in the root directory

./ = / ONLY if you are in the root folder

../ = / ONLY if you are one folder below the web root

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

If you use Git and have Git Bash installed you can open a Git Bash at the directory (via Right Click in the white space in Explorer > Git Bash Here) and do:

touch .htaccess

How to iterate over each string in a list of strings and operate on it's elements

The suggestion that using range(len()) is the equivalent of using enumerate() is incorrect. They return the same results, but they are not the same.

Using enumerate() actually gives you key/value pairs. Using range(len()) does not.

Let's check range(len()) first (working from the example from the original poster):

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
    print range(len(words))

This gives us a simple list:

[0, 1, 2, 3, 4]

... and the elements in this list serve as the "indexes" in our results.

So let's do the same thing with our enumerate() version:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']    
   print enumerate(words)

This certainly doesn't give us a list:

<enumerate object at 0x7f6be7f32c30>

...so let's turn it into a list, and see what happens:

print list(enumerate(words))

It gives us:

[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]

These are actual key/value pairs.

So this ...

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']

for i in range(len(words)):
    print "words[{}] = ".format(i), words[i]

... actually takes the first list (Words), and creates a second, simple list of the range indicated by the length of the first list.

So we have two simple lists, and we are merely printing one element from each list in order to get our so-called "key/value" pairs.

But they aren't really key/value pairs; they are merely two single elements printed at the same time, from different lists.

Whereas the enumerate () code:

for i, word in enumerate(words):
    print "words[{}] = {}".format(i, word)

... also creates a second list. But that list actually is a list of key/value pairs, and we are asking for each key and value from a single source -- rather than from two lists (like we did above).

So we print the same results, but the sources are completely different -- and handled completely differently.

How to allow Cross domain request in apache2

put the following in the site's .htaccess file (in the /var/www/XXX):

Header set Access-Control-Allow-Origin "*"

instead of the .conf file.

You'll also want to use

AllowOverride All

in your .conf file for the domain so Apache looks at it.

Why does GitHub recommend HTTPS over SSH?

Maybe because it's harder to steal a password from your brain then to steal a key file from your computer (at least to my knowledge, maybe some substances exist already or methods but this is an infinite discussion)? And if you password protect the key, then you are using a password again and the same problems arise (but some might argue that you have to do more work, because you need to get the key and then crack the password).

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

PHP: How to remove all non printable characters in a string?

My UTF-8 compliant version:

preg_replace('/[^\p{L}\s]/u','',$value);

How to run mysql command on bash?

Use double quotes while using BASH variables.

mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"

BASH doesn't expand variables in single quotes.

Pure JavaScript: a function like jQuery's isNumeric()

There's no isNumeric() type of function, but you could add your own:

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

NOTE: Since parseInt() is not a proper way to check for numeric it should NOT be used.

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

Close Bootstrap modal on form submit

Use this to submit and close the modal at the same time

$('#form-submit').on('click', function(e){
    e.preventDefault();
    $('#con-close-modal').modal('toggle'); //or  $('#IDModal').modal('hide');
    $('#date-form').submit();
});

Find an item in List by LINQ?

You want to search an object in object list.

This will help you in getting the first or default value in your Linq List search.

var item = list.FirstOrDefault(items =>  items.Reference == ent.BackToBackExternalReferenceId);

or

var item = (from items in list
    where items.Reference == ent.BackToBackExternalReferenceId
    select items).FirstOrDefault();

How to compare two dates?

Use the datetime method and the operator < and its kin.

>>> from datetime import datetime, timedelta
>>> past = datetime.now() - timedelta(days=1)
>>> present = datetime.now()
>>> past < present
True
>>> datetime(3000, 1, 1) < present
False
>>> present - datetime(2000, 4, 4)
datetime.timedelta(4242, 75703, 762105)

no such file to load -- rubygems (LoadError)

I had a similar problem and solved that by setting up RUBYLIB env.

In my environment I used this:

export RUBYLIB=$ruby_dir/lib/ruby/1.9.1/:$ruby_dir/lib/ruby/1.9.1/i686-linux/:$RUBYLIB

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

Should be a lot better

For a 32-bit JVM running on a 64-bit host, I imagine what's left over for the heap will be whatever unfragmented virtual space is available after the JVM, it's own DLL's, and any OS 32-bit compatibility stuff has been loaded. As a wild guess I would think 3GB should be possible, but how much better that is depends on how well you are doing in 32-bit-host-land.

Also, even if you could make a giant 3GB heap, you might not want to, as this will cause GC pauses to become potentially troublesome. Some people just run more JVM's to use the extra memory rather than one giant one. I imagine they are tuning the JVM's right now to work better with giant heaps.

It's a little hard to know exactly how much better you can do. I guess your 32-bit situation can be easily determined by experiment. It's certainly hard to predict abstractly, as a lot of things factor into it, particularly because the virtual space available on 32-bit hosts is rather constrained.. The heap does need to exist in contiguous virtual memory, so fragmentation of the address space for dll's and internal use of the address space by the OS kernel will determine the range of possible allocations.

The OS will be using some of the address space for mapping HW devices and it's own dynamic allocations. While this memory is not mapped into the java process address space, the OS kernel can't access it and your address space at the same time, so it will limit the size of any program's virtual space.

Loading DLL's depends on the implementation and the release of the JVM. Loading the OS kernel depends on a huge number of things, the release, the HW, how many things it has mapped so far since the last reboot, who knows...

In summary

I bet you get 1-2 GB in 32-bit-land, and about 3 in 64-bit, so an overall improvement of about 2x.

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

why is plotting with Matplotlib so slow?

First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:

import matplotlib.pyplot as plt
import numpy as np
import time

x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]

fig.show()

tstart = time.time()
for i in xrange(1, 20):
    for j, line in enumerate(lines, start=1):
        line.set_ydata(np.sin(j*x + i/10.0))
    fig.canvas.draw()

print 'FPS:' , 20/(time.time()-tstart)

With the above example, I get around 10fps.

Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.

However, there are a lot of things you can do to speed this example up.

There are two main reasons why this is as slow as it is.

1) Calling fig.canvas.draw() redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.

2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.

Both these can be fixed by using blitting.

To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.

However, without knowing a bit more about what you're doing, I can't help you there.

Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.

import matplotlib.pyplot as plt
import numpy as np
import time

x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)

fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
    return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

tstart = time.time()
for i in xrange(1, 2000):
    items = enumerate(zip(lines, axes, backgrounds), start=1)
    for j, (line, ax, background) in items:
        fig.canvas.restore_region(background)
        line.set_ydata(np.sin(j*x + i/10.0))
        ax.draw_artist(line)
        fig.canvas.blit(ax.bbox)

print 'FPS:' , 2000/(time.time()-tstart)

This gives me ~200fps.

To make this a bit more convenient, there's an animations module in recent versions of matplotlib.

As an example:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)

styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
    return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]

def animate(i):
    for j, line in enumerate(lines, start=1):
        line.set_ydata(np.sin(j*x + i/10.0))
    return lines

# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200), 
                              interval=0, blit=True)
plt.show()

How to use sessions in an ASP.NET MVC 4 application?

This is how session state works in ASP.NET and ASP.NET MVC:

ASP.NET Session State Overview

Basically, you do this to store a value in the Session object:

Session["FirstName"] = FirstNameTextBox.Text;

To retrieve the value:

var firstName = Session["FirstName"];

Rewrite URL after redirecting 404 error htaccess

Try adding this rule to the top of your htaccess:

RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]

Then under that (or any other rules that you have):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]

PHP: check if any posted vars are empty - form: all fields required

I use my own custom function...

public function areNull() {
    if (func_num_args() == 0) return false;
    $arguments = func_get_args();
    foreach ($arguments as $argument):
        if (is_null($argument)) return true;
    endforeach;
    return false;
}
$var = areNull("username", "password", "etc");

I'm sure it can easily be changed for you scenario. Basically it returns true if any of the values are NULL, so you could change it to empty or whatever.

How do I get the XML SOAP request of an WCF Web service request?

I am using below solution for IIS hosting in ASP.NET compatibility mode. Credits to Rodney Viana's MSDN blog.

Add following to your web.config under appSettings:

<add key="LogPath" value="C:\\logpath" />
<add key="LogRequestResponse" value="true" />

Replace your global.asax.cs with below (also fix namespace name):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Text;
using System.IO;
using System.Configuration;

namespace Yournamespace
{
    public class Global : System.Web.HttpApplication
    {
        protected static bool LogFlag;
        protected static string fileNameBase;
        protected static string ext = "log";

        // One file name per day
        protected string FileName
        {
            get
            {
                return String.Format("{0}{1}.{2}", fileNameBase, DateTime.Now.ToString("yyyy-MM-dd"), ext);
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            LogFlag = bool.Parse(ConfigurationManager.AppSettings["LogRequestResponse"].ToString());
            fileNameBase = ConfigurationManager.AppSettings["LogPath"].ToString() + @"\C5API-";   
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (LogFlag) 
            {                
                // Creates a unique id to match Rquests with Responses
                string id = String.Format("Id: {0} Uri: {1}", Guid.NewGuid(), Request.Url);
                FilterSaveLog input = new FilterSaveLog(HttpContext.Current, Request.Filter, FileName, id);
                Request.Filter = input;
                input.SetFilter(false);
                FilterSaveLog output = new FilterSaveLog(HttpContext.Current, Response.Filter, FileName, id);
                output.SetFilter(true);
                Response.Filter = output;
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }

    class FilterSaveLog : Stream
    {

        protected static string fileNameGlobal = null;
        protected string fileName = null;

        protected static object writeLock = null;
        protected Stream sinkStream;
        protected bool inDisk;
        protected bool isClosed;
        protected string id;
        protected bool isResponse;
        protected HttpContext context;

        public FilterSaveLog(HttpContext Context, Stream Sink, string FileName, string Id)
        {
            // One lock per file name
            if (String.IsNullOrWhiteSpace(fileNameGlobal) || fileNameGlobal.ToUpper() != fileNameGlobal.ToUpper())
            {
                fileNameGlobal = FileName;
                writeLock = new object();
            }
            context = Context;
            fileName = FileName;
            id = Id;
            sinkStream = Sink;
            inDisk = false;
            isClosed = false;
        }

        public void SetFilter(bool IsResponse)
        {


            isResponse = IsResponse;
            id = (isResponse ? "Reponse " : "Request ") + id;

            //
            // For Request only read the incoming stream and log it as it will not be "filtered" for a WCF request
            //
            if (!IsResponse)
            {
                AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
                AppendToFile(id);

                if (context.Request.InputStream.Length > 0)
                {
                    context.Request.InputStream.Position = 0;
                    byte[] rawBytes = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(rawBytes, 0, rawBytes.Length);
                    context.Request.InputStream.Position = 0;

                    AppendToFile(rawBytes);
                }
                else
                {
                    AppendToFile("(no body)");
                }
            }

        }

        public void AppendToFile(string Text)
        {
            byte[] strArray = Encoding.UTF8.GetBytes(Text);
            AppendToFile(strArray);

        }

        public void AppendToFile(byte[] RawBytes)
        {
            bool myLock = System.Threading.Monitor.TryEnter(writeLock, 100);


            if (myLock)
            {
                try
                {

                    using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        stream.Position = stream.Length;
                        stream.Write(RawBytes, 0, RawBytes.Length);
                        stream.WriteByte(13);
                        stream.WriteByte(10);

                    }

                }
                catch (Exception ex)
                {
                    string str = string.Format("Unable to create log. Type: {0} Message: {1}\nStack:{2}", ex, ex.Message, ex.StackTrace);
                    System.Diagnostics.Debug.WriteLine(str);
                    System.Diagnostics.Debug.Flush();


                }
                finally
                {
                    System.Threading.Monitor.Exit(writeLock);


                }
            }


        }


        public override bool CanRead
        {
            get { return sinkStream.CanRead; }
        }

        public override bool CanSeek
        {
            get { return sinkStream.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return sinkStream.CanWrite; }
        }

        public override long Length
        {
            get
            {
                return sinkStream.Length;
            }
        }

        public override long Position
        {
            get { return sinkStream.Position; }
            set { sinkStream.Position = value; }
        }

        //
        // For WCF this code will never be reached
        //
        public override int Read(byte[] buffer, int offset, int count)
        {
            int c = sinkStream.Read(buffer, offset, count);
            return c;
        }

        public override long Seek(long offset, System.IO.SeekOrigin direction)
        {
            return sinkStream.Seek(offset, direction);
        }

        public override void SetLength(long length)
        {
            sinkStream.SetLength(length);
        }

        public override void Close()
        {

            sinkStream.Close();
            isClosed = true;
        }

        public override void Flush()
        {

            sinkStream.Flush();
        }

        // For streamed responses (i.e. not buffered) there will be more than one Response (but the id will match the Request)
        public override void Write(byte[] buffer, int offset, int count)
        {
            sinkStream.Write(buffer, offset, count);
            AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
            AppendToFile(id);
            AppendToFile(buffer);
        }

    }
}

It should create log file in the folder LogPath with request and response XML.

How can a file be copied?

Use the shutil module.

copyfile(src, dst)

Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.

Take a look at filesys for all the file and directory handling functions available in standard Python modules.

Link a .css on another folder

I dont get it clearly, do you want to link an external css as the structure of files you defined above? If yes then just use the link tag :

    <link rel="stylesheet" type="text/css" href="file.css">

so basically for files that are under your website folder (folder containing your index) you directly call it. For each successive folder use the "/" for example in your case :

    <link rel="stylesheet" type="text/css" href="Fonts/Font1/file name">
    <link rel="stylesheet" type="text/css" href="Fonts/Font2/file name">

Android - R cannot be resolved to a variable

Agree it is probably due to a problem in resources that is preventing build of R.Java in gen. In my case a cut n paste had given a duplicate app name in string. Sort the fault, delete gen directory and clean.

How to getElementByClass instead of GetElementById with JavaScript?

The getElementsByClassName method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:

function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available
    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}

Usage:

function toggle_visibility(className) {
   var elements = getElementsByClassName(document, className),
       n = elements.length;
   for (var i = 0; i < n; i++) {
     var e = elements[i];

     if(e.style.display == 'block') {
       e.style.display = 'none';
     } else {
       e.style.display = 'block';
     }
  }
}

How to insert a file in MySQL database?

File size by MySQL type:

  • TINYBLOB 255 bytes = 0.000255 Mb
  • BLOB 65535 bytes = 0.0655 Mb
  • MEDIUMBLOB 16777215 bytes = 16.78 Mb
  • LONGBLOB 4294967295 bytes = 4294.97 Mb = 4.295 Gb

Why is it important to override GetHashCode when Equals method is overridden?

How about:

public override int GetHashCode()
{
    return string.Format("{0}_{1}_{2}", prop1, prop2, prop3).GetHashCode();
}

Assuming performance is not an issue :)

Best way to verify string is empty or null

In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.

Take an example where I have an input object which was converted into string using String.valueOf(obj) API. In case obj reference is null, String.valueOf returns "null" instead of null.

When you attempt to use, StringUtils.isBlank("null"), API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.

Creating a LinkedList class from scratch

If you're actually building a real system, then yes, you'd typically just use the stuff in the standard library if what you need is available there. That said, don't think of this as a pointless exercise. It's good to understand how things work, and understanding linked lists is an important step towards understanding more complex data structures, many of which don't exist in the standard libraries.

There are some differences between the way you're creating a linked list and the way the Java collections API does it. The Collections API is trying to adhere to a more complicated interface. The Collections API linked list is also a doubly linked list, while you're building a singly linked list. What you're doing is more appropriate for a class assignment.

With your LinkedList class, an instance will always be a list of at least one element. With this kind of setup you'd use null for when you need an empty list.

Think of next as being "the rest of the list". In fact, many similar implementations use the name "tail" instead of "next".

Here's a diagram of a LinkedList containing 3 elements:

linked list diagram

Note that it's a LinkedList object pointing to a word ("Hello") and a list of 2 elements. The list of 2 elements has a word ("Stack") and a list of 1 element. That list of 1 element has a word ("Overflow") and an empty list (null). So you can treat next as just another list that happens to be one element shorter.

You may want to add another constructor that just takes a String, and sets next to null. This would be for creating a 1-element list.

To append, you check if next is null. If it is, create a new one element list and set next to that.

next = new LinkedList(word);

If next isn't null, then append to next instead.

next.append(word);

This is the recursive approach, which is the least amount of code. You can turn that into an iterative solution which would be more efficient in Java*, and wouldn't risk a stack overflow with very long lists, but I'm guessing that level of complexity isn't needed for your assignment.


* Some languages have tail call elimination, which is an optimization that lets the language implementation convert "tail calls" (a call to another function as the very last step before returning) into (effectively) a "goto". This makes such code completely avoid using the stack, which makes it safer (you can't overflow the stack if you don't use the stack) and typically more efficient. Scheme is probably the most well known example of a language with this feature.

How to launch Windows Scheduler by command-line?

Here is an example I just used:

at 8am /EVERY:M,T,W,Th,F,S,Su cmd /c c:\myapp.exe

The result was:

Added a new job with job ID = 1

Then, to check my work:

at

installation app blocked by play protect

Try to create a new key store and replace with old one, then rebuild a new signed APK.

Update: Note that if you're using a http connection with server ,you should use SSL.

Take a look at: https://developer.android.com/distribute/best-practices/develop/understand-play-policies

How can you print multiple variables inside a string using printf?

Change the line where you print the output to:

printf("\nmaximum of %d and %d is = %d",a,b,c);

See the docs here

How to connect to remote Oracle DB with PL/SQL Developer?

I am facing to this problem so many times till I have 32bit PL/SQL Developer and 64bit Oracle DB or Oracle Client.

The solution is:

  1. install a 32bit client.
  2. set PLSQL DEV-Tools-Preferencies-Oracle Home to new 32bit client Home
  3. set PLSQL DEV-Tools-Preferencies-OCI to new 32 bit home /bin/oci.dll For example: c:\app\admin\product\11.2.0\client_1\BIN\oci.dll
  4. Save and restart PLSQL DEV.

Edit or create a TNSNAMES.ORA file in c:\app\admin\product\11.2.0\client_1\NETWORK\admin folder like mentioned above.

Try with TNSPING in console like

C:>tnsping ORCL

If still have problem, set the TNS_ADMIN Enviroment properties value pointing to the folder where the TNSNAMES.ORA located, like: c:\app\admin\product\11.2.0\client_1\network\admin

Pull request vs Merge request

As mentioned in previous answers, both serve almost same purpose. Personally I like git rebase and merge request (as in gitlab). It takes burden off of the reviewer/maintainer, making sure that while adding merge request, the feature branch includes all of the latest commits done on main branch after feature branch is created. Here is a very useful article explaining rebase in detail: https://git-scm.com/book/en/v2/Git-Branching-Rebasing

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

I m using this in my spring boot application

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public ResponseEntity<?> match(@PathVariable String matchId, @RequestBody String body,
            HttpServletRequest request, HttpServletResponse response) {

    Product p;
    try {
      p = service.getProduct(request.getProductId());
    } catch(Exception ex) {
       return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity(p, HttpStatus.OK);
}

How can I set my Cygwin PATH to find javac?

Although all other answers are technically correct, I would recommend you adding the custom path to the beginning of your PATH, not at the end. That way it would be the first place to look for instead of the last:

Add to bottom of ~/.bash_profile:

export PATH="/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/":$PATH

That way if you have more than one java or javac it will use the one you provided first.

R adding days to a date

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R> 
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
 and 42 methods, of which 31 are possibly relevant:
   addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
   getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
   getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
   getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
   getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
   setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
   setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R> 

How do I auto-submit an upload form when a file is selected?

HTML

<form id="xtarget" action="upload.php">
<input type="file" id="xfilename">
</form>

JAVASCRIPT PURE

<script type="text/javascript">
window.onload = function() {
    document.getElementById("xfilename").onchange = function() {
        document.getElementById("xtarget").submit();
    }
};
</script>

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Just default the variable to the expected type:

(number=1) => ...
(number=1.0) => ...
(string='str') ...

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Some special characters give this type of error, so use

$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";

How to set top-left alignment for UILabel for iOS application?

The simplest and easiest way is to embed Label in StackView and setting StackView's Axis to Horizontal, Alignment to Top in Attribute Inspector from Storyboard like shown here.

Get response from PHP file using AJAX

<?php echo 'apple'; ?> is pretty much literally all you need on the server.

as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

success: function(data) {
   alert(data); // apple
}

VB.NET Switch Statement GoTo Case

I'm not sure it's a good idea to use a GoTo but if you do want to use it, you can do something like this:

Select Case parameter 
    Case "userID"
        ' does something here.
    Case "packageID"
        ' does something here.
    Case "mvrType" 
        If otherFactor Then 
            ' does something here. 
        Else 
            GoTo caseElse
        End If 
    Case Else
caseElse:
        ' does some processing... 
End Select

As I said, although it works, GoTo is not good practice, so here are some alternative solutions:

Using elseif...

If parameter = "userID" Then
    ' does something here.
ElseIf parameter = "packageID" Then
    ' does something here.
ElseIf parameter = "mvrType" AndAlso otherFactor Then
    ' does something here.
Else
    'does some processing...
End If

Using a boolean value...

Dim doSomething As Boolean

Select Case parameter
Case "userID"
     ' does something here.
Case "packageID"
     ' does something here.
Case "mvrType"
     If otherFactor Then
          ' does something here. 
     Else
          doSomething = True
     End If
Case Else
     doSomething = True
End Select

If doSomething Then
     ' does some processing... 
End If

Instead of setting a boolean variable you could also call a method directly in both cases...

iFrame src change event detection?

Note: The snippet would only work if the iframe is with the same origin.

Other answers proposed the load event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.

Here's a plain JavaScript solution:

_x000D_
_x000D_
function iframeURLChange(iframe, callback) {_x000D_
    var unloadHandler = function () {_x000D_
        // Timeout needed because the URL changes immediately after_x000D_
        // the `unload` event is dispatched._x000D_
        setTimeout(function () {_x000D_
            callback(iframe.contentWindow.location.href);_x000D_
        }, 0);_x000D_
    };_x000D_
_x000D_
    function attachUnload() {_x000D_
        // Remove the unloadHandler in case it was already attached._x000D_
        // Otherwise, the change will be dispatched twice._x000D_
        iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
        iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
    }_x000D_
_x000D_
    iframe.addEventListener("load", attachUnload);_x000D_
    attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
    console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
_x000D_
_x000D_

This will successfully track the src attribute changes, as well as any URL changes made from within the iframe itself.

Tested in all modern browsers.

I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.

How to add Tomcat Server in eclipse

If by mistake, you have deleted your Tomcat Server and Eclipse is not showing more options (Next button will be inactive) then in this case follow the bellow steps:

  1. First remove the two files from the following path:

    • Path : workspace/.metadata/.plugins/org.eclipse.runtime/.settings/
    • And that two files are :

      1. org.eclipse.wst.server.core.prefs
      2. org.eclipse.jst/server.tomcat.core.prefs
    • After deleting/removing the above two files from the workspace, Restart the Eclipse IDE.

    • Change to the Server View, Right Click 'New', Window 'Define a New Server' is shown, --> Select the Apache Folder, choose Tomcat-Version

    • Browse to the unzipped 'Apache-Tomcat folder', choose the second level

    • Now you are able to add/configure your new Tomcat Server. (Now you will see the 'Next' button will become active, and you can then follow the normal instructions)

How to determine whether an object has a given property in JavaScript

Object has property:

If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():

if (x.hasOwnProperty('y')) { 
  // ......
}

Object or its prototype has a property:

You can use the in operator to test for properties that are inherited as well.

if ('y' in x) {
  // ......
}

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

I'm using ReactJs and used import 'core-js/es6/string'; at the start of index.js to solve my problem.

I'm also using import 'react-app-polyfill/ie11'; to support running React in IE11.

react-app-polyfill

This package includes polyfills for various browsers. It includes minimum requirements and commonly used language features used by Create React App projects.

https://github.com/facebook/create-react-app/blob/master/packages/react-app-polyfill/README.md

Quicksort: Choosing the pivot

It depends on your requirements. Choosing a pivot at random makes it harder to create a data set that generates O(N^2) performance. 'Median-of-three' (first, last, middle) is also a way of avoiding problems. Beware of relative performance of comparisons, though; if your comparisons are costly, then Mo3 does more comparisons than choosing (a single pivot value) at random. Database records can be costly to compare.


Update: Pulling comments into answer.

mdkess asserted:

'Median of 3' is NOT first last middle. Choose three random indexes, and take the middle value of this. The whole point is to make sure that your choice of pivots is not deterministic - if it is, worst case data can be quite easily generated.

To which I responded:

  • Analysis Of Hoare's Find Algorithm With Median-Of-Three Partition (1997) by P Kirschenhofer, H Prodinger, C Martínez supports your contention (that 'median-of-three' is three random items).

  • There's an article described at portal.acm.org that is about 'The Worst Case Permutation for Median-of-Three Quicksort' by Hannu Erkiö, published in The Computer Journal, Vol 27, No 3, 1984. [Update 2012-02-26: Got the text for the article. Section 2 'The Algorithm' begins: 'By using the median of the first, middle and last elements of A[L:R], efficient partitions into parts of fairly equal sizes can be achieved in most practical situations.' Thus, it is discussing the first-middle-last Mo3 approach.]

  • Another short article that is interesting is by M. D. McIlroy, "A Killer Adversary for Quicksort", published in Software-Practice and Experience, Vol. 29(0), 1–4 (0 1999). It explains how to make almost any Quicksort behave quadratically.

  • AT&T Bell Labs Tech Journal, Oct 1984 "Theory and Practice in the Construction of a Working Sort Routine" states "Hoare suggested partitioning around the median of several randomly selected lines. Sedgewick [...] recommended choosing the median of the first [...] last [...] and middle". This indicates that both techniques for 'median-of-three' are known in the literature. (Update 2014-11-23: The article appears to be available at IEEE Xplore or from Wiley — if you have membership or are prepared to pay a fee.)

  • 'Engineering a Sort Function' by J L Bentley and M D McIlroy, published in Software Practice and Experience, Vol 23(11), November 1993, goes into an extensive discussion of the issues, and they chose an adaptive partitioning algorithm based in part on the size of the data set. There is a lot of discussion of trade-offs for various approaches.

  • A Google search for 'median-of-three' works pretty well for further tracking.

Thanks for the information; I had only encountered the deterministic 'median-of-three' before.

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

How to save to local storage using Flutter?

I think If you are going to store large amount of data in local storage you can use sqflite library. It is very easy to setup and I have personally used for some test project and it works fine.

https://github.com/tekartik/sqflite This a tutorial - https://proandroiddev.com/flutter-bookshelf-app-part-2-personal-notes-and-database-integration-a3b47a84c57

If you want to store data in cloud you can use firebase. It is solid service provide by google.

https://firebase.google.com/docs/flutter/setup

Invoke JSF managed bean action on page load

JSF 1.0 / 1.1

Just put the desired logic in the constructor of the request scoped bean associated with the JSF page.

public Bean() {
    // Do your stuff here.
}

JSF 1.2 / 2.x

Use @PostConstruct annotated method on a request or view scoped bean. It will be executed after construction and initialization/setting of all managed properties and injected dependencies.

@PostConstruct
public void init() {
    // Do your stuff here.
}

This is strongly recommended over constructor in case you're using a bean management framework which uses proxies, such as CDI, because the constructor may not be called at the times you'd expect it.

JSF 2.0 / 2.1

Alternatively, use <f:event type="preRenderView"> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:event type="preRenderView" listener="#{bean.onload}" />
</f:metadata>
public void onload() { 
    // Do your stuff here.
}

JSF 2.2+

Alternatively, use <f:viewAction> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
public void onload() { 
    // Do your stuff here.
}

Note that this can return a String navigation case if necessary. It will be interpreted as a redirect (so you do not need a ?faces-redirect=true here).

public String onload() { 
    // Do your stuff here.
    // ...
    return "some.xhtml";
}

See also:

Why does DEBUG=False setting make my django Static Files Access fail?

I agree with Marek Sapkota answer; But you can still use django URFConf to reallocate the url, if static file is requested.

Step 1: Define a STATIC_ROOT path in settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Step 2: Then collect the static files

$ python manage.py collectstatic

Step 3: Now define your URLConf that if static is in the beginning of url, access files from the static folder staticfiles. NOTE: This is your project's urls.py file:

from django.urls import re_path
from django.views.static import serve

urlpattern += [
  re_path(r'^static/(?:.*)$', serve, {'document_root': settings.STATIC_ROOT, })
]

Casting objects in Java

The example you are referring to is called Upcasting in java.

It creates a subclass object with a super class variable pointing to it.

The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.

For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine

class Machine{

    public void start(){

        System.out.println("Machine Started");
    }
}

class Camera extends Machine{
     public void start(){

            System.out.println("Camera Started");
        }
     public void snap(){
         System.out.println("Photo taken");
     }
 }
Machine machine1 = new Camera();
machine1.start();

If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started" The variable is still a reference of Machine class. If you attempt machine1.snap(); the code will not compile

The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap() wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()). You can not ask a machine reference to take a snap. :)

Twitter Bootstrap hide css class and jQuery

This is what I do for those situations:

I don't start the html element with class 'hide', but I put style="display: none".

This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.

Example:

<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>

or

<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>

Later on, you can run all the following that will work:

$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()

You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

I had a similar issue which i solved by making two changes

  1. added below entry in application.yaml file

    spring: jackson: serialization.write_dates_as_timestamps: false

  2. add below two annotations in pojo

    1. @JsonDeserialize(using = LocalDateDeserializer.class)
    2. @JsonSerialize(using = LocalDateSerializer.class)

    sample example

    import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class Customer { //your fields ... @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = LocalDateSerializer.class) protected LocalDate birthdate; }

then the following json requests worked for me

  1. sample request format as string

{ "birthdate": "2019-11-28" }

  1. sample request format as array

{ "birthdate":[2019,11,18] }

Hope it helps!!

Oracle Add 1 hour in SQL

To add/subtract from a DATE, you have 2 options :

Method #1 : The easiest way is to use + and - to add/subtract days, hours, minutes, seconds, etc.. from a DATE, and ADD_MONTHS() function to add/subtract months and years from a DATE. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS() and no add_years(), because from months, you can get years (1 year = 12 months).

Let's try them :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')             FROM dual;        -- prints current date:    19-OCT-2019 20:42:02 
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS')    FROM dual;        -- prints date + 1 hour:   19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS')  FROM dual;        -- prints date + 1 minute: 19-OCT-2019 20:43:02 
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 second: 19-OCT-2019 20:42:03 
-- Same goes for subtraction.

SELECT SYSDATE                  FROM dual;       -- prints current date:     19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1)   FROM dual;       -- prints date + 1 month:   19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12)  FROM dual;       -- prints date + 1 year:    19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3)  FROM dual;       -- prints date - 3 months:  19-JUL-19

Method #2 : Using INTERVALs, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..) Examples :

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS')                                        FROM dual;        -- prints current date:                 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS')                  FROM dual;        -- prints date + 1 hour:                19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 minute:              19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS')                FROM dual;        -- prints date + 1 second:              19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual;        -- prints date + 1 hour and 5 minutes:  19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS')        FROM dual;        -- prints date + 3 days and 1 hour:     22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS')      FROM dual;        -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15

Where is web.xml in Eclipse Dynamic Web Project

Follow below steps to generate web.xml in Eclipse with existing Dynamic Web Project

  1. Right Click on Created Dynamic Web Project
  2. Mouse Over Java EE Tools
  3. Click on Generate Deployment Descriptor Stub
  4. Now you are able to see web.xml file on WEB-INF folder

enter image description here

How do I show the changes which have been staged?

If you'd be interested in a visual side-by-side view, the diffuse visual diff tool can do that. It will even show three panes if some but not all changes are staged. In the case of conflicts, there will even be four panes.

Screenshot of diffuse with staged and unstaged edits

Invoke it with

diffuse -m

in your Git working copy.

If you ask me, the best visual differ I've seen for a decade. Also, it is not specific to Git: It interoperates with a plethora of other VCS, including SVN, Mercurial, Bazaar, ...

See also: Show both staged & working tree in git diff?

Loop structure inside gnuplot?

Use the following if you have discrete columns to plot in a graph

do for [indx in "2 3 7 8"] {
  column = indx + 0
  plot ifile using 1:column ;  
}

How to get class object's name as a string in Javascript?

As a more elementary situation it would be nice IF this had a property that could reference it's referring variable (heads or tails) but unfortunately it only references the instantiation of the new coinSide object.

javascript:  /* it would be nice but ... a solution NOT! */
function coinSide(){this.ref=this};
/* can .ref be set so as to identify it's referring variable? (heads or tails) */
heads = new coinSide();
tails = new coinSide();
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);
alert(["FF's Gecko engine shows:\n\ntoss.toSource()  is  ", toss.toSource()])

which always displays

[object Object]

and Firefox's Gecko engine shows:

toss.toSource()  is  ,#1={ref:#1#}

Of course, in this example, to resolve #1, and hence toss, it's simple enough to test toss==heads and toss==tails. This question, which is really asking if javascript has a call-by-name mechanism, motivates consideration of the counterpart, is there a call-by-value mechanism to determine the ACTUAL value of a variable? The example demonstrates that the "values" of both heads and tails are identical, yet alert(heads==tails) is false.

The self-reference can be coerced as follows:
(avoiding the object space hunt and possible ambiguities as noted in the How to get class object's name as a string in Javascript? solution)

javascript:
function assign(n,v){ eval( n +"="+ v ); eval( n +".ref='"+ n +"'" ) }
function coinSide(){};
assign("heads", "new coinSide()");
assign("tails", "new coinSide()");
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);

to display heads or tails.

It is perhaps an anathema to the essence of Javascript's language design, as an interpreted prototyping functional language, to have such capabilities as primitives.

A final consideration:

 javascript:
     item=new Object(); refName="item"; deferAgain="refName";
     alert([deferAgain,eval(deferAgain),eval(eval(deferAgain))].join('\n'));

so, as stipulated ...

javascript:
  function bindDIV(objName){ 
    return eval( objName +'=new someObject("'+objName+'")' )
  };
  function someObject(objName){
    this.div="\n<DIV onclick='window.opener."+   /* window.opener - hiccup!! */
               objName+
             ".someFunction()'>clickable DIV</DIV>\n";
    this.someFunction=function(){alert(['my variable object name is ',objName])}
  };
  with(window.open('','test').document){         /*     see above hiccup    */
    write('<html>'+
      bindDIV('DIVobj1').div+
      bindDIV('DIV2').div+
      (alias=bindDIV('multiply')).div+
      'an aliased DIV clone'+multiply.div+
      '</html>');
    close();
  };
  void (0);

Is there a better way ... ?

"better" as in easier? Easier to program? Easier to understand? Easier as in faster execution? Or is it as in "... and now for something completely different"?

pull/push from multiple remote locations

This answer is different from the prior answers because it avoids the needless and asymmetric use of the --push option in the set-url command of git remote. In this way, both URLs are symmetric in their configuration. For skeptics, the git config as shown by cat ./.git/config looks different with versus without this option.

  1. Clone from the first URL:
git clone [email protected]:myuser/myrepo.git
  1. Add the second URL:
git remote set-url --add origin [email protected]:myuser/myrepo.git
  1. Confirm that both URLs are listed for push:
$ git remote -v
origin  [email protected]:myuser/myrepo.git (fetch)
origin  [email protected]:myuser/myrepo.git (push)
origin  [email protected]:myuser/myrepo.git (push)

$ git config --local --get-regexp ^remote\..+\.url$
remote.origin.url [email protected]:myuser/myrepo.git
remote.origin.url [email protected]:myuser/myrepo.git
  1. Push to all URLs in sequence:
git push

To delete an added URL:

git remote set-url --delete origin [email protected]:myuser/myrepo.git

Telegram Bot - how to get a group chat id?

My second Solution for the error {"ok":true,"result":[]}

  1. Go in your Telegram Group
  2. Add new User (Invite)
  3. Search for "getidsbot" => @getidsbot
  4. Message: /start@getidsbot
  5. Now you see the ID. looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!
  6. Kick the bot from the Group.
  7. Now go to the Webbrowser an send this line (Test Message):
https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test

Edit the API Token and the Group-ID!

How to get the HTML for a DOM element in javascript

First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.

<div><span><b>This is in bold</b></span></div>

=> <div id="wrap"><div><span><b>This is in bold</b></span></div></div>

and then:

var e=document.getElementById("wrap");
var content=e.innerHTML;

Note that outerHTML is not cross-browser compatible.

Sum all the elements java arraylist

I haven't tested it but it should work.

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum = sum + m.get(i);
    }
    return sum;
}

Find records from one table which don't exist in another

SELECT t1.ColumnID,
CASE 
    WHEN NOT EXISTS( SELECT t2.FieldText  
                     FROM Table t2 
                     WHERE t2.ColumnID = t1.ColumnID) 
    THEN t1.FieldText
    ELSE t2.FieldText
END FieldText       
FROM Table1 t1, Table2 t2

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

let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();

if (dd<10) {
    dd = '0' + dd;
}
if (mm<10) {
    mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;

How do you set your pythonpath in an already-created virtualenv?

The comment by @s29 should be an answer:

One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do

mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path

If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth

Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/

Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv

Drop a temporary table if it exists

From SQL Server 2016 you can just use

 DROP TABLE IF EXISTS ##CLIENTS_KEYWORD

On previous versions you can use

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
   client_id INT
)

You could also consider truncating the table instead rather than dropping and recreating.

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
  TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
  CREATE TABLE ##CLIENTS_KEYWORD
  (
     client_id INT
  ) 

C#: How to access an Excel cell?

I think, that you have to declare the associated sheet!

Try something like this

objsheet(1).Cells[i,j].Value;

Eclipse comment/uncomment shortcut?

Source -> Remove Block Comment

link

enter image description here

Pass Arraylist as argument to function

It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

public void AnalyseArray(ArrayList<Integer> theList){}

and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

PS: Some maybe helpful Information to Variables and parameters.

Pandas dataframe fillna() only some columns in place

Here's how you can do it all in one line:

df[['a', 'b']].fillna(value=0, inplace=True)

Breakdown: df[['a', 'b']] selects the columns you want to fill NaN values for, value=0 tells it to fill NaNs with zero, and inplace=True will make the changes permanent, without having to make a copy of the object.

Circle drawing with SVG's arc path

Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.

function(cx, cy, r, deg){
    var theta = deg*Math.PI/180,
        dx = r*Math.cos(theta),
        dy = -r*Math.sin(theta);
    return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}

Ruby on Rails: How do I add placeholder text to a f.text_field?

I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:

text_field_tag :attr, "", placeholder: "placeholder text"

How to parse a month name (string) to an integer for comparison in C#?

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

Check if a row exists using old mysql_* API

function checkLectureStatus($lectureName) {
  global $con;
  $lectureName = mysql_real_escape_string($lectureName);
  $sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
  $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if (mysql_fetch_row($result)) {
    return 'Assigned';
  }
  return 'Available';
}

however you have to use some abstraction library for the database access.
the code would become

function checkLectureStatus($lectureName) {
  $res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
  if($res) {
    return 'Assigned';
  }
  return 'Available';
}

Weird PHP error: 'Can't use function return value in write context'

This error is quite right and highlights a contextual syntax issue. Can be reproduced by performing any kind "non-assignable" syntax. For instance:

function Syntax($hello) { .... then attempt to call the function as though a property and assign a value.... $this->Syntax('Hello') = 'World';

The above error will be thrown because syntactially the statement is wrong. The right assignment of 'World' cannot be written in the context you have used (i.e. syntactically incorrect for this context). 'Cannot use function return value' or it could read 'Cannot assign the right-hand value to the function because its read-only'

The specific error in the OPs code is as highlighted, using brackets instead of square brackets.

Unfamiliar symbol in algorithm: what does ? mean?

The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.

If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.

Active Directory LDAP Query by sAMAccountName and Domain

You can use following queries

Users whose Logon Name(Pre-Windows 2000) is equal to John

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(sAMAccountName=**John**))

All Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370))

Enabled Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(!userAccountControl:1.2.840.113556.1.4.803:=2))

Disabled Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(userAccountControl:1.2.840.113556.1.4.803:=2))

LockedOut Users

(&(objectCategory=person)(objectClass=user)(!sAMAccountType=805306370)(lockouttime>=1))

TypeError: a bytes-like object is required, not 'str' in python and CSV

just change wb to w

outfile=open('./immates.csv','wb')

to

outfile=open('./immates.csv','w')

Tomcat manager/html is not available?

I had the situatuion when tomcat manager did not start. I had this exception in my logs/manager.DDD-MM-YY.log:

org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter CSRF
java.lang.ClassNotFoundException: org.apache.catalina.filters.CsrfPreventionFilter
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        ...

This exception was raised because I used a version of tomcat that hadn't CSRF prevention filter. Tomcat 6.0.24 doesn't have the CSRF prevention filter in it. The first version that has it is the 6.0.30 version (at least. according to the changelog). As a result, Tomcat Manager was uncompatible with version of Tomcat that I used. I've digged description of this issue here: http://blog.techstacks.com/.m/2009/05/tomcat-management-setting-up-tomcat/comments/

Steps to fix it:

  1. Check version of tomcat installed by running "sh version.sh" from your tomcat/bin directory
  2. Download corresponding version of tomcat
  3. Stop tomcat
  4. Remove your webapps/manager directory and copy manager application from distributive that you've downloaded.
  5. Start tomcat

Now you should be able to access tomcat manager.

How can I convert an HTML table to CSV?

This method is not really a library OR a program, but for ad hoc conversions you can

  • put the HTML for a table in a text file called something.xls
  • open it with a spreadsheet
  • save it as CSV.

I know this works with Excel, and I believe I've done it with the OpenOffice spreadsheet.

But you probably would prefer a Perl or Ruby script...

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

Get Memory Usage in Android

Check the Debug class. http://developer.android.com/reference/android/os/Debug.html i.e. Debug.getNativeHeapAllocatedSize()

It has methods to get the used native heap, which is i.e. used by external bitmaps in your app. For the heap that the app is using internally, you can see that in the DDMS tool that comes with the Android SDK and is also available via Eclipse.

The native heap + the heap as indicated in the DDMS make up the total heap that your app is allocating.

For CPU usage I'm not sure if there's anything available via API/SDK.

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You don't have the namespace the Login class is in as a reference.

Add the following to the form that uses the Login class:

using FootballLeagueSystem;

When you want to use a class in another namespace, you have to tell the compiler where to find it. In this case, Login is inside the FootballLeagueSystem namespace, or : FootballLeagueSystem.Login is the fully qualified namespace.

As a commenter pointed out, you declare the Login class inside the FootballLeagueSystem namespace, but you're using it in the FootballLeague namespace.

How to easily map c++ enums to strings

I remember having answered this elsewhere on StackOverflow. Repeating it here. Basically it's a solution based on variadic macros, and is pretty easy to use:

#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \
inline std::ostream& operator<<(std::ostream& os, name value) { \
std::string enumName = #name; \
std::string str = #__VA_ARGS__; \
int len = str.length(); \
std::vector<std::string> strings; \
std::ostringstream temp; \
for(int i = 0; i < len; i ++) { \
if(isspace(str[i])) continue; \
        else if(str[i] == ',') { \
        strings.push_back(temp.str()); \
        temp.str(std::string());\
        } \
        else temp<< str[i]; \
} \
strings.push_back(temp.str()); \
os << enumName << "::" << strings[static_cast<int>(value)]; \
return os;} 

To use it in your code, simply do:

AWESOME_MAKE_ENUM(Animal,
    DOG,
    CAT,
    HORSE
);
auto dog = Animal::DOG;
std::cout<<dog;

Directory index forbidden by Options directive

Adding this in conf.d fixed this issue for me.

Options +Indexes +FollowSymLinks

How do I split an int into its digits?

The following will do the trick

void splitNumber(std::list<int>& digits, int number) {
  if (0 == number) { 
    digits.push_back(0);
  } else {
    while (number != 0) {
      int last = number % 10;
      digits.push_front(last);
      number = (number - last) / 10;
    }
  }
}

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

How can I create an executable JAR with dependencies using Maven?

See executable-jar-with-maven-example (GitHub)

Notes

Those pros and cons are provided by Stephan.


For Manual Deployment

  • Pros
  • Cons
    • Dependencies are out of the final jar.

Copy Dependencies to a specific directory

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
    <execution>
      <id>copy-dependencies</id>
      <phase>prepare-package</phase>
      <goals>
        <goal>copy-dependencies</goal>
      </goals>
      <configuration>
        <outputDirectory>${project.build.directory}/${project.build.finalName}.lib</outputDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>

Make the Jar Executable and Classpath Aware

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <configuration>
    <archive>
      <manifest>
        <addClasspath>true</addClasspath>
        <classpathPrefix>${project.build.finalName}.lib/</classpathPrefix>
        <mainClass>${fully.qualified.main.class}</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

At this point the jar is actually executable with external classpath elements.

$ java -jar target/${project.build.finalName}.jar

Make Deployable Archives

The jar file is only executable with the sibling ...lib/ directory. We need to make archives to deploy with the directory and its content.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-antrun-plugin</artifactId>
  <executions>
    <execution>
      <id>antrun-archive</id>
      <phase>package</phase>
      <goals>
        <goal>run</goal>
      </goals>
      <configuration>
        <target>
          <property name="final.name" value="${project.build.directory}/${project.build.finalName}"/>
          <property name="archive.includes" value="${project.build.finalName}.${project.packaging} ${project.build.finalName}.lib/*"/>
          <property name="tar.destfile" value="${final.name}.tar"/>
          <zip basedir="${project.build.directory}" destfile="${final.name}.zip" includes="${archive.includes}" />
          <tar basedir="${project.build.directory}" destfile="${tar.destfile}" includes="${archive.includes}" />
          <gzip src="${tar.destfile}" destfile="${tar.destfile}.gz" />
          <bzip2 src="${tar.destfile}" destfile="${tar.destfile}.bz2" />
        </target>
      </configuration>
    </execution>
  </executions>
</plugin>

Now you have target/${project.build.finalName}.(zip|tar|tar.bz2|tar.gz) which each contains the jar and lib/*.


Apache Maven Assembly Plugin

  • Pros
  • Cons
    • No class relocation support (use maven-shade-plugin if class relocation is needed).
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
      <configuration>
        <archive>
          <manifest>
            <mainClass>${fully.qualified.main.class}</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </execution>
  </executions>
</plugin>

You have target/${project.bulid.finalName}-jar-with-dependencies.jar.


Apache Maven Shade Plugin

  • Pros
  • Cons
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <executions>
    <execution>
      <goals>
        <goal>shade</goal>
      </goals>
      <configuration>
        <shadedArtifactAttached>true</shadedArtifactAttached>
        <transformers>
          <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
            <mainClass>${fully.qualified.main.class}</mainClass>
          </transformer>
        </transformers>
      </configuration>
    </execution>
  </executions>
</plugin>

You have target/${project.build.finalName}-shaded.jar.


onejar-maven-plugin

  • Pros
  • Cons
    • Not actively supported since 2012.
<plugin>
  <!--groupId>org.dstovall</groupId--> <!-- not available on the central -->
  <groupId>com.jolira</groupId>
  <artifactId>onejar-maven-plugin</artifactId>
  <executions>
    <execution>
      <configuration>
        <mainClass>${fully.qualified.main.class}</mainClass>
        <attachToBuild>true</attachToBuild>
        <!-- https://code.google.com/p/onejar-maven-plugin/issues/detail?id=8 -->
        <!--classifier>onejar</classifier-->
        <filename>${project.build.finalName}-onejar.${project.packaging}</filename>
      </configuration>
      <goals>
        <goal>one-jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Spring Boot Maven Plugin

  • Pros
  • Cons
    • Add potential unecessary Spring and Spring Boot related classes.
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <executions>
    <execution>
      <goals>
        <goal>repackage</goal>
      </goals>
      <configuration>
        <classifier>spring-boot</classifier>
        <mainClass>${fully.qualified.main.class}</mainClass>
      </configuration>
    </execution>
  </executions>
</plugin>

You have target/${project.bulid.finalName}-spring-boot.jar.

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I solved the same issue by removing:

compile fileTree(include: ['*.jar'], dir: 'libs')

and adding for each jar file:

compile files('libs/yourjarfile.jar')

if, elif, else statement issues in Bash

[ is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:

elif [

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

First make sure the PHP files themselves are UTF-8 encoded.

The meta tag is ignored by some browser. If you only use ASCII-characters, it doesn't matter anyway.

http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

header('Content-Type: text/html; charset=utf-8');

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

How to debug a bash script?

I found shellcheck utility and may be some folks find it interesting https://github.com/koalaman/shellcheck

A little example:

$ cat test.sh 
ARRAY=("hello there" world)

for x in $ARRAY; do
  echo $x
done

$ shellcheck test.sh 

In test.sh line 3:
for x in $ARRAY; do
         ^-- SC2128: Expanding an array without an index only gives the first element.

fix the bug, first try...

$ cat test.sh       
ARRAY=("hello there" world)

for x in ${ARRAY[@]}; do
  echo $x
done

$ shellcheck test.sh

In test.sh line 3:
for x in ${ARRAY[@]}; do
         ^-- SC2068: Double quote array expansions, otherwise they're like $* and break on spaces.

Let's try again...

$ cat test.sh 
ARRAY=("hello there" world)

for x in "${ARRAY[@]}"; do
  echo $x
done

$ shellcheck test.sh

find now!

It's just a small example.

T-SQL get SELECTed value of stored procedure

Try do this:

EXEC @SelectedValue = GetMyInt

Good MapReduce examples

Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.

For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner

Here is a wikipedia article explaining what map-reduce is all about

Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.

Personally, found this link quite useful to understand the concept

Copying the explanation provided in the blog (In case the link goes stale)

Finding Friends

MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.

I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:

3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research

They get grouped as:

3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]

Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:

3 : 3
4 : 3
5 : 2
8 : 2

The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...

The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.

The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of 1. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.

Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):

Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.

Assume the friends are stored as Person->[List of Friends], our friends list is then:

A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D

Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:

For map(A -> B C D) :

(A B) -> B C D
(A C) -> B C D
(A D) -> B C D

For map(B -> A C D E) : (Note that A comes before B in the key)

(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :

(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :

(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):

(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:

(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)

Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.

The result after reduction is:

(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)

Now when D visits B's profile, we can quickly look up (B D) and see that they have three friends in common, (A C E).

How to execute a raw update sql with dynamic binding in rails

It doesn't look like the Rails API exposes methods to do this generically. You could try accessing the underlying connection and using it's methods, e.g. for MySQL:

st = ActiveRecord::Base.connection.raw_connection.prepare("update table set f1=? where f2=? and f3=?")
st.execute(f1, f2, f3)
st.close

I'm not sure if there are other ramifications to doing this (connections left open, etc). I would trace the Rails code for a normal update to see what it's doing aside from the actual query.

Using prepared queries can save you a small amount of time in the database, but unless you're doing this a million times in a row, you'd probably be better off just building the update with normal Ruby substitution, e.g.

ActiveRecord::Base.connection.execute("update table set f1=#{ActiveRecord::Base.sanitize(f1)}")

or using ActiveRecord like the commenters said.

How to define hash tables in Bash?

I also used the bash4 way but I find and annoying bug.

I needed to update dynamically the associative array content so i used this way:

for instanceId in $instanceList
do
   aws cloudwatch describe-alarms --output json --alarm-name-prefix $instanceId| jq '.["MetricAlarms"][].StateValue'| xargs | grep -E 'ALARM|INSUFFICIENT_DATA'
   [ $? -eq 0 ] && statusCheck+=([$instanceId]="checkKO") || statusCheck+=([$instanceId]="allCheckOk"
done

I find out that with bash 4.3.11 appending to an existing key in the dict resulted in appending the value if already present. So for example after some repetion the content of the value was "checkKOcheckKOallCheckOK" and this was not good.

No problem with bash 4.3.39 where appenging an existent key means to substisture the actuale value if already present.

I solved this just cleaning/declaring the statusCheck associative array before the cicle:

unset statusCheck; declare -A statusCheck

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

How to parse JSON without JSON.NET library?

For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.

Example usage:

Given the json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

You could parse it into a RadComboBoxClientState object like this:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

I found that it was necessary to enter the architecture names by hand:

enter image description here

I don't know why this was necessary, i.e. why these values were not inherited from Xcode itself. But as soon as I did this, the problem went away.

Can Android do peer-to-peer ad-hoc networking?

You can use Alljoyn framework for Peer-to-Peer connectivity in Android. Its based on Ad-hoc networking and also Open source.

How to launch another aspx web page upon button click?

Use an html button and javascript? in javascript, window.location is used to change the url location of the current window, while window.open will open a new one

<input type="button" onclick="window.open('newPage.aspx', 'newPage');" />

Edit: Ah, just found this: If the ID of your form tag is form1, set this attribute in your asp button

OnClientClick="form1.target ='_blank';"

How do I delete NuGet packages that are not referenced by any project in my solution?

You can use Package Manager Console with command: Uninstall-Package PackageId to remove it, or just delete package folder from 'packages' folder under solution folder. More information about Package Manager Console you can find here: http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference

Reset AutoIncrement in SQL Server after Delete

If you're using MySQL, try this:

ALTER TABLE tablename AUTO_INCREMENT = 1

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
try
{
    playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

Image frame;
try
{
    frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
    return;
}

using (frame)
{
    using (var bitmap = new Bitmap(width, height))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.DrawImage(frame,
                             new Rectangle(0,
                                           0,
                                           width,
                                           height),
                             new Rectangle(0,
                                           0,
                                           frame.Width,
                                           frame.Height),
                             GraphicsUnit.Pixel);
            canvas.DrawImage(playbutton,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
            canvas.Save();
        }
        try
        {
            bitmap.Save(/*somekindofpath*/,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) { }
    }
}

endforeach in loops?

as an alternative syntax you can write foreach loops like so

foreach($arr as $item):
    //do stuff
endforeach;

This type of syntax is typically used when php is being used as a templating language as such

<?php foreach($arr as $item):?>
    <!--do stuff -->
<?php endforeach; ?>

List(of String) or Array or ArrayList

Sometimes I don't want to add items to a list when I instantiate it.

Instantiate a blank list

Dim blankList As List(Of String) = New List(Of String)

Add to the list

blankList.Add("Dis be part of me list") 'blankList is no longer blank, but you get the drift

Loop through the list

For Each item in blankList
  ' write code here, for example:
  Console.WriteLine(item)
Next

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

Querying DynamoDB by date

Given your current table structure this is not currently possible in DynamoDB. The huge challenge is to understand that the Hash key of the table (partition) should be treated as creating separate tables. In some ways this is really powerful (think of partition keys as creating a new table for each user or customer, etc...).

Queries can only be done in a single partition. That's really the end of the story. This means if you want to query by date (you'll want to use msec since epoch), then all the items you want to retrieve in a single query must have the same Hash (partition key).

I should qualify this. You absolutely can scan by the criterion you are looking for, that's no problem, but that means you will be looking at every single row in your table, and then checking if that row has a date that matches your parameters. This is really expensive, especially if you are in the business of storing events by date in the first place (i.e. you have a lot of rows.)

You may be tempted to put all the data in a single partition to solve the problem, and you absolutely can, however your throughput will be painfully low, given that each partition only receives a fraction of the total set amount.

The best thing to do is determine more useful partitions to create to save the data:

  • Do you really need to look at all the rows, or is it only the rows by a specific user?

  • Would it be okay to first narrow down the list by Month, and do multiple queries (one for each month)? Or by Year?

  • If you are doing time series analysis there are a couple of options, change the partition key to something computated on PUT to make the query easier, or use another aws product like kinesis which lends itself to append-only logging.

Convert YYYYMMDD to DATE

Use SELECT CONVERT(date, '20140327')

In your case,

SELECT [FIRST_NAME],
       [MIDDLE_NAME],
       [LAST_NAME],
       CONVERT(date, [GRADUATION_DATE])     
FROM mydb

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

If it happens when you try to install some package via composer just use this command COMPOSER_MEMORY_LIMIT=-1 composer require nameofpackage

Sass Variable in CSS calc() function

Interpolate:

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

For this case, border-box would also suffice:

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

Change select box option background color

You need to put background-color on the option tag and not the select tag...

select option {
    margin: 40px;
    background: rgba(0, 0, 0, 0.3);
    color: #fff;
    text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}

If you want to style each one of the option tags.. use the css attribute selector:

_x000D_
_x000D_
select option {_x000D_
  margin: 40px;_x000D_
  background: rgba(0, 0, 0, 0.3);_x000D_
  color: #fff;_x000D_
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);_x000D_
}_x000D_
_x000D_
select option[value="1"] {_x000D_
  background: rgba(100, 100, 100, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="2"] {_x000D_
  background: rgba(150, 150, 150, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="3"] {_x000D_
  background: rgba(200, 200, 200, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="4"] {_x000D_
  background: rgba(250, 250, 250, 0.3);_x000D_
}
_x000D_
<select>_x000D_
  <option value="">Please choose</option>_x000D_
  <option value="1">Option 1</option>_x000D_
  <option value="2">Option 2</option>_x000D_
  <option value="3">Option 3</option>_x000D_
  <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_