Programs & Examples On #Smb

Server Message Block, network-protocol for sharing files and printers implemented by Windows, Samba and others

How do you force a CIFS connection to unmount

There's a -f option to umount that you can try:

umount -f /mnt/fileshare

Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.

You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.

Single vs Double quotes (' vs ")

If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of RSI.

fopen deprecated warning

Consider using a portability library like glib or the apache portable runtime. These usually provide safe, portable alternatives to calls like these. It's a good thing too, because these insecure calls are deprecated in most modern environments.

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

send checkbox value in PHP form

If the checkbox is checked you will get a value for it in your $_POST array. If it isn't the element will be omitted from the array altogether.

The easiest way to test it is like this:

if (isset($_POST['myCheckbox'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

For your code, add it immediately below the other preprocessing:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

if (isset($_POST['newsletter'])) {
  $newsletter = "yes";
} else {
  $newsletter = "no";
}

You'll also need to change the HTML slightly. Change this line:

<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter<br>

to this:

<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up   for newsletter<br>
                                      ^^^ remove square brackets here.

Call child method from parent

Here my demo: https://stackblitz.com/edit/react-dgz1ee?file=styles.css

I am using useEffect to call the children component's methods. I have tried with Proxy and Setter_Getter but sor far useEffect seems to be the more convenient way to call a child method from parent. To use Proxy and Setter_Getter it seems there is some subtlety to overcome first, because the element firstly rendered is an objectLike's element through the ref.current return => <div/>'s specificity. Concerning useEffect, you can also leverage on this approach to set the parent's state depending on what you want to do with the children.

In the demo's link I have provided, you will find my full ReactJS' code with my draftwork inside's so you can appreciate the workflow of my solution.

Here I am providing you my ReactJS' snippet with the relevant code only. :

import React, {
  Component,
  createRef,
  forwardRef,
  useState,
  useEffect
} from "react"; 

{...}

// Child component
// I am defining here a forwardRef's element to get the Child's methods from the parent
// through the ref's element.
let Child = forwardRef((props, ref) => {
  // I am fetching the parent's method here
  // that allows me to connect the parent and the child's components
  let { validateChildren } = props;
  // I am initializing the state of the children
  // good if we can even leverage on the functional children's state
  let initialState = {
    one: "hello world",
    two: () => {
      console.log("I am accessing child method from parent :].");
      return "child method achieve";
    }
  };
  // useState initialization
  const [componentState, setComponentState] = useState(initialState);
  // useEffect will allow me to communicate with the parent
  // through a lifecycle data flow
  useEffect(() => {
    ref.current = { componentState };
    validateChildren(ref.current.componentState.two);
  });

{...}

});

{...}

// Parent component
class App extends Component {
  // initialize the ref inside the constructor element
  constructor(props) {
    super(props);
    this.childRef = createRef();
  }

  // I am implementing a parent's method
  // in child useEffect's method
  validateChildren = childrenMethod => {
    // access children method from parent
    childrenMethod();
    // or signaling children is ready
    console.log("children active");
  };

{...}
render(){
       return (
          {
            // I am referencing the children
            // also I am implementing the parent logic connector's function
            // in the child, here => this.validateChildren's function
          }
          <Child ref={this.childRef} validateChildren={this.validateChildren} />
        </div>
       )
}

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Do this:

var left: Node? = null

fun show() {
     val left = left
     if (left != null) {
         queue.add(left) // safe cast succeeds
     }
}

Which seems to be the first option provided by the accepted answer, but that's what you're looking for.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

Edit: isMounted is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.


As the warning states, you are calling this.setState on an a component that was mounted but since then has been unmounted.

To make sure your code is safe, you can wrap it in

if (this.isMounted()) {
    this.setState({'time': remainTimeInfo});
}

to ensure that the component is still mounted.

MySQL DROP all tables, ignoring foreign keys

Here is an automated way to do this via a bash script:

host=$1
dbName=$2
user=$3
password=$4

if [ -z "$1" ]
then
    host="localhost"
fi

# drop all the tables in the database
for i in `mysql -h$host -u$user -p$password $dbName -e "show tables" | grep -v Tables_in` ; do  echo $i && mysql -h$host -u$user -p$password $dbName -e "SET FOREIGN_KEY_CHECKS = 0; drop table $i ; SET FOREIGN_KEY_CHECKS = 1" ; done

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Define css class in django Forms

Simply add the classes to your form as follows.

class UserLoginForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={
        'class':'form-control',
        'placeholder':'Username'
        }
    ))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
        'class':'form-control',
        'placeholder':'Password'
        }
    ))

Flatten List in LINQ

With query syntax:

var values =
from inner in outer
from value in inner
select value;

Editing specific line in text file in Python

If your text contains only one individual:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def roplo(file_name,what):
    patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
    with open(file_name,'rb+') as f:
        ch = f.read()
        f.seek(0)
        f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')


# after treatment
with open('pers.txt','rb') as h:
    print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If your text contains several individuals:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim  \n  dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def ripli(file_name,who,what):
    with open(file_name,'rb+') as f:
        ch = f.read()
        x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
        f.seek(x)
        f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')


# after treatment
with open('pers.txt','rb') as h:
    print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.

But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:

from cPickle import dump, load

with open('cards','wb') as f:
    dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)

with open('cards','rb') as g:
    id_cards = load(g)
print 'id_cards before change==',id_cards

id_cards['Jim'][0] = 'Wizard'

with open('cards','w') as h:
    dump(id_cards,h)

with open('cards') as e:
    id_cards = load(e)
print '\nid_cards after change==',id_cards

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

How to set back button text in Swift

GOTCHA: If you are having trouble with any of the many-starred suggestions, ensure that you are registering your UITableViewCells in viewDidLoad(), not from init()

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

Can typescript export a function?

In my case I'm doing it like this:

 module SayHi {
    export default () => { console.log("Hi"); }
 }
 new SayHi();

How to view an HTML file in the browser with Visual Studio Code

I am just re-posting the steps I used from msdn blog. It may help the community.

This will help you to setup a local web server known as lite-server with VS Code, and also guides you to host your static html files in localhost and debug your Javascript code.

1. Install Node.js

If not already installed, get it here

It comes with npm (the package manager for acquiring and managing your development libraries)

2. Create a new folder for your project

Somewhere in your drive, create a new folder for your web app.

3. Add a package.json file to the project folder

Then copy/paste the following text:

{
   "name": "Demo",
   "version": "1.0.0",
   "description": "demo project.",
   "scripts": {
     "lite": "lite-server --port 10001",
     "start": "npm run lite"
   },
   "author": "",
   "license": "ISC",
   "devDependencies": {
     "lite-server": "^2.5.4"
   }
}

4. Install the web server

In a terminal window (command prompt in Windows) opened on your project folder, run this command:

npm install

This will install lite-server (defined in package.json), a static server that loads index.html in your default browser and auto refreshes it when application files change.

5. Start the local web server!

(Assuming you have an index.html file in your project folder).

In the same terminal window (command prompt in Windows) run this command:

npm start

Wait a second and index.html is loaded and displayed in your default browser served by your local web server!

lite-server is watching your files and refreshes the page as soon as you make changes to any html, js or css files.

And if you have VS Code configured to auto save (menu File / Auto Save), you see changes in the browser as you type!

Notes:

  • Do not close the command line prompt until you’re done coding in your app for the day
  • It opens on http://localhost:10001 but you can change the port by editing the package.json file.

That’s it. Now before any coding session just type npm start and you are good to go!

Originally posted here in msdn blog. Credits goes to Author : @Laurent Duveau

What is the maximum number of edges in a directed graph with n nodes?

Putting it another way:

A complete graph is an undirected graph where each distinct pair of vertices has an unique edge connecting them. This is intuitive in the sense that, you are basically choosing 2 vertices from a collection of n vertices.

nC2 = n!/(n-2)!*2! = n(n-1)/2

This is the maximum number of edges an undirected graph can have. Now, for directed graph, each edge converts into two directed edges. So just multiply the previous result with two. That gives you the result: n(n-1)

Convert object array to hash map, indexed by an attribute value of the Object

Using ES6 Map (pretty well supported), you can try this:

_x000D_
_x000D_
var arr = [_x000D_
    { key: 'foo', val: 'bar' },_x000D_
    { key: 'hello', val: 'world' }_x000D_
];_x000D_
_x000D_
var result = new Map(arr.map(i => [i.key, i.val]));_x000D_
_x000D_
// When using TypeScript, need to specify type:_x000D_
// var result = arr.map((i): [string, string] => [i.key, i.val])_x000D_
_x000D_
// Unfortunately maps don't stringify well.  This is the contents in array form._x000D_
console.log("Result is: " + JSON.stringify([...result])); _x000D_
// Map {"foo" => "bar", "hello" => "world"}
_x000D_
_x000D_
_x000D_

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

After not able to find a good universal solution I made something of my own. I have not tested it for a very large list.

It takes care of nested keys,arrays or just about anything.

Here is the github and demo

app.filter('xf', function() {
    function keyfind(f, obj) {
        if (obj === undefined)
            return -1;
        else {
            var sf = f.split(".");
            if (sf.length <= 1) {
                return obj[sf[0]];
            } else {
                var newobj = obj[sf[0]];
                sf.splice(0, 1);
                return keyfind(sf.join("."), newobj)
            }
        }

    }
    return function(input, clause, fields) {
        var out = [];
        if (clause && clause.query && clause.query.length > 0) {
            clause.query = String(clause.query).toLowerCase();
            angular.forEach(input, function(cp) {
                for (var i = 0; i < fields.length; i++) {
                    var haystack = String(keyfind(fields[i], cp)).toLowerCase();
                    if (haystack.indexOf(clause.query) > -1) {
                        out.push(cp);
                        break;
                    }
                }
            })
        } else {
            angular.forEach(input, function(cp) {
                out.push(cp);
            })
        }
        return out;
    }

})

HTML

<input ng-model="search.query" type="text" placeholder="search by any property">
<div ng-repeat="product in products |  xf:search:['color','name']">
...
</div>

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

Array to String PHP?

One of the Best way:

echo print_r($array, true);

Get MIME type from filename extension

It is always not necessary that the mime type calculated by the extention of the file will be always right.

lets say i can save a file with .png extention but the fileformat i can set as "ImageFormat.jpeg".

So in this case the file which you will be calculating, will give a different result... it may result in big size file than the original.

If you are working with images then you can use the imagecodecInfo and ImageFormat.

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

How do I clear only a few specific objects from the workspace?

Following command will do

rm(list=ls(all=TRUE))

Meaning of "[: too many arguments" error from if [] (square brackets)

Some times If you touch the keyboard accidentally and removed a space.

if [ "$myvar" = "something"]; then
    do something
fi

Will trigger this error message. Note the space before ']' is required.

Selenium WebDriver.get(url) does not open the URL

Try the following code

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

WebDriver DRIVER = new FirefoxDriver();
DRIVER.get("http://www.google.com");

Can I access constants in settings.py from templates in Django?

Django provides access to certain, frequently-used settings constants to the template such as settings.MEDIA_URL and some of the language settings if you use django's built in generic views or pass in a context instance keyword argument in the render_to_response shortcut function. Here's an example of each case:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template

def my_generic_view(request, template='my_template.html'):
    return direct_to_template(request, template)

def more_custom_view(request, template='my_template.html'):
    return render_to_response(template, {}, context_instance=RequestContext(request))

These views will both have several frequently used settings like settings.MEDIA_URL available to the template as {{ MEDIA_URL }}, etc.

If you're looking for access to other constants in the settings, then simply unpack the constants you want and add them to the context dictionary you're using in your view function, like so:

from django.conf import settings
from django.shortcuts import render_to_response

def my_view_function(request, template='my_template.html'):
    context = {'favorite_color': settings.FAVORITE_COLOR}
    return render_to_response(template, context)

Now you can access settings.FAVORITE_COLOR on your template as {{ favorite_color }}.

New Intent() starts new instance with Android: launchMode="singleTop"

What actually worked for me in the end was this:

Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.

Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.

Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.

So, the only option is to make the request from your server to see if you can display the site in your IFrame.

So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.

What is a .NET developer?

I'd say the minimum would be to

  • know one of the .Net Languages (C#, VB.NET, etc.)
  • know the basic working of the .Net runtime
  • know and understand the core parts of the .Net class libraries
  • have an understanding about what additional classes and functions are available as part of the .Net class libraries

How to enumerate an enum

I know it is a bit messy, but if you are fan of one-liners, here is one:

((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));

Work with a time span in Javascript

a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat

some formatting examples

/** delta: 1234567890, @locale: 'en-US', @style: 'long' */

/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds

/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890

/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms

/* D,h:m:s.f */
14,06:56:07.890

/* D~, h:m:s.f */
14 days, 06:56:07.890

/* h~ m~ s~ */
342 hours 56 minutes 7 seconds

/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days

/* up D~, h:m */
up 14 days, 06:56

the code & test

_x000D_
_x000D_
/**
    Init locale formatter:
    
        timespan.locale(@locale, @style)
    
    Example:

        timespan.locale('en-US', 'long');
        timespan.locale('es', 'narrow');

    Format time delta:
    
        timespan.format(@pattern, @milliseconds)

        @pattern tokens:
            D: days, h: hours, m: minutes, s: seconds, f: millis

        @pattern token extension:
            h  => '0'-padded value, 
            h# => raw value,
            h~ => locale formatted value

    Example:

        timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
        
        output: 14 days 6 hours 56 minutes 7 seconds 890 millis

    NOTES:

    * milliseconds unit have no locale translation
    * may encounter declension issues for some locales
    * use quoted text for raw inserts
            
*/

const timespan = (() => {
    let rtf, tokensRtf;
    const
    tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
    map = [
        {t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
        {t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
        {t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
        {t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
        {t: [['f', 3], ['f#'], ['f~']], u: 1}
    ],
    locale = (value, style = 'long') => {
        try {
            rtf = new Intl.RelativeTimeFormat(value, {style});
        } catch (e) {
            if (rtf) throw e;
            return;
        }
        const h = rtf.format(1, 'hour').split(' ');
        tokensRtf = new Set(rtf.format(1, 'day').split(' ')
            .filter(t => t != 1 && h.indexOf(t) > -1));
        return true;
    },
    fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
    mapper = {
        number: (t, u) => (u + '').padStart(t.fmt, '0'),
        string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
            .filter(t => !tokensRtf.has(t)).join(' ')
            .trim().replace(/[+-]/g, '') : fallback(t, u),
    },
    replace = (out, t) => out[t] || t.slice(1, t.length - 1),
    format = (pattern, value) => {
        if (typeof pattern !== 'string')
            throw Error('invalid pattern');
        if (!Number.isFinite(value))
            throw Error('invalid value');
        if (!pattern)
            return '';
        const out = {};
        value = Math.abs(value);
        pattern.match(tokens)?.forEach(t => out[t] = null);
        map.forEach(m => {
            let u = null;
            m.t.forEach(t => {
                if (out[t.token] !== null)
                    return;
                if (u === null) {
                    u = Math.floor(value / m.u);
                    value %= m.u;
                }
                out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
            })
        });
        return pattern.replace(tokens, replace.bind(null, out));
    };
    map.forEach(m => m.t = m.t.map(t => ({
        token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
    })));
    locale('en');
    return {format, locale};
})();


/************************** test below *************************/

const
cfg = {
  locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
  style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
  try {
      const tv = new Date(td.value);
      if (isNaN(tv)) throw Error('invalid "datetime2" value');
      timespan.locale(loc.value || locale.value, style.value);
      const delta = fd.getTime() - tv.getTime();
      out.innerHTML = timespan.format(fmt.value, delta);
  } catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
  const elm = el(id);
  value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
_x000D_
_x000D_

Java: How to access methods from another class

public class WeatherResponse {

private int cod;
private String base;
private Weather main;

public int getCod(){
    return this.cod;
}

public void setCod(int cod){
    this.cod = cod;
}

public String getBase(){
    return base;
}

public void setBase(String base){
    this.base = base;
}

public Weather getWeather() {
    return main;
}

// default constructor, getters and setters
}

another class

public class Weather {

private int id;
private String main;
private String description;

public String getMain(){
    return main;
}

public void setMain(String main){
    this.main = main;
}

public String getDescription(){
    return description;
}

public void setDescription(String description){
    this.description = description;
}

// default constructor, getters and setters
}

// accessing methods
// success!

    Log.i("App", weatherResponse.getBase());
    Log.i("App", weatherResponse.getWeather().getMain());
    Log.i("App", weatherResponse.getWeather().getDescription());

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

Convert php array to Javascript

Below is a pretty simple trick to convert PHP array to JavaScript array:

$array = array("one","two","three");

JS below:

// Use PHP tags for json_encode()

var js_json =  json_encode($array);
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string);

alert(js_json_array.length);

It works like a charm.

No restricted globals

/* eslint no-restricted-globals:0 */

is another alternate approach

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

To drop all tables:

exec sp_MSforeachtable 'DROP TABLE ?'

This will, of course, drop all constraints, triggers etc., everything but the stored procedures.

For the stored procedures I'm afraid you will need another stored procedure stored in master.

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

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

How to check queue length in Python

Use queue.rear+1 to get the length of the queue

Convert List(of object) to List(of string)

This works for all types.

List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();

How to count the number of columns in a table using SQL?

Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:

SELECT t.owner, 
       t.table_name, 
       t.num_rows, 
       Count(*) 
FROM   all_tables t 
       LEFT JOIN all_tab_columns c 
              ON t.table_name = c.table_name 
WHERE  num_rows IS NOT NULL 
GROUP  BY t.owner, 
          t.table_name, 
          t.num_rows 
ORDER  BY t.num_rows DESC; 

How to start anonymous thread class

Not exactly sure this is what you are asking but you can do something like:

new Thread() {
    public void run() {
        System.out.println("blah");
    }
}.start();

Notice the start() method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.

Better than creating an anonymous Thread class is to create an anonymous Runnable class:

new Thread(new Runnable() {
    public void run() {
        System.out.println("blah");
    }
}).start();

Instead overriding the run() method in the Thread you inject a target Runnable to be run by the new thread. This is a better pattern.

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

How do I change the ID of a HTML element with JavaScript?

That seems to work for me:

<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>

The expected behaviour is to change the colour of the word "fruit".

Perhaps your document was not fully loaded when you called the routine?

#ifdef replacement in the Swift language

isDebug Constant Based on Active Compilation Conditions

Another, perhaps simpler, solution that still results in a boolean that you can pass into functions without peppering #if conditionals throughout your codebase is to define DEBUG as one of your project build target's Active Compilation Conditions and include the following (I define it as a global constant):

#if DEBUG
    let isDebug = true
#else
    let isDebug = false
#endif

isDebug Constant Based on Compiler Optimization Settings

This concept builds on kennytm's answer

The main advantage when comparing against kennytm's, is that this does not rely on private or undocumented methods.

In Swift 4:

let isDebug: Bool = {
    var isDebug = false
    // function with a side effect and Bool return value that we can pass into assert()
    func set(debug: Bool) -> Bool {
        isDebug = debug
        return isDebug
    }
    // assert:
    // "Condition is only evaluated in playgrounds and -Onone builds."
    // so isDebug is never changed to true in Release builds
    assert(set(debug: true))
    return isDebug
}()

Compared with preprocessor macros and kennytm's answer,

  • ? You don't need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • ? Documented, which means the function will follow normal API release/deprecation patterns.

  • ? Using in if/else will not generate a "Will never be executed" warning.

Draw path between two points using Google Maps Android API v2

Dont know whether I should put this as answer or not...

I used @Zeeshan0026's solution to draw the path...and the problem was that if I draw path once, and then I do try to draw path once again, both two paths show and this continues...paths showing even when markers were deleted... while, ideally, old paths' shouldn't be there once new path is drawn / markers are deleted..

going through some other question over SO, I had the following solution

I add the following function in Zeeshan's class

 public void clearRoute(){

         for(Polyline line1 : polylines)
         {
             line1.remove();
         }

         polylines.clear();

     }

in my map activity, before drawing the path, I called this function.. example usage as per my app is

private Route rt;

rt.clearRoute();

            if (src == null) {
                Toast.makeText(getApplicationContext(), "Please select your Source", Toast.LENGTH_LONG).show();
            }else if (Destination == null) {
                Toast.makeText(getApplicationContext(), "Please select your Destination", Toast.LENGTH_LONG).show();
            }else if (src.equals(Destination)) {
                Toast.makeText(getApplicationContext(), "Source and Destinatin can not be the same..", Toast.LENGTH_LONG).show();
            }else{

                rt.drawRoute(mMap, MapsMainActivity.this, src,
                        Destination, false, "en");
            }

you can use rt.clearRoute(); as per your requirements.. Hoping that it will save a few minutes of someone else and will help some beginner in solving this issue..

Complete Class Code

see on github

Edit: here is part of code from mainactivity..

case R.id.mkrbtn_set_dest:
                    Destination = selmarker.getPosition();
                    destmarker = selmarker;
                    desShape = createRouteCircle(Destination, false);

                    if (src == null) {
                        Toast.makeText(getApplicationContext(),
                                "Please select your Source first...",
                                Toast.LENGTH_LONG).show();
                    } else if (src.equals(Destination)) {
                        Toast.makeText(getApplicationContext(),
                                "Source and Destinatin can not be the same..",
                                Toast.LENGTH_LONG).show();
                    } else {

                        if (isNetworkAvailable()) {
                            rt.drawRoute(mMap, MapsMainActivity.this, src,
                                    Destination, false, "en");
                            src = null;
                            Destination = null;

                        } else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Internet Connection seems to be OFFLINE...!",
                                    Toast.LENGTH_LONG).show();

                        }

                    }

                    break;

Edit 2 as per comments

usage :

//variables as data members
GoogleMap mMap;
private Route rt;
static LatLng src;
static LatLng Destination;
//MapsMainActivity is my activity
//false for interim stops for traffic, google
// en language for html description returned

rt.drawRoute(mMap, MapsMainActivity.this, src,
                            Destination, false, "en");

Check if event exists on element

Below code will provide you with all the click events on given selector:

jQuery(selector).data('events').click

You can iterate over it using each or for ex. check the length for validation like:

jQuery(selector).data('events').click.length

Thought it would help someone. :)

How to validate phone number using PHP?

Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

An example

$phone = '000-0000-0000';

if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
  // $phone is valid
}

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

I got the same error in the same tutorial because I had forgot the export keyword for the interface.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Though I am new to hibernate but with little research (trial and error we can say) I found out that it is due to inconsistency in annotating the methods/fileds.

when you are annotating @ID on variable make sure all other annotations are also done on variable only and when you are annotating it on getter method same make sure you are annotating all other getter methods only and not their respective variables.

Average of multiple columns

You could simply do:

Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID

Right?

I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID

Changing upload_max_filesize on PHP

Since I just ran in to this problem on a shared host and was unable to add the values to my .htaccess file I thought I'd share my solution.

I made an ini file with the values in it. Simple as that:

Make a file called ".user.ini" and add your values

upload_max_filesize = 150M
post_max_size = 150M

Boom, problem solved.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Sql script to find invalid email addresses

I find this simple T-SQL query useful for returning valid e-mail addresses

SELECT email
FROM People
WHERE email LIKE '%_@__%.__%' 
    AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0

The PATINDEX bit eliminates all e-mail addresses containing characters that are not in the allowed a-z, 0-9, '@', '.', '_' & '-' set of characters.

It can be reversed to do what you want like this:

SELECT email
FROM People
WHERE NOT (email LIKE '%_@__%.__%' 
    AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0)

MVC Razor Radio Button

In order to do this for multiple items do something like:

foreach (var item in Model)
{
    @Html.RadioButtonFor(m => m.item, "Yes") @:Yes
    @Html.RadioButtonFor(m => m.item, "No") @:No
}

Ignoring upper case and lower case in Java

You have to use the String method .toLowerCase() or .toUpperCase() on both the input and the string you are trying to match it with.

Example:

public static void findPatient() {
    System.out.print("Enter part of the patient name: ");
    String name = sc.nextLine();

    System.out.print(myPatientList.showPatients(name));
}

//the other class
ArrayList<String> patientList;

public void showPatients(String name) {
    boolean match = false;

    for(String matchingname : patientList) {
        if (matchingname.toLowerCase().contains(name.toLowerCase())) {
            match = true;
        }
    }
}

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

I've heard this doesn't always work on the designer, but it compiles fine.

Determine if string is in list in JavaScript

Looks like you need to use in_array function.

jQuery -> inArray

Prototype -> Array.indexOf

Or, see these examples if you are not using jQuery or Prototype:

Stylistic note: variables named thisthing thatthing, should be named to tell you something about what they contain (noun).

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

SVN Error - Not a working copy

Maybe you just copied tree of folder and trying to add lowest one.

SVN
|_
  |
  subfolder1
       |
       subfolder2   (here you get an error)

in that case you have to commit directory on the upper level.

Passing argument to alias in bash

to use parameters in aliases, i use this method:

alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'

its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:

alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'

so..

you could, if you need to have that variable in there

alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'

of course...

alias mongodb='./path/to/mongodb/'

would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).

I hope that helps you out :)

How to set button click effect in Android?

It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.

Kotlin Version:

fun buttonEffect(button: View) {
    button.setOnTouchListener { v, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
                v.invalidate()
            }
            MotionEvent.ACTION_UP -> {
                v.background.clearColorFilter()
                v.invalidate()
            }
        }
        false
    }
}

Java Version:

public static void buttonEffect(View button){
    button.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
                    v.invalidate();
                    break;
                }
                case MotionEvent.ACTION_UP: {
                    v.getBackground().clearColorFilter();
                    v.invalidate();
                    break;
                }
            }
            return false;
        }
    });
}

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

The shortest way, I think, is the following:

import struct
val = 0x11223344
val = struct.unpack("<I", struct.pack(">I", val))[0]
print "%08x" % val

This converts an integer to a byte-swapped integer.

Difference between SurfaceView and View?

A few things I've noted:

  • SurfaceViews contain a nice rendering mechanism that allows threads to update the surface's content without using a handler (good for animation).
  • Surfaceviews cannot be transparent, they can only appear behind other elements in the view hierarchy.
  • I've found that they are much faster for animation than rendering onto a View.

For more information (and a great usage example) refer to the LunarLander project in the SDK 's examples section.

How to read string from keyboard using C?

When reading input from any file (stdin included) where you do not know the length, it is often better to use getline rather than scanf or fgets because getline will handle memory allocation for your string automatically so long as you provide a null pointer to receive the string entered. This example will illustrate:

#include <stdio.h>
#include <stdlib.h>

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

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    ssize_t read;

    printf ("\nEnter string below [ctrl + d] to quit\n");

    while ((read = getline(&line, &len, stdin)) != -1) {

        if (read > 0)
            printf ("\n  read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

        printf ("Enter string below [ctrl + d] to quit\n");
    }

    free (line);  /* free memory allocated by getline */

    return 0;
}

The relevant parts being:

char *line = NULL;  /* forces getline to allocate with malloc */
size_t len = 0;     /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);

Setting line to NULL causes getline to allocate memory automatically. Example output:

$ ./getline_example

Enter string below [ctrl + d] to quit
A short string to test getline!

  read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!

Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL

  read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL

Enter string below [ctrl + d] to quit

So with getline you do not need to guess how long your user's string will be.

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

How to have an auto incrementing version number (Visual Studio)?

If you put an asterisk in for build and revision visual studio uses the number of days since Jan. 1st 2000 as the build number, and the number of seconds since midnight divided by 2 as the revision.

A MUCH better life saver solution is http://autobuildversion.codeplex.com/

It works like a charm and it's VERY flexible.

PDF Parsing Using Python - extracting formatted and plain texts

That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.

I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.

How do I get the current time only in JavaScript

This worked for me but this depends on what you get when you hit Date():

Date().slice(16,-12)

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Git on Windows: How do you set up a mergetool?

I found two ways to configure "SourceGear DiffMerge" as difftool and mergetool in github Windows.

The following commands in a Command Prompt window will update your .gitconfig to configure GIT use DiffMerge:

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd 'C:/Program\ Files/SourceGear/Common/DiffMerge/sgdm.exe  \"$LOCAL\" \"$REMOTE\"'

git config --global merge.tool diffmerge
git config --global mergetool.diffmerge.cmd  'C:/Program\ Files/SourceGear/Common/DiffMerge/sgdm.exe  -merge  -result=\"$MERGED\" \"$LOCAL\" \"$BASE\" \"$REMOTE\"'

[OR]

Add the following lines to your .gitconfig. This file should be in your home directory in C:\Users\UserName:

[diff]
    tool = diffmerge
[difftool "diffmerge"]
    cmd = C:/Program\\ Files/SourceGear/Common/DiffMerge/sgdm.exe \"$LOCAL\" \"$REMOTE\"

[merge]
    tool = diffmerge
[mergetool "diffmerge"]
    trustExitCode = true
    cmd = C:/Program\\ Files/SourceGear/Common/DiffMerge/sgdm.exe -merge -result=\"$MERGED\" \"$LOCAL\" \"$BASE\" \"$REMOTE\"

Simulate Keypress With jQuery

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

How to create localhost database using mysql?

See here for starting the service and here for how to make it permanent. In short to test it, open a "DOS" terminal with administrator privileges and write:

shell> "C:\Program Files\MySQL\[YOUR MYSQL VERSION PATH]\bin\mysqld"

How would I find the second largest salary from the employee table?

SELECT
    TOP 1 salary
FROM
    (
        SELECT
            TOP 2 salary
        FROM
            employees
    ) sal
ORDER BY
    salary DESC;

process.start() arguments

Try fully qualifying the filenames in the arguments - I notice you're specifying the path in the FileName part, so it's possible that the process is being started elsewhere, then not finding the arguments and causing an error.

If that works, then setting the WorkingDirectory property on the StartInfo may be of use.

Actually, according to the link

The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\system32.

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

How do I get the title of the current active window using c#?

Based on GetForegroundWindow function | Microsoft Docs:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);

private string GetCaptionOfActiveWindow()
{
    var strTitle = string.Empty;
    var handle = GetForegroundWindow();
    // Obtain the length of the text   
    var intLength = GetWindowTextLength(handle) + 1;
    var stringBuilder = new StringBuilder(intLength);
    if (GetWindowText(handle, stringBuilder, intLength) > 0)
    {
        strTitle = stringBuilder.ToString();
    }
    return strTitle;
}

It supports UTF8 characters.

Find out time it took for a python script to complete execution

use the time and datetime packages.

if anybody want to execute this script and also find out how much time it took to execute in minutes

import time
from time import strftime
from datetime import datetime 
from time import gmtime

def start_time_():    
    #import time
    start_time = time.time()
    return(start_time)

def end_time_():
    #import time
    end_time = time.time()
    return(end_time)

def Execution_time(start_time_,end_time_):
   #import time
   #from time import strftime
   #from datetime import datetime 
   #from time import gmtime
   return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))

start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))

The above code works for me. I hope this helps.

Match at every second occurrence

Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d)

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

Show percent % instead of counts in charts of categorical variables

Here is a workaround for faceted data. (The accepted answer by @Andrew does not work in this case.) The idea is to calculate the percentage value using dplyr and then to use geom_col to create the plot.

library(ggplot2)
library(scales)
library(magrittr)
library(dplyr)

binwidth <- 30

mtcars.stats <- mtcars %>%
  group_by(cyl) %>%
  mutate(bin = cut(hp, breaks=seq(0,400, binwidth), 
               labels= seq(0+binwidth,400, binwidth)-(binwidth/2)),
         n = n()) %>%
  group_by(cyl, bin) %>%
  summarise(p = n()/n[1]) %>%
  ungroup() %>%
  mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +  
  geom_col() + 
  scale_y_continuous(labels = percent) +
  facet_grid(cyl~.)

This is the plot:

enter image description here

Add JavaScript object to JavaScript object

var jsonIssues = []; // new Array
jsonIssues.push( { ID:1, "Name":"whatever" } );
// "push" some more here

Adding new files to a subversion repository

  • Checkout a working copy of the repository (or at least the subdirectory that you want to add the files to): svn checkout https://example.org/path/to/repo/bleh
  • Copy the files over there.
  • svn add file1 file2...
  • svn commit

I am not aware of a quicker option.

Note: if you are on the same machine as your Subversion repository, the URL can use the file: specifier with a path in place of https: in the svn checkout command. For example svn checkout file:///path/to/repo/bleh.

PS. as pointed out in the comments and other answers, you can use something like svn import . <URL> if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

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

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

echo that outputs to stderr

Don't use cat as some have mentioned here. cat is a program while echo and printf are bash (shell) builtins. Launching a program or another script (also mentioned above) means to create a new process with all its costs. Using builtins, writing functions is quite cheap, because there is no need to create (execute) a process (-environment).

The opener asks "is there any standard tool to output (pipe) to stderr", the short answer is : NO ... why? ... redirecting pipes is an elementary concept in systems like unix (Linux...) and bash (sh) builds up on these concepts.

I agree with the opener that redirecting with notations like this: &2>1 is not very pleasant for modern programmers, but that's bash. Bash was not intended to write huge and robust programs, it is intended to help the admins to get there work with less keypresses ;-)

And at least, you can place the redirection anywhere in the line:

$ echo This message >&2 goes to stderr 
This message goes to stderr

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If you don't see the Active Directory, it's because you did not install AD LS Users and Computer Feature. Go to Manage - Add Roles & Features. Within Add Roles and Features Wizard, on Features tab, select Remote Server Administration Tools, select - Role Admininistration Tools - Select AD DS and DF LDS Tools.

After that, you can see the PS Active Directory package.

Can I access a form in the controller?

Definitely you can't access form in scope bec. it is not created. The DOM from html template is loaded little bit slowly like controller constructor. the solution is to watch until DOM loaded and all the scope defined!

in controller:

$timeout(function(){
    console.log('customerForm:', $scope.customerForm);
    // everything else what you need
});

Is there a way to programmatically minimize a window

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     if(e.KeyChar == 'm')
         this.WindowState = FormWindowState.Minimized;
}

prevent property from being serialized in web API

For .NET Core 3.0 and above:

The default JSON serializer for ASP.NET Core is now System.Text.Json, which is new in .NET Core 3.0. Consider using System.Text.Json when possible. It's high-performance and doesn't require an additional library dependency.

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#newtonsoftjson-jsonnet-support

Sample (Thanks cuongle)

using System.Text.Json.Serialization;

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonIgnore]
    public List<Something> Somethings { get; set; }
}

If you already have Newtonsoft.Json intalled and chose to use it instead, by default, [JsonIgnore] won't work as expected.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

These issue arise generally due to mismatch between @ngx-translate/core version and Angular .Before installing check compatible version of corresponding ngx_trnalsate/Core, @ngx-translate/http-loader and Angular at https://www.npmjs.com/package/@ngx-translate/core

Eg: For Angular 6.X versions,

npm install @ngx-translate/core@10 @ngx-translate/http-loader@3 rxjs --save

Like as above, follow below command and rest of code part is common for all versions(Note: Version can obtain from( https://www.npmjs.com/package/@ngx-translate/core)

npm install @ngx-translate/core@version @ngx-translate/http-loader@version rxjs --save

Get Root Directory Path of a PHP project

For PHP >= 5.3.0 try

PHP magic constants.

__DIR__

And make your path relative.

For PHP < 5.3.0 try

dirname(__FILE__)

Counting Line Numbers in Eclipse

Are you interested in counting the executable lines rather than the total file line count? If so you could try a code coverage tool such as EclEmma. As a side effect of the code coverage stats you get stats on the number of executable lines and blocks (and methods and classes). These are rolled up from the method level upwards, so you can see line counts for the packages, source roots and projects as well.

How to view the contents of an Android APK file?

Actually the apk file is just a zip archive, so you can try to rename the file to theappname.apk.zip and extract it with any zip utility (e.g. 7zip).

The androidmanifest.xml file and the resources will be extracted and can be viewed whereas the source code is not in the package - just the compiled .dex file ("Dalvik Executable")

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

How do I round a double to two decimal places in Java?

Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:

import java.text.DecimalFormat;

public class TwoDecimalPlaces {
    static double myFixedNumber = 98765.4321;
    public static void main(String[] args) {

        System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
    }
}

The result is: 98765.43

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Solution without charts

Function SelectionToPicture(nome)

'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"

'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height



With ThisWorkbook.ActiveSheet

    .Activate

    Dim chtObj As ChartObject
    Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
    chtObj.Name = "TemporaryPictureChart"

    'resize obj to picture size
    chtObj.Width = w
    chtObj.Height = h

    ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
    ActiveChart.Paste

    ActiveChart.Export FileName:=FName, FilterName:="jpg"

    chtObj.Delete

End With
End Function

momentJS date string add 5 days

To get an actual working example going that returns what one would expect:

var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)

How to uninstall Anaconda completely from macOS

To uninstall Anaconda open a terminal window:

  1. Remove the entire anaconda installation directory:
rm -rf ~/anaconda
  1. Edit ~/.bash_profile and remove the anaconda directory from your PATH environment variable.

Note: You may need to edit .bashrc and/or .profile files instead of .bash_profile

  1. Remove the following hidden files and directories, which may have been created in the home directory:

    • .condarc
    • .conda
    • .continuum

Use:

rm -rf ~/.condarc ~/.conda ~/.continuum

Is it wrong to place the <script> tag after the </body> tag?

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

printf format specifiers for uint32_t and size_t

All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long is at least 32 bits, so %lu together with (unsigned long)k is always correct:

uint32_t k;
printf("%lu\n", (unsigned long)k);

size_t is trickier, which is why %zu was added in C99. If you can't use that, then treat it just like k (long is the biggest type in C89, size_t is very unlikely to be larger).

size_t sz;
printf("%zu\n", sz);  /* C99 version */
printf("%lu\n", (unsigned long)sz);  /* common C89 version */

If you don't get the format specifiers correct for the type you are passing, then printf will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

remap is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:

:map and :noremap are recursive and non-recursive versions of the various mapping commands. For example, if we run:

:map j gg           (moves cursor to first line)
:map Q j            (moves cursor to first line)
:noremap W j        (moves cursor down one line)

Then:

  • j will be mapped to gg.
  • Q will also be mapped to gg, because j will be expanded for the recursive mapping.
  • W will be mapped to j (and not to gg) because j will not be expanded for the non-recursive mapping.

Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.

For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map and :noremap), one that works in normal mode (:nmap and :nnoremap), one in visual mode (:vmap and :vnoremap) and so on.

For more guidance on this, see:

:help :map
:help :noremap
:help recursive_mapping
:help :map-modes

How to read from a file or STDIN in Bash?

Perhaps the simplest solution is to redirect stdin with a merging redirect operator:

#!/bin/bash
less <&0

Stdin is file descriptor zero. The above sends the input piped to your bash script into less's stdin.

Read more about file descriptor redirection.

Convert String to Double - VB

Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
    ' text is convertible to Double, and value contains the Double value now
Else
    ' Cannot convert text to Double
End If

Namespace not recognized (even though it is there)

Restarting Visual Studio 2019 - that did it.

How to make background of table cell transparent

You can try :

  @media print {
    .table td,
    .table th {
        background-color: transparent !important;
        -webkit-print-color-adjust: exact !important;

    }
}

Difference between partition key, composite key and clustering key in Cassandra?

In database design, a compound key is a set of superkeys that is not minimal.

A composite key is a set that contains a compound key and at least one attribute that is not a superkey

Given table: EMPLOYEES {employee_id, firstname, surname}

Possible superkeys are:

{employee_id}
{employee_id, firstname}
{employee_id, firstname, surname}

{employee_id} is the only minimal superkey, which also makes it the only candidate key--given that {firstname} and {surname} do not guarantee uniqueness. Since a primary key is defined as a chosen candidate key, and only one candidate key exists in this example, {employee_id} is the minimal superkey, the only candidate key, and the only possible primary key.

The exhaustive list of compound keys is:

{employee_id, firstname}
{employee_id, surname}
{employee_id, firstname, surname}

The only composite key is {employee_id, firstname, surname} since that key contains a compound key ({employee_id,firstname}) and an attribute that is not a superkey ({surname}).

Open a Web Page in a Windows Batch FIle

When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com

Also you cannot have http:// in the url.

How do I select a sibling element using jQuery?

Try -

   $(this).siblings(".bidbutton").addClass("disabled").attr("disabled", "");

How to remove an element from a list by index

Use del and specify the index of the element you want to delete:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Also supports slices:

>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]

Here is the section from the tutorial.

How to parse month full form string using DateFormat in Java?

LocalDate from java.time

Use LocalDate from java.time, the modern Java date and time API, for a date

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
    LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
    System.out.println(date);

Output:

2007-06-27

As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate is a date without time of day, so a lot better suitable for the date from your string than the old Date class. Despite its name a Date does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.

Only if you need an old-fashioned Date for an API that you cannot afford to upgrade to java.time just now, convert like this:

    Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date oldfashionedDate = Date.from(startOfDay);
    System.out.println(oldfashionedDate);

Output in my time zone:

Wed Jun 27 00:00:00 CEST 2007

Link

Oracle tutorial: Date Time explaining how to use java.time.

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

 $("body,html,document").scrollTop($("#map_canvas").position().top);

This works for Chrome 7, IE6, IE7, IE8, IE9, FF 3.6 and Safari 5.

2012 UPDATE
This is still good but I had to use it again. Sometimes position doesn't work so this is an alternative:

$("body,html,document").scrollTop($("#map_canvas").offset().top);

Solr vs. ElasticSearch

Since the long history of Apache Solr, I think one strength of the Solr is its ecosystem. There are many Solr plugins for different types of data and purposes.

solr stack

Search platform in the following layers from bottom to top:

  • Data
    • Purpose: Represent various data types and sources
  • Document building
    • Purpose: Build document information for indexing
  • Indexing and searching
    • Purpose: Build and query a document index
  • Logic enhancement
    • Purpose: Additional logic for processing search queries and results
  • Search platform service
    • Purpose: Add additional functionalities of search engine core to provide a service platform.
  • UI application
    • Purpose: End-user search interface or applications

Reference article : Enterprise search

Is there a 'foreach' function in Python 3?

Python doesn't have a foreach statement per se. It has for loops built into the language.

for element in iterable:
    operate(element)

If you really wanted to, you could define your own foreach function:

def foreach(function, iterable):
    for element in iterable:
        function(element)

As a side note the for element in iterable syntax comes from the ABC programming language, one of Python's influences.

Return list of items in list greater than some value

Since your desired output is sorted, you also need to sort it:

>>> j=[4, 5, 6, 7, 1, 3, 7, 5]
>>> sorted(x for x in j if x >= 5)
[5, 5, 6, 7, 7]

What is the difference between canonical name, simple name and class name in Java Class?

this is best document I found describing getName(), getSimpleName(), getCanonicalName()

https://javahowtodoit.wordpress.com/2014/09/09/java-lang-class-what-is-the-difference-between-class-getname-class-getcanonicalname-and-class-getsimplename/

// Primitive type
int.class.getName();          // -> int
int.class.getCanonicalName(); // -> int
int.class.getSimpleName();    // -> int

// Standard class
Integer.class.getName();          // -> java.lang.Integer
Integer.class.getCanonicalName(); // -> java.lang.Integer
Integer.class.getSimpleName();    // -> Integer

// Inner class
Map.Entry.class.getName();          // -> java.util.Map$Entry
Map.Entry.class.getCanonicalName(); // -> java.util.Map.Entry
Map.Entry.class.getSimpleName();    // -> Entry     

// Anonymous inner class
Class<?> anonymousInnerClass = new Cloneable() {}.getClass();
anonymousInnerClass.getName();          // -> somepackage.SomeClass$1
anonymousInnerClass.getCanonicalName(); // -> null
anonymousInnerClass.getSimpleName();    // -> // An empty string

// Array of primitives
Class<?> primitiveArrayClass = new int[0].getClass();
primitiveArrayClass.getName();          // -> [I
primitiveArrayClass.getCanonicalName(); // -> int[]
primitiveArrayClass.getSimpleName();    // -> int[]

// Array of objects
Class<?> objectArrayClass = new Integer[0].getClass();
objectArrayClass.getName();          // -> [Ljava.lang.Integer;
objectArrayClass.getCanonicalName(); // -> java.lang.Integer[]
objectArrayClass.getSimpleName();    // -> Integer[]

jQuery append text inside of an existing paragraph tag

I have just discovered a way to append text and its working fine at least.

 var text = 'Put any text here';
 $('#text').append(text);

You can change text according to your need.

Hope this helps.

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

How do I write to a Python subprocess' stdin?

It might be better to use communicate:

from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]

"Better", because of this warning:

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

How to find whether MySQL is installed in Red Hat?

rpmquery <package Name> By this command you can check which package is installed.

For Example: rpmquery mysql

How can I disable the default console handler, while using the java logging API?

The default console handler is attached to the root logger, which is a parent of all other loggers including yours. So I see two ways to solve your problem:

If this is only affects this particular class of yours, the simplest solution would be to disable passing the logs up to the parent logger:

logger.setUseParentHandlers(false);

If you want to change this behaviour for your whole app, you could remove the default console handler from the root logger altogether before adding your own handlers:

Logger globalLogger = Logger.getLogger("global");
Handler[] handlers = globalLogger.getHandlers();
for(Handler handler : handlers) {
    globalLogger.removeHandler(handler);
}

Note: if you want to use the same log handlers in other classes too, the best way is to move the log configuration into a config file in the long run.

How to remove trailing whitespaces with sed?

To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):

sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"

Change Bootstrap input focus blue glow

Actually, in Bootstrap 4.0.0-Beta (as of October 2017) the input element isn't referenced by input[type="text"], all Bootstrap 4 properties for the input element are actually form based.

So it's using the .form-control:focus styles. The appropriate code for the "on focus" highlighting of an input element is the following:

.form-control:focus {
  color: #495057;
  background-color: #fff;
  border-color: #80bdff;
  outline: none;
}

Pretty easy to implement, just change the border-color property.

Mixing C# & VB In The Same Project

Although Visual Studio does not support this (you can do some tricks and get MSBuild to compile both, but not from within Visual Studio), SharpDevelop does. You can have both in the same solution (as long as you are running Visual Studio Professional and above), so the easiest solution if you want to keep using Visual Studio is to seperate your VB code into a different project and access it that way.

Configure nginx with multiple locations with different root folders on subdomain

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /web/test.example.com/www;
    }

    location /static {
        root /web/test.example.com;
    }
}

http://nginx.org/r/root

How to set environment variable for everyone under my linux system?

Every process running under the Linux kernel receives its own, unique environment that it inherits from its parent. In this case, the parent will be either a shell itself (spawning a sub shell), or the 'login' program (on a typical system).

As each process' environment is protected, there is no way to 'inject' an environmental variable to every running process, so even if you modify the default shell .rc / profile, it won't go into effect until each process exits and reloads its start up settings.

Look in /etc/ to modify the default start up variables for any particular shell. Just realize that users can (and often do) change them in their individual settings.

Unix is designed to obey the user, within limits.

NB: Bash is not the only shell on your system. Pay careful attention to what the /bin/sh symbolic link actually points to. On many systems, this could actually be dash which is (by default, with no special invocation) POSIXLY correct. Therefore, you should take care to modify both defaults, or scripts that start with /bin/sh will not inherit your global defaults. Similarly, take care to avoid syntax that only bash understands when editing both, aka avoiding bashisms.

removeEventListener on anonymous functions in JavaScript

A version of Otto Nascarella's solution that works in strict mode is:

button.addEventListener('click', function handler() {
      ///this will execute only once
      alert('only once!');
      this.removeEventListener('click', handler);
});

Use of "global" keyword in Python

This is explained well in the Python FAQ

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

dll missing in JDBC

If its the case of the dll file missing you can download the dll file from this link http://en.osdn.jp/projects/sfnet_dose-grok/downloads/sqljdbc_auth.dll/

else you need to provide the username and password of the db you are trying to connect, and make the authentication as false

Does Java support default parameter values?

Try this solution:

public int getScore(int score, Integer... bonus)
{
    if(bonus.length > 0)
    {
        return score + bonus[0];
    }

    return score;
}

Click button copy to clipboard using jQuery

With Line Breaks (Extention of the Answer from Alvaro Montoro)

var ClipboardHelper = {

    copyElement: function ($element)
    {
       this.copyText($element.text())
    },
    copyText:function(text) // Linebreaks with \n
    {
        var $tempInput =  $("<textarea>");
        $("body").append($tempInput);
        $tempInput.val(text).select();
        document.execCommand("copy");
        $tempInput.remove();
    }
};

ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());

SyntaxError: Use of const in strict mode?

The const and let are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, “All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.”. Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.

To enable some of the ECMAScript 2015 features (including const and let) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:

node --harmony app.js

It all depends on which side your strict js is located. I would recommend using strict mode with const declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const declarations.

Updating records codeigniter

How to update in codeignitor?

whenever you want to update same status with multiple rows you use where_in insteam of where or if you want to change only single record can use where.

below is my code

$conditionArray = array(1, 3, 4, 6);
$this->db->where_in("ip_id", $conditionArray);
$this->db->update($this->table, array("status" => 'active'));

its working perfect.

How to encode the filename parameter of Content-Disposition header in HTTP?

If you are using a nodejs backend you can use the following code I found here

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" 
             + encodeRFC5987ValueChars(fileName);

function encodeRFC5987ValueChars (str) {
    return encodeURIComponent(str).
        // Note that although RFC3986 reserves "!", RFC5987 does not,
        // so we do not need to escape it
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // The following are not required for percent-encoding per RFC5987, 
            // so we can allow for a little better readability over the wire: |`^
            replace(/%(?:7C|60|5E)/g, unescape);
}

Converting byte array to string in javascript

If you are using node.js you can do this:

yourByteArray.toString('base64');

Saving a Numpy array as an image

If you are working in python environment Spyder, then it cannot get more easier than to just right click the array in variable explorer, and then choose Show Image option.

enter image description here

This will ask you to save image to dsik, mostly in PNG format.

PIL library will not be needed in this case.

How to access the local Django webserver from outside world

I had to add this line to settings.py in order to make it work (otherwise it showed an error when accessed from another computer)

ALLOWED_HOSTS = ['*']

then ran the server with:

python manage.py runserver 0.0.0.0:9595

Also ensure that the firewall allows connections to that port

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if (target.value === "[email protected]") {
            target.value= "";
        }
    }
    </script>
<input type="text" name="email" value="[email protected]" size="30" onfocus="clearThis(this)">

Try it out here: http://jsfiddle.net/2K3Vp/

Remove a string from the beginning of a string

<?php
$str = 'bla_string_bla_bla_bla';
echo preg_replace('/bla_/', '', $str, 1); 
?>

How to save an image locally using Python whose URL address I already know?

Version for Python 3

I adjusted the code of @madprops for Python 3

# getem.py
# python2 script to download all images in a given url
# use: python getem.py http://url.where.images.are

from bs4 import BeautifulSoup
import urllib.request
import shutil
import requests
from urllib.parse import urljoin
import sys
import time

def make_soup(url):
    req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"}) 
    html = urllib.request.urlopen(req)
    return BeautifulSoup(html, 'html.parser')

def get_images(url):
    soup = make_soup(url)
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + " images found.")
    print('Downloading images to current working directory.')
    image_links = [each.get('src') for each in images]
    for each in image_links:
        try:
            filename = each.strip().split('/')[-1].strip()
            src = urljoin(url, each)
            print('Getting: ' + filename)
            response = requests.get(src, stream=True)
            # delay to avoid corrupted previews
            time.sleep(1)
            with open(filename, 'wb') as out_file:
                shutil.copyfileobj(response.raw, out_file)
        except:
            print('  An error occured. Continuing.')
    print('Done.')

if __name__ == '__main__':
    get_images('http://www.wookmark.com')

Entity Framework select distinct name

Try this:

var results = (from ta in context.TestAddresses
               select ta.Name).Distinct();

This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

Java: Check if command line arguments are null

To expand upon this point:

It is possible that the args variable itself will be null, but not via normal execution. Normal execution will use java.exe as the entry point from the command line. However, I have seen some programs that use compiled C++ code with JNI to use the jvm.dll, bypassing the java.exe entirely. In this case, it is possible to pass NULL to the main method, in which case args will be null.

I recommend always checking if ((args == null) || (args.length == 0)), or if ((args != null) && (args.length > 0)) depending on your need.

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

This was an interesting solution for the safe navigation operator using some mixin..

http://jsfiddle.net/avernet/npcmv/

  // Assume you have the following data structure
  var companies = {
      orbeon: {
          cfo: "Erik",
          cto: "Alex"
      }
  };

  // Extend Underscore.js
  _.mixin({ 
      // Safe navigation
      attr: function(obj, name) { return obj == null ? obj : obj[name]; },
      // So we can chain console.log
      log: function(obj) { console.log(obj); }
  });

  // Shortcut, 'cause I'm lazy
  var C = _(companies).chain();

  // Simple case: returns Erik
  C.attr("orbeon").attr("cfo").log();
  // Simple case too, no CEO in Orbeon, returns undefined
  C.attr("orbeon").attr("ceo").log();
  // IBM unknown, but doesn't lead to an error, returns undefined
  C.attr("ibm").attr("ceo").log();

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Horizontal centering is easy: text-align: center;. Vertical centering of text inside an element can be done by setting line-height equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.

Better is to set line-height equal to font-size (or slightly smaller) and use padding. You'll have to adjust your height to accomodate.

Here's a CSS-only, single <div> solution that looks pretty iPhone-like. They expand with content.

Demo: http://jsfiddle.net/ThinkingStiff/mLW47/

Output:

enter image description here

CSS:

.badge {
    background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
    background-color: red;
    border: 2px solid white;
    border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
    box-shadow: 1px 1px 1px black;
    color: white;
    font: bold 15px/13px Helvetica, Verdana, Tahoma;
    height: 16px; 
    min-width: 14px;
    padding: 4px 3px 0 3px;
    text-align: center;
}

HTML:

<div class="badge">1</div>
<div class="badge">2</div>
<div class="badge">3</div>
<div class="badge">44</div>
<div class="badge">55</div>
<div class="badge">666</div>
<div class="badge">777</div>
<div class="badge">8888</div>
<div class="badge">9999</div>

Android Studio was unable to find a valid Jvm (Related to MAC OS)

  1. Install newest JDK (8u102 current)
  2. Set envirionment variable STUDIO_JDK (java_home outputs the Java home dir and sed strips two folders to get the jdk dir)

    launchctl setenv STUDIO_JDK `/usr/libexec/java_home -version 1.8 | sed 's/\/Contents\/Home//g'`

  3. Launch Android Studio like you would normally

Set STUDIO_JDK on every reboot

The above steps only works for the current session. Here is how to create a plist file in /Library/LaunchDaemons that runs the above command on every boot:

sudo defaults write /Library/LaunchDaemons/com.google.studiojdk Label STUDIO_JDK
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk ProgramArguments -array /bin/launchctl setenv STUDIO_JDK `/usr/libexec/java_home | sed 's/\/Contents\/Home//g'`
sudo defaults write /Library/LaunchDaemons/com.google.studiojdk RunAtLoad -bool TRUE

Found out about the plist trick thanks to http://www.dowdandassociates.com/blog/content/howto-set-an-environment-variable-in-mac-os-x-launchd-plist/

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

I was getting this error too, although my issue was that I kept switching between two corporate networks via my Virtual Machine, with different access credentials. I had to run the command prompt:

ipconfig /renew

After this my network issues were resolved and I could connect once again to SQL.

How to redirect a URL path in IIS?

Taken from Microsoft Technet.

Redirecting Web Sites in IIS 6.0 (IIS 6.0)


When a browser requests a page or program on your Web site, the Web server locates the page identified by the URL and returns it to the browser. When you move a page on your Web site, you can't always correct all of the links that refer to the old URL of the page. To make sure that browsers can find the page at the new URL, you can instruct the Web server to redirect the browser to the new URL.

You can redirect requests for files in one directory to a different directory, to a different Web site, or to another file in a different directory. When the browser requests the file at the original URL, the Web server instructs the browser to request the page by using the new URL.

Important

You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc".

Procedures

To redirect requests to another Web site or directory


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination directory or Web site. For example, to redirect all requests for files in the Catalog directory to the NewCatalog directory, type /NewCatalog.

To redirect all requests to a single file


  1. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  2. Click the Home Directory, Virtual Directory, or Directory tab.

  3. Under The content for this source should come from, click A redirection to a URL.

  4. In the Redirect to box, type the URL of the destination file.

  5. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

    You can use wildcards and redirect variables in the destination URL to precisely control how the original URL is translated into the destination URL.

    You can also use the redirect method to redirect all requests for files in a particular directory to a program. Generally, you should pass any parameters from the original URL to the program, which you can do by using redirect variables.

    To redirect requests to a program


  6. In IIS Manager, expand the local computer, right-click the Web site or directory you want to redirect, and click Properties.

  7. Click the Home Directory, Virtual Directory, or Directory tab.

  8. Under The content for this source should come from, click A redirection to a URL.

    In the Redirect to box, type the URL of the program, including any redirect variables needed to pass parameters to the program. For example, to redirect all requests for scripts in a Scripts directory to a logging program that records the requested URL and any parameters passed with the URL, type /Scripts/Logger.exe?URL=$V+PARAMS=$P. $V and $P are redirect variables.

  9. Select the The exact URL entered above check box to prevent the Web server from appending the original file name to the destination URL.

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

They way I did it was by selecting all of the data

select * from myTable and then right-clicking on the result set and chose "Save results as..." a csv file.

Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.

Converting NumPy array into Python List structure?

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

Stop MySQL service windows

to stop the service:

sc stop mysql56

and to start it:

sc start mysql56

you might need to change the mysql56 to whatever your version is.

VBA Excel sort range by specific column

Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes

How can I enable MySQL's slow query log without restarting MySQL?

For slow queries on version < 5.1, the following configuration worked for me:

log_slow_queries=/var/log/mysql/slow-query.log
long_query_time=20
log_queries_not_using_indexes=YES

Also note to place it under [mysqld] part of the config file and restart mysqld.

Is header('Content-Type:text/plain'); necessary at all?

no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a zipped data and it has to upzip it,this is a example where Type really matters at Bowser.

How can I change the version of npm using nvm?

Changing npm versions on linux based OSs isn't a straight forward one command process yet. I have done following to switch back to older version of npm. This should work to get any version of npm working. First install the version of npm you want to use:

sudo npm install -g [email protected]

Remove the sym link in /usr/local/bin/

sudo rm /usr/local/bin/npm

Recreate the sym link using the desired version of npm you have installed

sudo ln -s /usr/bin/[email protected] /usr/local/bin/npm

Adding blur effect to background in swift

You should always use .dark for style and add the following code to make it look cool

    blurEffectView.backgroundColor = .black
    blurEffectView.alpha = 0.4

What is phtml, and when should I use a .phtml extension rather than .php?

To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.

setBackground vs setBackgroundDrawable (Android)

Now you can use either of those options. And it is going to work in any case. Your color can be a HEX code, like this:

myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));

A color resource, like this:

myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));

Or a custom xml resource, like so:

myView.setBackgroundResource(R.drawable.my_custom_background);

Hope it helps!

Difference between onLoad and ng-init in angular

From angular's documentation,

ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit

onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude

The major difference between them is when used with ng-include.

<div ng-include="partialViewUrl" onload="myFunction()"></div>

In this case, myFunction is called everytime the partial view is loaded.

<div ng-include="partialViewUrl" ng-init="myFunction()"></div>

Whereas, in this case, myFunction is called only once when the parent view is loaded.

Show "loading" animation on button click

I know this a very much late reply but I saw this query recently And found a working scenario,

OnClick of Submit use the below code:

 $('#Submit').click(function ()
 { $(this).html('<img src="icon-loading.gif" />'); // A GIF Image of Your choice
 return false });

To Stop the Gif use the below code:

$('#Submit').ajaxStop();

Resolve absolute path from relative path and/or file name

Without having to have another batch file to pass arguments to (and use the argument operators), you can use FOR /F:

FOR /F %%i IN ("..\relativePath") DO echo absolute path: %%~fi

where the i in %%~fi is the variable defined at /F %%i. eg. if you changed that to /F %%a then the last part would be %%~fa.

To do the same thing right at the command prompt (and not in a batch file) replace %% with %...

Nested ng-repeat

Create a dummy tag that is not going to rendered on the page but it will work as holder for ng-repeat:

<dummyTag ng-repeat="featureItem in item.features">{{featureItem.feature}}</br> </dummyTag>

Android Studio cannot resolve R in imported project?

This is probably due to a failed resource build

Once the issue is fixed, a mere Build > Rebuild Project will do the trick

Draw text in OpenGL ES

Rendering text to a texture is simpler than what the Sprite Text demo make it looks like, the basic idea is to use the Canvas class to render to a Bitmap and then pass the Bitmap to an OpenGL texture:

// Create an empty, mutable bitmap
Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);

// get a background image from resources
// note the image format must match the bitmap format
Drawable background = context.getResources().getDrawable(R.drawable.background);
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap

// Draw the text
Paint textPaint = new Paint();
textPaint.setTextSize(32);
textPaint.setAntiAlias(true);
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
// draw the text centered
canvas.drawText("Hello World", 16,112, textPaint);

//Generate one texture pointer...
gl.glGenTextures(1, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

//Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

//Clean up
bitmap.recycle();

php error: Class 'Imagick' not found

From: http://news.ycombinator.com/item?id=1726074

For RHEL-based i386 distributions:

yum install ImageMagick.i386
yum install ImageMagick-devel.i386
pecl install imagick
echo "extension=imagick.so" > /etc/php.d/imagick.ini
service httpd restart

This may also work on other i386 distributions using yum package manager. For x86_64, just replace .i386 with .x86_64

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

it is because you already defined the 'abuse_id' as auto increment, then there is no need to insert its value. it will be inserted automatically. the error comes because you are inserting 1 many times that is duplication of data. the primary key should be unique. should not be repeated.

the thing you have to do is to change your insertion query as below

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I     thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

How to install a specific JDK on Mac OS X?

As the message says, you have to go to Apple, not Sun, for Java on the Mac. As far as I know, Apple JDK 6 is installed by default on Mac OS X 10.6 (Snow Leopard). Maybe you need to install the developer tools from your Mac OS X installation DVD (the dev tools are an optional install from the OS DVD).

See: http://developer.apple.com/java/

NOTE This answer from 16 Oct 2009 is now outdated; you can get the JDK for Mac OS X from the regular JDK download page on Oracle's website now.

Convert blob to base64

I wanted something where I have access to base64 value to store into a list and for me adding event listener worked. You just need the FileReader which will read the image blob and return the base64 in the result.

createImageFromBlob(image: Blob) {
    const reader = new FileReader();
    const supportedImages = []; // you can also refer to some global variable
    reader.addEventListener(
      'load',
      () => {
        // reader.result will have the required base64 image
        const base64data = reader.result;
        supportedImages.push(base64data); // this can be a reference to global variable and store the value into that global list so as to use it in the other part
      },
      false
    );
    // The readAsDataURL method is used to read the contents of the specified Blob or File.
    if (image) {
      reader.readAsDataURL(image);
    }
 }

Final part is the readAsDataURL which is very important is being used to read the content of the specified Blob

How to Find And Replace Text In A File With C#

You need to write all the lines you read into the output file, even if you don't change them.

Something like:

using (var input = File.OpenText("input.txt"))
using (var output = new StreamWriter("output.txt")) {
  string line;
  while (null != (line = input.ReadLine())) {
     // optionally modify line.
     output.WriteLine(line);
  }
}

If you want to perform this operation in place then the easiest way is to use a temporary output file and at the end replace the input file with the output.

File.Delete("input.txt");
File.Move("output.txt", "input.txt");

(Trying to perform update operations in the middle of text file is rather hard to get right because always having the replacement the same length is hard given most encodings are variable width.)

EDIT: Rather than two file operations to replace the original file, better to use File.Replace("input.txt", "output.txt", null). (See MSDN.)

Outline radius?

As others have said, only firefox supports this. Here is a work around that does the same thing, and even works with dashed outlines.

example

_x000D_
_x000D_
.has-outline {_x000D_
    display: inline-block;_x000D_
    background: #51ab9f;_x000D_
    border-radius: 10px;_x000D_
    padding: 5px;_x000D_
    position: relative;_x000D_
}_x000D_
.has-outline:after {_x000D_
  border-radius: 10px;_x000D_
  padding: 5px;_x000D_
  border: 2px dashed #9dd5cf;_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  top: -2px;_x000D_
  left: -2px;_x000D_
  bottom: -2px;_x000D_
  right: -2px;_x000D_
}
_x000D_
<div class="has-outline">_x000D_
  I can haz outline_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to prevent line breaks in list items using CSS

If you want to achieve this selectively (ie: only to that particular link), you can use a non-breaking space instead of a normal space:

<li>submit&nbsp;resume</li>

https://en.wikipedia.org/wiki/Non-breaking_space#Encodings

edit: I understand that this is HTML, not CSS as requested by the OP, but some may find it helpful…

Access host database from a docker container

From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:

docker.for.mac.localhost

The documentation is here: https://docs.docker.com/docker-for-mac/networking/#httphttps-proxy-support

ReactJS: Maximum update depth exceeded error

Forget about the react first:
This is not related to react and let us understand the basic concepts of Java Script. For Example you have written following function in java script (name is A).

function a() {

};

Q.1) How to call the function that we have defined?
Ans: a();

Q.2) How to pass reference of function so that we can call it latter?
Ans: let fun = a;

Now coming to your question, you have used paranthesis with function name, mean that function will be called when following statement will be render.

_x000D_
_x000D_
<td><span onClick={this.toggle()}>Details</span></td>
_x000D_
_x000D_
_x000D_

Then How to correct it?
Simple!! Just remove parenthesis. By this way you have given the reference of that function to onClick event. It will call back your function only when your component is clicked.

_x000D_
_x000D_
 <td><span onClick={this.toggle}>Details</span></td>
_x000D_
_x000D_
_x000D_

One suggestion releated to react:
Avoid using inline function as suggested by someone in answers, it may cause performance issue. Avoid following code, It will create instance of same function again and again whenever function will be called (lamda statement creates new instance every time).
Note: and no need to pass event (e) explicitly to the function. you can access it with in the function without passing it.

_x000D_
_x000D_
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
_x000D_
_x000D_
_x000D_

https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578

PHP Include for HTML?

Try to get some debugging information, could be that the file path is wrong, for example.

Try these two things:- Add this line to the top of your sample page:

<?php error_reporting(E_ALL);?>

This will print all errors/warnings/notices in the page so if there is any problem you get a text message describing it instead of a blank page

Additionally you can change include() to require()

<?php require ('headings.php'); ?>
<?php require ('navbar.php'); ?>
<?php require ('image.php'); ?>

This will throw a FATAL error PHP is unable to load required pages, and should help you in getting better tracing what is going wrong..

You can post the error descriptions here, if you get any, and you are unable to figure out what it means..

SQL Server: Examples of PIVOTing String data

From http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/:

SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO

Find indices of elements equal to zero in a NumPy array

numpy.where() is my favorite.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])

How to start automatic download of a file in Internet Explorer?

<meta http-equiv="Refresh" content="n;url">

That's It. Easy, Right?

_x000D_
_x000D_
<meta http-equiv="Refresh" content="n;url">
_x000D_
_x000D_
_x000D_

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

I also vote for GemBox.Spreadsheet.

Very fast and easy to use, with tons of examples on their site.

Took my reporting tasks on a whole new level of execution speed.

Add target="_blank" in CSS

Unfortunately, no. In 2013, there is no way to do it with pure CSS.


Update: thanks to showdev for linking to the obsolete spec of CSS3 Hyperlinks, and yes, no browser has implemented it. So the answer still stands valid.

Database development mistakes made by application developers

1) Poor understanding of how to properly interact between Java and the database.

2) Over parsing, improper or no reuse of SQL

3) Failing to use BIND variables

4) Implementing procedural logic in Java when SQL set logic in the database would have worked (better).

5) Failing to do any reasonable performance or scalability testing prior to going into production

6) Using Crystal Reports and failing to set the schema name properly in the reports

7) Implementing SQL with Cartesian products due to ignorance of the execution plan (did you even look at the EXPLAIN PLAN?)

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}

hexadecimal string to byte array in python

provided I understood correctly, you should look for binascii.unhexlify

import binascii
a='45222e'
s=binascii.unhexlify(a)
b=[ord(x) for x in s]

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

How do I remove carriage returns with Ruby?

If you are using Rails, there is a squish method

"\tgoodbye\r\n".squish => "goodbye"

"\tgood \t\r\nbye\r\n".squish => "good bye"

How to Initialize char array from a string

You can't - in C. In C initializing of global and local static variables are designed such that the compiler can put the values statically into the executable. It can't handle non-constant expressions as initializers. And only in C99, you can use non-constant expression in aggregate initializers - not so in C89!

In your case, since your array is an array containing characters, each element has to be an arithmetic constant expression. Look what it says about those

An arithmetic constant expression shall have arithmetic type and shall only have operands that are integer constants, ?oating constants, enumeration constants, character constants, and sizeof expressions.

Surely this is not satisfied by your initializer, which uses an operand of pointer type. Surely, the other way is to initialize your array using a string literal, as it explains too

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

All quotes are taken out of the C99 TC3 committee draft. So to conclude, what you want to do - using non-constant expression - can't be done with C. You have several options:

  • Write your stuff multiple times - one time reversed, and the other time not reversed.
  • Change the language - C++ can do that all.
  • If you really want to do that stuff, use an array of char const* instead

Here is what i mean by the last option

char const c[] = "ABCD";
char const *f[] = { &c[0], &c[1], &c[2], &c[3] };
char const *g[] = { &c[3], &c[2], &c[1], &c[0] };

That works fine, as an address constant expression is used to initialize the pointers

An address constant is a null pointer, a pointer to an lvalue designating an object of static storage duration, or a pointer to a function designator; it shall be created explicitly using the unary & operator or an integer constant cast to pointer type, or implicitly by the use of an expression of array or function type. The array-subscript [] and member-access . and -> operators, the address & and indirection * unary operators, and pointer casts may be used in the creation of an address constant, but the value of an object shall not be accessed by use of these operators.

You may have luck tweaking your compiler options - another quote:

An implementation may accept other forms of constant expressions.

C# Collection was modified; enumeration operation may not execute

As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:

foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....

    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

What may not be obvious from the code above is where the Enumerator comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach loop gets expanded to by the compiler. The generated code will look something like:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator() returns) you will see:

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.

How to serve up a JSON response using Go?

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

Determine the path of the executing BASH script

Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

printf '%s\n' "$prg"

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

You need to use js get better height for body div

<html><body>
<div id="head" style="height:50px; width=100%; font-size:50px;">This is head</div>
<div id="body" style="height:700px; font-size:100px; white-space:pre-wrap;    overflow:scroll;">
This is body
T
h
i
s

i
s

b 
o
d
y
</div>
</body></html>