Programs & Examples On #Keylistener

A KeyListener is an implementation of the Observer pattern which is created specifically for handling keyboard events.

Unresponsive KeyListener for JFrame

This should help

    yourJFrame.setFocusable(true);
    yourJFrame.addKeyListener(new java.awt.event.KeyAdapter() {


        @Override
        public void keyTyped(KeyEvent e) {
            System.out.println("you typed a key");
        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("you pressed a key");
        }

        @Override
        public void keyReleased(KeyEvent e) {
            System.out.println("you released a key");
        }
    });

Key Listeners in python?

I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys

Keylistener in Javascript

Did you check the small Mousetrap library?

Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.

Place cursor at the end of text in EditText

If you called setText before and the new text didn't get layout phase call setSelection in a separate runnable fired by View.post(Runnable) (repost from this topic).

So, for me this code works:

editText.setText("text");
editText.post(new Runnable() {
         @Override
         public void run() {
             editText.setSelection(editText.getText().length());
         }
});

Edit 05/16/2019: Right now I'm using Kotlin extension for that:

fun EditText.placeCursorToEnd() {
    this.setSelection(this.text.length)
}

and then - editText.placeCursorToEnd().

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        super(s);
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        p.add(label);
        add(p);
        addKeyListener(this);
        setSize(200, 100);
        setVisible(true);

    }

    @Override
    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");
        }

    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        }
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");
        }
    }

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");
    }
}

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

Without a frame this works for me:

JTextField tf = new JTextField(20);
tf.addKeyListener(new KeyAdapter() {

  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
       SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
    }
  }
});
String[] options = {"Ok", "Cancel"};
int result = JOptionPane.showOptionDialog(
    null, tf, "Enter your message", 
    JOptionPane.OK_CANCEL_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null,
    options,0);

message = tf.getText();

KeyListener, keyPressed versus keyTyped

Neither. You should NOT use a KeyLIstener.

Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings.

Call to a member function on a non-object

you can use 'use' in function like bellow example

function page_properties($objPortal) use($objPage){    
    $objPage->set_page_title($myrow['title']);
}

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

For my situation, I switched the value of "fork" to false, such as <fork>false</fork>. I do not understand why, hope someone could explain to me. Thanks in advance.

Put quotes around a variable string in JavaScript

I think, the best and easy way for you, to put value inside quotes is:

JSON.stringify(variable or value)

How to set page content to the middle of screen?

I'm guessing you want to center the box both vertically and horizontally, regardless of browser window size. Since you have a fixed width and height for the box, this should work:

Markup:

<div></div>

CSS:

div {
    height: 200px;
    width: 400px;
    background: black;

    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

The div should remain in the center of the screen even if you resize the browser. Just replace the margin-top and margin-left with half of the height and width of your table.

Edit: Credit goes to CSS-Tricks, where I got the original idea.

How to set OnClickListener on a RadioButton in Android?

You could also add listener from XML layout: android:onClick="onRadioButtonClicked" in your <RadioButton/> tag.

<RadioButton android:id="@+id/radio_pirates"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pirates"
    android:onClick="onRadioButtonClicked"/>

See Android developer SDK- Radio Buttons for details.

Alternative to google finance api

If you are still looking to use Google Finance for your data you can check this out.

I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)

SQL Server: combining multiple rows into one row

Using MySQL inbuilt function group_concat() will be a good choice for getting the desired result. The syntax will be -

SELECT group_concat(STRINGVALUE) 
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534
AND ISSUE = 19602

Before you execute the above command make sure you increase the size of group_concat_max_len else the the whole output may not fit in that cell.

To set the value of group_concat_max_len, execute the below command-

SET group_concat_max_len = 50000;

You can change the value 50000 accordingly, you increase it to a higher value as required.

Java - Check if JTextField is empty or not

Try this

if(name.getText() != null && name.getText().equals(""))
{
        loginbt.setEnabled(false);
}
else
{
        loginbt.setEnabled(true);
}

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

Try using No Wrap - In Head or No wrap - in body in your fiddle:

Working fiddle: http://jsfiddle.net/Q5hd6/

Explanation:

Angular begins compiling the DOM when the DOM is fully loaded. You register your code to run onLoad (onload option in fiddle) => it's too late to register your myApp module because angular begins compiling the DOM and angular sees that there is no module named myApp and throws an exception.

By using No Wrap - In Head, your code looks like this:

<head>

    <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>

    <script type='text/javascript'>
      //Your script.
    </script>

</head>

Your script has a chance to run before angular begins compiling the DOM and myApp module is already created when angular starts compiling the DOM.

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

The difference between the Runnable and Callable interfaces in Java

It is a kind of an interface naming convention which matches with functional programming

//Runnable
interface Runnable {
    void run();
}

//Action - throws exception
interface Action {
    void run() throws Exception;
}

//Consumer - consumes a value/values, throws exception
interface Consumer1<T> {
    void accept(T t) throws Exception;
}

//Callable - return result, throws exception
interface Callable<R> {
    R call() throws Exception;
}

//Supplier - returns result, throws exception
interface Supplier<R> {
    R get() throws Exception;
}

//Predicate - consumes a value/values, returns true or false, throws exception
interface Predicate1<T> {
    boolean test(T t) throws Exception;
}

//Function - consumes a value/values, returns result, throws exception
public interface Function1<T, R> {
    R apply(T t) throws Exception;
}

...

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

string to string array conversion in java

In java 8, there is a method with which you can do this: toCharArray():

String k = "abcdef";
char[] x = k.toCharArray();

This results to the following array:

[a,b,c,d,e,f]

How to Set AllowOverride all

As other users explained here about the usage of allowoveride directive, which is used to give permission to .htaccess usage. one thing I want to point out that never use allowoverride all if other users have access to write .htaccess instead use allowoveride as to permit certain modules.

Such as AllowOverride AuthConfig mod_rewrite Instead of

AllowOverride All

Because module like mod_mime can render your server side files as plain text.

Converting String Array to an Integer Array

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

How should I call 3 functions in order to execute them one after the other?

asec=1000; 

setTimeout('some_3secs_function("somevalue")',asec*3);
setTimeout('some_5secs_function("somevalue")',asec*5);
setTimeout('some_8secs_function("somevalue")',asec*8);

I won't go into a deep discussion of setTimeout here, but:

  • in this case I've added the code to execute as a string. this is the simplest way to pass a var into your setTimeout-ed function, but purists will complain.
  • you can also pass a function name without quotes, but no variable can be passed.
  • your code does not wait for setTimeout to trigger.
  • This one can be hard to get your head around at first: because of the previous point, if you pass a variable from your calling function, that variable will not exist anymore by the time the timeout triggers - the calling function will have executed and it's vars gone.
  • I have been known to use anonymous functions to get around all this, but there could well be a better way,

How do I set <table> border width with CSS?

The reason it didn't work is that despite setting the border-width and the border-color you didn't specify the border-style:

<table style="border-width:1px;border-color:black;border-style:solid;">

JS Fiddle demo.

It's usually better to define the styles in the stylesheet (so that all elements are styled without having to find, and change, every element's style attribute):

table {
    border-color: #000;
    border-width: 1px;
    border-style: solid;
    /* or, of course,
    border: 1px solid #000;
    */
}

JS Fiddle demo (Or using shorthand border notation).

How do I find the time difference between two datetime objects in python?

Just subtract one from the other. You get a timedelta object with the difference.

>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)

You can convert dd.days, dd.seconds and dd.microseconds to minutes.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:

<configuration>
  <appSettings>
    <add key="key" value="value"/>
  </appSettings>
</configuration>

angular-cli server - how to specify default port

Update for @angular/[email protected]: and over

In angular.json you can specify a port per "project"

"projects": {
    "my-cool-project": {
        ... rest of project config omitted
        "architect": {
            "serve": {
                "options": {
                    "port": 1337
                }
            }
        }
    }
}

All options available:

https://angular.io/guide/workspace-config#project-tool-configuration-options

Alternatively, you may specify the port each time when running ng serve like this:

ng serve --port 1337

With this approach you may wish to put this into a script in your package.json to make it easier to run each time / share the config with others on your team:

"scripts": {
    "start": "ng serve --port 1337"
}

Legacy:

Update for @angular/cli final:

Inside angular-cli.json you can specify the port in the defaults:

"defaults": {
  "serve": {
    "port": 1337
  }
}

Legacy-er:

Tested in [email protected]

The server in angular-cli comes from the ember-cli project. To configure the server, create an .ember-cli file in the project root. Add your JSON config in there:

{
   "port": 1337
}

Restart the server and it will serve on that port.

There are more options specified here: http://ember-cli.com/#runtime-configuration

{
  "skipGit" : true,
  "port" : 999,
  "host" : "0.1.0.1",
  "liveReload" : true,
  "environment" : "mock-development",
  "checkForUpdates" : false
}

How to use glyphicons in bootstrap 3.0

The icons (glyphicons) are now contained in a separate css file...

The markup has changed to:

<i class="glyphicon glyphicon-search"></i>

or

<span class="glyphicon glyphicon-search"></span>

Here is a helpful list of changes for Bootstrap 3: http://bootply.com/bootstrap-3-migration-guide

Automatically plot different colored lines

Actually, a decent shortcut method for getting the colors to cycle is to use hold all; in place of hold on;. Each successive plot will rotate (automatically for you) through MATLAB's default colormap.

From the MATLAB site on hold:

hold all holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.

How can you run a command in bash over and over until success?

until passwd
do
  echo "Try again"
done

or

while ! passwd
do
  echo "Try again"
done

How can I calculate the difference between two ArrayLists?

I have used Guava Sets.difference.

The parameters are sets and not general collections, but a handy way to create sets from any collection (with unique items) is Guava ImmutableSet.copyOf(Iterable).

(I first posted this on a related/dupe question, but I'm copying it here too since I feel it is a good option that is so far missing.)

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I get this error whenever I use np.concatenate the wrong way:

>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:

>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I ran into this error because I was attempting to write a string to a cell which started with an "=".

The solution was to put an "'" (apostrophe) before the equals sign, which is a way to tell excel that you're not, in fact, trying to write a formula, and just want to print the equals sign.

Collection was modified; enumeration operation may not execute in ArrayList

You are removing the item during a foreach, yes? Simply, you can't. There are a few common options here:

  • use List<T> and RemoveAll with a predicate
  • iterate backwards by index, removing matching items

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • use foreach, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)

UIImage: Resize, then Crop

Xamarin.iOS version for accepted answer on how to resize and then crop UIImage (Aspect Fill) is below

    public static UIImage ScaleAndCropImage(UIImage sourceImage, SizeF targetSize)
    {
        var imageSize = sourceImage.Size;
        UIImage newImage = null;
        var width = imageSize.Width;
        var height = imageSize.Height;
        var targetWidth = targetSize.Width;
        var targetHeight = targetSize.Height;
        var scaleFactor = 0.0f;
        var scaledWidth = targetWidth;
        var scaledHeight = targetHeight;
        var thumbnailPoint = PointF.Empty;
        if (imageSize != targetSize)
        {
            var widthFactor = targetWidth / width;
            var heightFactor = targetHeight / height;
            if (widthFactor > heightFactor)
            {
                scaleFactor = widthFactor;// scale to fit height
            }
            else
            {
                scaleFactor = heightFactor;// scale to fit width
            }
            scaledWidth = width * scaleFactor;
            scaledHeight = height * scaleFactor;
            // center the image
            if (widthFactor > heightFactor)
            {
                thumbnailPoint.Y = (targetHeight - scaledHeight) * 0.5f;
            }
            else
            {
                if (widthFactor < heightFactor)
                {
                    thumbnailPoint.X = (targetWidth - scaledWidth) * 0.5f;
                }
            }
        }
        UIGraphics.BeginImageContextWithOptions(targetSize, false, 0.0f);
        var thumbnailRect = new RectangleF(thumbnailPoint, new SizeF(scaledWidth, scaledHeight));
        sourceImage.Draw(thumbnailRect);
        newImage = UIGraphics.GetImageFromCurrentImageContext();
        if (newImage == null)
        {
            Console.WriteLine("could not scale image");
        }
        //pop the context to get back to the default
        UIGraphics.EndImageContext();

        return newImage;
    }

Create pandas Dataframe by appending one row at a time

Here is the way to add/append a row in pandas DataFrame

def add_row(df, row):
    df.loc[-1] = row
    df.index = df.index + 1  
    return df.sort_index()

add_row(df, [1,2,3]) 

It can be used to insert/append a row in empty or populated pandas DataFrame

ORA-01438: value larger than specified precision allows for this column

From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):

ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.

http://ora-06512.ora-code.com/:

ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.

Java way to check if a string is palindrome

Here is a simple one"

public class Palindrome {

    public static void main(String [] args){
        Palindrome pn = new Palindrome();

        if(pn.isPalindrome("ABBA")){
            System.out.println("Palindrome");
        } else {
            System.out.println("Not Palindrome");
        }   
    }

    public boolean isPalindrome(String original){
        int i = original.length()-1;
        int j=0;
        while(i > j) {
            if(original.charAt(i) != original.charAt(j)) {
                return false;
            }
            i--;
            j++;
        }
        return true;
    }
}

iPhone SDK on Windows (alternative solutions)

This really comes down to how much you value your time. As the other posters have mentioned, there are a couple of ways you can build iPhone apps without a Mac. However, you are jumping through serious hoops, and it'll be much more difficult and take longer than it would with the proper development chain.

You can buy a second-hand Mac Mini for a couple of hundred bucks on eBay. If you're serious about doing iPhone development you'll make this back in saved time very quickly.

Select data from "show tables" MySQL query

SELECT * FROM INFORMATION_SCHEMA.TABLES

That should be a good start. For more, check INFORMATION_SCHEMA Tables.

How do I get the full path of the current file's directory?

IPython has a magic command %pwd to get the present working directory. It can be used in following way:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwd can be used directly as following:

present_working_directory = %pwd

How to import keras from tf.keras in Tensorflow?

To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.

In Keras (v2.1.5)

from keras.models import Sequential
from keras.layers import Dense

def get_model(n_x, n_h1, n_h2):
    model = Sequential()
    model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(Dense(n_h2, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    return model

In tf.keras (v1.9)

import tensorflow as tf

def get_model(n_x, n_h1, n_h2):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(4, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    return model

or it can be imported the following way instead of the above-mentioned way

from tensorflow.keras.layers import Dense

The official documentation of tf.keras

Note: TensorFlow Version is 1.9

Wait until page is loaded with Selenium WebDriver for Python

Trying to pass find_element_by_id to the constructor for presence_of_element_located (as shown in the accepted answer) caused NoSuchElementException to be raised. I had to use the syntax in fragles' comment:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get('url')
timeout = 5
try:
    element_present = EC.presence_of_element_located((By.ID, 'element_id'))
    WebDriverWait(driver, timeout).until(element_present)
except TimeoutException:
    print "Timed out waiting for page to load"

This matches the example in the documentation. Here is a link to the documentation for By.

Can we update primary key values of a table?

Short answer: yes you can. Of course you'll have to make sure that the new value doesn't match any existing value and other constraints are satisfied (duh).

What exactly are you trying to do?

What techniques can be used to speed up C++ compilation times?

  • Upgrade your computer

    1. Get a quad core (or a dual-quad system)
    2. Get LOTS of RAM.
    3. Use a RAM drive to drastically reduce file I/O delays. (There are companies that make IDE and SATA RAM drives that act like hard drives).
  • Then you have all your other typical suggestions

    1. Use precompiled headers if available.
    2. Reduce the amount of coupling between parts of your project. Changing one header file usually shouldn't require recompiling your entire project.

How to see what privileges are granted to schema of another user

Use example with from the post of Szilágyi Donát.

I use two querys, one to know what roles I have, excluding connect grant:

SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema

Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:

SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.

The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).

Regards.

How can I get a process handle by its name in C++?

The following code shows how you can use toolhelp and OpenProcess to get a handle to the process. Error handling removed for brevity.

HANDLE GetProcessByName(PCSTR name)
{
    DWORD pid = 0;

    // Create toolhelp snapshot.
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

    // Walkthrough all processes.
    if (Process32First(snapshot, &process))
    {
        do
        {
            // Compare process.szExeFile based on format of name, i.e., trim file path
            // trim .exe if necessary, etc.
            if (string(process.szExeFile) == string(name))
            {
               pid = process.th32ProcessID;
               break;
            }
        } while (Process32Next(snapshot, &process));
    }

    CloseHandle(snapshot);

    if (pid != 0)
    {
         return OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    }

    // Not found


       return NULL;
}

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

How to remove the focus from a TextBox in WinForms?

The way I get around it is to place all my winform controls. I make all labels and non-selecting winform controls as tab order 0, then my first control as tab order 2 and then increment each selectable control's order by 1, so 3, 4, 5 etc...

This way, when my Winforms start up, the first TextBox doesn't have focus!

How can I catch all the exceptions that will be thrown through reading and writing a file?

You may catch multiple exceptions in single catch block.

try{
  // somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
  // handle exception.
} 

Convert Json Array to normal Java list

If you don't already have a JSONArray object, call

JSONArray jsonArray = new JSONArray(jsonArrayString);

Then simply loop through that, building your own array. This code assumes it's an array of strings, it shouldn't be hard to modify to suit your particular array structure.

List<String> list = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    list.add( jsonArray.getString(i) );
}

Retrieve a single file from a repository

I solved in this way:

git archive --remote=ssh://[email protected]/user/mi-repo.git BranchName /path-to-file/file_name | tar -xO /path-to-file/file_name > /path-to-save-the-file/file_name

If you want, you could replace "BranchName" for "HEAD"

How do I know which version of Javascript I'm using?

JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.

List an Array of Strings in alphabetical order

Weird, your code seems to work for me:

import java.util.Arrays;

public class Test
{
    public static void main(String[] args)
    {
        // args is the list of guests
        Arrays.sort(args);
        for(int i = 0; i < args.length; i++)
            System.out.println(args[i]);
    }
}

I ran that code using "java Test Bobby Joe Angel" and here is the output:

$ java Test Bobby Joe Angel
Angel
Bobby
Joe

Cannot instantiate the type List<Product>

List is an interface. Interfaces cannot be instantiated. Only concrete types can be instantiated. You probably want to use an ArrayList, which is an implementation of the List interface.

List<Product> products = new ArrayList<Product>();

How to get Current Directory?

If you are using the Poco library, it's a one liner and it should work on all platforms I think.

Poco::Path::current()

UIImageView aspect fit and center

Updated answer

When I originally answered this question in 2014, there was no requirement to not scale the image up in the case of a small image. (The question was edited in 2015.) If you have such a requirement, you will indeed need to compare the image's size to that of the imageView and use either UIViewContentModeCenter (in the case of an image smaller than the imageView) or UIViewContentModeScaleAspectFit in all other cases.

Original answer

Setting the imageView's contentMode to UIViewContentModeScaleAspectFit was enough for me. It seems to center the images as well. I'm not sure why others are using logic based on the image. See also this question: iOS aspect fit and center

How to convert string representation of list to a list?

If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).

>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']

If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar - like this one on the pyparsing wiki, which will handle tuples, lists, ints, floats, and quoted strings. Will work with Python versions back to 2.4.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You need to include xmlbeans-xxx.jar and if you have downloaded the POI binary zip, you will get the xmlbeans-xxx.jar in ooxml-lib folder (eg: \poi-3.11\ooxml-lib)

This jar is used for XML binding which is applicable for .xlsx files.

what is the use of "response.setContentType("text/html")" in servlet

It means what type of response you want to send to client, some content types like :

 res.setContentType("image/gif");
 res.setContentType("application/pdf");
 res.setContentType("application/zip");

What is the purpose of a plus symbol before a variable?

It is a unary "+" operator which yields a numeric expression. It would be the same as d*1, I believe.

jQuery and TinyMCE: textarea value doesn't submit

This will ensure that the content gets save when you lose focus of the textarea

 setup: function (editor) {
                editor.on('change', function () {
                    tinymce.triggerSave();
                });

Checking the equality of two slices

You should use reflect.DeepEqual()

DeepEqual is a recursive relaxation of Go's == operator.

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

Array values are deeply equal when their corresponding elements are deeply equal.

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

Interface values are deeply equal if they hold deeply equal concrete values.

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

How to delete a file from SD card?

Try this.

File file = new File(FilePath);
FileUtils.deleteDirectory(file);

from Apache Commons

Set padding for UITextField with UITextBorderStyleNone

textField.layer.borderWidth = 3;

will add border, which worked as padding for me.

Grep characters before and after match?

You could use

awk '/test_pattern/ {
    match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

I had this problem when I added the group of the login user to another user.

Let's say there is an SSH-login user called userA and a non-SSH-login user userB. userA has the group userA as well. I modified userB to have the group userA as well. The lead to the the described behaviour, so that userA was not able to login without a prompt.

After I removed the group userA from userB, the login without a prompt worked again.

PHP date() with timezone?

You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.

Upload Progress Bar in PHP

A php/ajax progress bar can be done. (Checkout the Html_Ajax library in pear). However this requires installing a custom module into php.

Other methods require using an iframe, through which php looks to see how much of the file has been uploaded. However this hidden iframe, may be blocked by some browsers addons because hidden iframes are often used to send malicious data to a users computer.

Your best bet is to use some form of flash progress bar if you do not have control over your server.

How to click on hidden element in Selenium WebDriver?

Here is the script in Python.

You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.

element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

In Java how does one turn a String into a char or a char into a String?

I like to do something like this:

String oneLetter = "" + someChar;

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Angular 2 Date Input not binding to date value

use DatePipe

> // ts file

import { DatePipe } from '@angular/common';

@Component({
....
providers:[DatePipe]
})

export class FormComponent {

constructor(private datePipe : DatePipe){}

    demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);  
}

c++ compile error: ISO C++ forbids comparison between pointer and integer

You need the change those double quotation marks into singles. ie. if (answer == 'y') returns true;

Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx

How to change spinner text size and text color?

Can change the text colour by overriding the getView method as follows:

 new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, list()){
                @Override
                public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    //change the color to which ever you want                    
                    ((CheckedTextView) view).setTextColor(Color.RED);
                    //change the size to which ever you want                    
                    ((CheckedTextView) view).setTextSize(5);
                    //for using sp values use setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    return view;
                }
    }

google-services.json for different productFlavors

Inspired by @ahmed_khan_89 answer above. We can directly keep like this in gradle file.

android{

// set build flavor here to get the right Google-services configuration(Google Analytics).
    def currentFlavor = "free" //This should match with Build Variant selection. free/paidFull/paidBasic

    println "--> $currentFlavor copy!"
    copy {
        from "src/$currentFlavor/"
        include 'google-services.json'
        into '.'
    }
//other stuff
}

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.

I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11

JavaScript array to CSV

If your data contains any newlines or commas, you will need to escape those first:

const escape = text =>
    text.replace(/\\/g, "\\\\")
        .replace(/\n/g, "\\n")
        .replace(/,/g, "\\,")

escaped_array = test_array.map(fields => fields.map(escape))

Then simply do:

csv = escaped_array.map(fields => fields.join(","))
                .join("\n")

If you want to make it downloadable in-browser:

dl = "data:text/csv;charset=utf-8," + csv
window.open(encodeURI(dl))

Scroll to element on click in Angular 4

Here is how I did it using Angular 4.

Template

<div class="col-xs-12 col-md-3">
  <h2>Categories</h2>
  <div class="cat-list-body">
    <div class="cat-item" *ngFor="let cat of web.menu | async">
      <label (click)="scroll('cat-'+cat.category_id)">{{cat.category_name}}</label>
    </div>
  </div>
</div>

add this function to the Component.

scroll(id) {
  console.log(`scrolling to ${id}`);
  let el = document.getElementById(id);
  el.scrollIntoView();
}

Couldn't connect to server 127.0.0.1:27017

Step 1: Remove lock file.
sudo rm /var/lib/mongodb/mongod.lock

Step 2: Repair mongodb. 
sudo mongod --repair 

Step 3: start mongodb.
sudo start mongodb 
or
sudo service mongodb start

Step 4: Check status of mongodb.
sudo status mongodb 
or   
sudo service mongodb status

Step 5: Start mongo console.
mongo 

Where does Chrome store extensions?

Storage Location for Unpacked Extensions

Extension engine does not explicitly change their location or add a reference to its local paths, they are left in the place where there are selected from in all Operating Systems.

Ex: If i load a unpacked Extension from E:\Chrome Extension the unpacked Extension is still in the same location

Storage Location for Packed Extensions

Navigate to chrome://version/ and look for Profile Path, it is your default directory and Extensions Folder is where all the extensions, apps, themes are stored

Ex:

Windows

If my Profile Path is %userprofile%\AppData\Local\Google\Chrome\User Data\Default then my storage directory is:

C:\Users\<Your_User_Name>\AppData\Local\Google\Chrome\User Data\Default\Extensions 

Linux

~/.config/google-chrome/Default/Extensions/

MacOS

~/Library/Application\ Support/Google/Chrome/Default/Extensions

Chromium

~/.config/chromium/Default/Extensions

Best way to randomize an array with .NET

Just thinking off the top of my head, you could do this:

public string[] Randomize(string[] input)
{
  List<string> inputList = input.ToList();
  string[] output = new string[input.Length];
  Random randomizer = new Random();
  int i = 0;

  while (inputList.Count > 0)
  {
    int index = r.Next(inputList.Count);
    output[i++] = inputList[index];
    inputList.RemoveAt(index);
  }

  return (output);
}

How to add RSA key to authorized_keys file?

There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.

ssh-copy-id -i /path/to/key/file [email protected]

If the key you are installing is ~/.ssh/id_rsa then you can even drop the -i flag completely.

Much better than manually doing it!

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

In the Global.asax I am using the code below. My URI to get JSON is http://www.digantakumar.com/api/values?json=true

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new  QueryStringMapping("json", "true", "application/json"));
}

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

I have faced same type of issue and followed the below steps to resolved the issue

Go to Tools --> Library Package Manager --> Package Manager Console and run the below command

Install-Package Microsoft.ASPNet.WebAPI -pre

Initializing array of structures

It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name. my_data is obviously a typedef for a struct type that has a member name of type char * or char [N].

React js change child component's state from parent component

Above answer is partially correct for me, but In my scenario, I want to set the value to a state, because I have used the value to show/toggle a modal. So I have used like below. Hope it will help someone.

class Child extends React.Component {
  state = {
    visible:false
  };

  handleCancel = (e) => {
      e.preventDefault();
      this.setState({ visible: false });
  };

  componentDidMount() {
    this.props.onRef(this)
  }

  componentWillUnmount() {
    this.props.onRef(undefined)
  }

  method() {
    this.setState({ visible: true });
  }

  render() {
    return (<Modal title="My title?" visible={this.state.visible} onCancel={this.handleCancel}>
      {"Content"}
    </Modal>)
  }
}

class Parent extends React.Component {
  onClick = () => {
    this.child.method() // do stuff
  }
  render() {
    return (
      <div>
        <Child onRef={ref => (this.child = ref)} />
        <button onClick={this.onClick}>Child.method()</button>
      </div>
    );
  }
}

Reference - https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-252969542

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's the gutsy solution. It assumes you have the actual object to test (rather than a Type).

public static Type ListOfWhat(Object list)
{
    return ListOfWhat2((dynamic)list);
}

private static Type ListOfWhat2<T>(IList<T> list)
{
    return typeof(T);
}

Example usage:

object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();

Prints

typeof(DateTime)

Downloading jQuery UI CSS from Google's CDN

You could use this one if you mean the jQuery UI css:

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

CSS hover vs. JavaScript mouseover

In Internet Explorer, there must be declared a <!DOCTYPE> for the :hover selector to work on other elements than the <a> element.

Spring Data: "delete by" is supported?

@Query(value = "delete from addresses u where u.ADDRESS_ID LIKE %:addressId%", nativeQuery = true)
void deleteAddressByAddressId(@Param("addressId") String addressId);

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

How can I sort a std::map first by value, then by key?

std::map will sort its elements by keys. It doesn't care about the values when sorting.

You can use std::vector<std::pair<K,V>> then sort it using std::sort followed by std::stable_sort:

std::vector<std::pair<K,V>> items;

//fill items

//sort by value using std::sort
std::sort(items.begin(), items.end(), value_comparer);

//sort by key using std::stable_sort
std::stable_sort(items.begin(), items.end(), key_comparer);

The first sort should use std::sort since it is nlog(n), and then use std::stable_sort which is n(log(n))^2 in the worst case.

Note that while std::sort is chosen for performance reason, std::stable_sort is needed for correct ordering, as you want the order-by-value to be preserved.


@gsf noted in the comment, you could use only std::sort if you choose a comparer which compares values first, and IF they're equal, sort the keys.

auto cmp = [](std::pair<K,V> const & a, std::pair<K,V> const & b) 
{ 
     return a.second != b.second?  a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);

That should be efficient.

But wait, there is a better approach: store std::pair<V,K> instead of std::pair<K,V> and then you don't need any comparer at all — the standard comparer for std::pair would be enough, as it compares first (which is V) first then second which is K:

std::vector<std::pair<V,K>> items;
//...
std::sort(items.begin(), items.end());

That should work great.

Store text file content line by line into array

You can use this code. This works very fast!

public String[] loadFileToArray(String fileName) throws IOException {
    String s = new String(Files.readAllBytes(Paths.get(fileName)));
    return Arrays.stream(s.split("\n")).toArray(String[]::new);
}

How to create cross-domain request?

In my experience the plugins worked with http but not with the latest httpClient. Also, configuring the CORS respsonse headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server.

Read more about this here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

below is my prox.conf.json file

{
  "/posts": {
    "target": "https://example.com",
    "secure": true,
    "pathRewrite": {
    "^/posts": ""
  },
    "changeOrigin": true
  }
}

I placed the proxy.conf.json file right next the the package.json file in the same directory

then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from my app component is as follows

return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
  console.log(returnedStuff);
});

Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json

How to Remove Array Element and Then Re-Index Array?

unset($foo[0]); // remove item at index 0
$foo2 = array_values($foo); // 'reindex' array

How to get a list of sub-folders and their files, ordered by folder-names

dir /b /a-d /s *.* will fulfill your requirement.

What is a correct MIME type for .docx, .pptx, etc.?

Swift4

 func mimeTypeForPath(path: String) -> String {
        let url = NSURL(fileURLWithPath: path)
        let pathExtension = url.pathExtension

        if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
            if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
                return mimetype as String
            }
        }
        return "application/octet-stream"
    }

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

Comparing arrays for equality in C++

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.

How to concat two ArrayLists?

If you want to do it one line and you do not want to change list1 or list2 you can do it using stream

List<String> list1 = Arrays.asList("London", "Paris");
List<String> list2 = Arrays.asList("Moscow", "Tver");

List<String> list = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList());

Adding double quote delimiters into csv file

This is actually pretty easy in Excel (or any spreadsheet application).

You'll want to use the =CONCATENATE() function as shown in the formula bar in the following screenshot:

Step 1 involves adding quotes in column B,

Step 2 involves specifying the function and then copying it down column C (by now your spreadsheet should look like the screenshot),

enter image description here

Step 3 (if you need the text outside of the formula) involves copying column C, right-clicking on column D, choosing Paste Special >> Paste Values. Column D should then contain the text that was calculated in column C.

The view or its master was not found or no view engine supports the searched locations

If the problem happens intermittently in production, it could be due to an action method getting interrupted. For example, during a POST operation involving a large file upload, the user closes the browser window before the upload completes. In this case, the action method may throw a null reference exception resulting from a null model or view object. A solution would be to wrap the method body in a try/catch and return null. Like this:

[HttpPost]
public ActionResult Post(...)
{
    try
    {
        ...
    }
    catch (NullReferenceException ex)  // could happen if POST is interrupted
    {
        // perhaps log a warning here
        return null;
    }

    return View(model);
}

How can I get the session object if I have the entity-manager?

'entityManager.unwrap(Session.class)' is used to get session from EntityManager.

@Repository
@Transactional
public class EmployeeRepository {

  @PersistenceContext
  private EntityManager entityManager;

  public Session getSession() {
    Session session = entityManager.unwrap(Session.class);
    return session;
  }

  ......
  ......

}

Demo Application link.

Set keyboard caret position in html textbox

I found an easy way to fix this issue, tested in IE and Chrome:

function setCaret(elemId, caret)
 {
   var elem = document.getElementById(elemId);
   elem.setSelectionRange(caret, caret);
 }

Pass text box id and caret position to this function.

What is the standard naming convention for html/css ids and classes?

Another reason why many prefer hyphens in CSS id and class names is functionality.

Using keyboard shortcuts like option + left/right (or ctrl+left/right on Windows) to traverse code word by word stops the cursor at each dash, allowing you to precisely traverse the id or class name using keyboard shortcuts. Underscores and camelCase do not get detected and the cursor will drift right over them as if it were all one single word.

Open images? Python

Open any file

import os
os.startfile(<filepath>)

How to cache Google map tiles for offline usage?

On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

Project is works in DotNET Core 3.1+ or higher(future)

Add this package:

  1. NuGet: Microsoft.EntityFrameworkCore.Tools
  2. Project Config (.csproj): <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.8">

Copy folder structure (without files) from one location to another

1 line solution:

find . -type d -exec mkdir -p /path/to/copy/directory/tree/{} \;

Making RGB color in Xcode

Yeah.ios supports RGB valur to range between 0 and 1 only..its close Range [0,1]

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

In .NET4.5, MVC 5 no need for widgets.

Javascript:

object in JS: enter image description here

mechanism that does post.

    $('.button-green-large').click(function() {
        $.ajax({
            url: 'Quote',
            type: "POST",
            dataType: "json",
            data: JSON.stringify(document.selectedProduct),
            contentType: 'application/json; charset=utf-8',
        });
    });

C#

Objects:

public class WillsQuoteViewModel
{
    public string Product { get; set; }

    public List<ClaimedFee> ClaimedFees { get; set; }
}

public partial class ClaimedFee //Generated by EF6
{
    public long Id { get; set; }
    public long JourneyId { get; set; }
    public string Title { get; set; }
    public decimal Net { get; set; }
    public decimal Vat { get; set; }
    public string Type { get; set; }

    public virtual Journey Journey { get; set; }
}

Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}

Object received:

enter image description here

Hope this saves you some time.

How to save local data in a Swift app?

They Say Use NSUserDefaults

When I was implementing long term (after app close) data storage for the first time, everything I read online pointed me towards NSUserDefaults. However, I wanted to store a dictionary and, although possible, it was proving to be a pain. I spent hours trying to get type-errors to go away.

NSUserDefaults is Also Limited in Function

Further reading revealed how the read/write of NSUserDefaults really forces the app to read/write everything or nothing, all at once, so it isn't efficient. Then I learned that retrieving an array isn't straight forward. I realized that if you're storing more than a few strings or booleans, NSUserDefaults really isn't ideal.

It's also not scalable. If you're learning how to code, learn the scalable way. Only use NSUserDefaults for storing simple strings or booleans related to preferences. Store arrays and other data using Core Data, it's not as hard as they say. Just start small.

Update: Also, if you add Apple Watch support, there's another potential consideration. Your app's NSUserDefaults is now automatically sent to the Watch Extension.

Using Core Data

So I ignored the warnings about Core Data being a more difficult solution and started reading. Within three hours I had it working. I had my table array being saved in Core Data and reloading the data upon opening the app back up! The tutorial code was easy enough to adapt and I was able to have it store both title and detail arrays with only a little extra experimenting.

So for anyone reading this post who's struggling with NSUserDefault type issues or whose need is more than storing strings, consider spending an hour or two playing with core data.

Here's the tutorial I read:

http://www.raywenderlich.com/85578/first-core-data-app-using-swift

If you didn't check "Core Data"

If you didn't check "Core Data"when you created your app, you can add it after and it only takes five minutes:

http://craig24.com/2014/12/how-to-add-core-data-to-an-existing-swift-project-in-xcode/

http://blog.zeityer.com/post/119012600864/adding-core-data-to-an-existing-swift-project

How to Delete from Core Data Lists

Delete Data from Coredata Swift

Python script to do something at the same time every day

I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.

import datetime as dt

def my_job():
    print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()

Reload child component when variables on parent component changes. Angular2

Use @Input to pass your data to child components and then use ngOnChanges (https://angular.io/api/core/OnChanges) to see if that @Input changed on the fly.

How to determine whether a Pandas Column contains a particular value

in of a Series checks whether the value is in the index:

In [11]: s = pd.Series(list('abc'))

In [12]: s
Out[12]: 
0    a
1    b
2    c
dtype: object

In [13]: 1 in s
Out[13]: True

In [14]: 'a' in s
Out[14]: False

One option is to see if it's in unique values:

In [21]: s.unique()
Out[21]: array(['a', 'b', 'c'], dtype=object)

In [22]: 'a' in s.unique()
Out[22]: True

or a python set:

In [23]: set(s)
Out[23]: {'a', 'b', 'c'}

In [24]: 'a' in set(s)
Out[24]: True

As pointed out by @DSM, it may be more efficient (especially if you're just doing this for one value) to just use in directly on the values:

In [31]: s.values
Out[31]: array(['a', 'b', 'c'], dtype=object)

In [32]: 'a' in s.values
Out[32]: True

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

Boxplot in R showing the mean

With ggplot2:

p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)

How to check if a file contains a specific string using Bash

Shortest (correct) version:

grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"

can be also written as

grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"

but you dont need to explicitly test it in this case, so the same with:

grep -q "something" file && echo "yes" || echo "no"

Stop node.js program from command line

For MacOS

  1. Open terminal
  2. Run the below code and hit enter

     sudo kill $(sudo lsof -t -i:4200)
    

How to fix the "508 Resource Limit is reached" error in WordPress?

On my blog, the reason of this error is a plugin named Broken Link checker. This plugin has high resource usage from hosting, resulting in this error.

Check if a plugin on your installation is behaving similarly like this.

Table overflowing outside of div

At first I used James Lawruk's method. This however changed all the widths of the td's.

The solution for me was to use white-space: normal on the columns (which was set to white-space: nowrap). This way the text will always break. Using word-wrap: break-word will ensure that everything will break when needed, even halfway through a word.

The CSS will look like this then:

td, th {
    white-space: normal; /* Only needed when it's set differntly somewhere else */
    word-wrap: break-word;
}

This might not always be the desirable solution, as word-wrap: break-word might make your words in the table illegible. It will however keep your table the right width.

Circle-Rectangle collision detection (intersection)

The simplest solution I've come up with is pretty straightforward.

It works by finding the point in the rectangle closest to the circle, then comparing the distance.

You can do all of this with a few operations, and even avoid the sqrt function.

public boolean intersects(float cx, float cy, float radius, float left, float top, float right, float bottom)
{
   float closestX = (cx < left ? left : (cx > right ? right : cx));
   float closestY = (cy < top ? top : (cy > bottom ? bottom : cy));
   float dx = closestX - cx;
   float dy = closestY - cy;

   return ( dx * dx + dy * dy ) <= radius * radius;
}

And that's it! The above solution assumes an origin in the upper left of the world with the x-axis pointing down.

If you want a solution to handling collisions between a moving circle and rectangle, it's far more complicated and covered in another answer of mine.

Convert a bitmap into a byte array

There are a couple ways.

ImageConverter

public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

This one is convenient because it doesn't require a lot of code.

Memory Stream

public static byte[] ImageToByte2(Image img)
{
    using (var stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        return stream.ToArray();
    }
}

This one is equivalent to what you are doing, except the file is saved to memory instead of to disk. Although more code you have the option of ImageFormat and it can be easily modified between saving to memory or disk.

Source: http://www.vcskicks.com/image-to-byte.php

Check array position for null/empty

There is no bound checking in array in C programming. If you declare array as

int arr[50];

Then you can even write as

arr[51] = 10;

The compiler would not throw an error. Hope this answers your question.

Creating JSON on the fly with JObject

There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.

In these cases you can do:

using Newtonsoft.Json.Linq;

JObject jsonObject =
     new JObject(
             new JProperty("Date", DateTime.Now),
             new JProperty("Album", "Me Against The World"),
             new JProperty("Year", "James 2Pac-King's blog."),
             new JProperty("Artist", "2Pac")
         )

More documentation here: http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm

How to read files from resources folder in Scala?

For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

How to unstage large number of files without deleting the content

I'm afraid that the first of those command lines unconditionally deleted from the working copy all the files that are in git's staging area. The second one unstaged all the files that were tracked but have now been deleted. Unfortunately this means that you will have lost any uncommitted modifications to those files.

If you want to get your working copy and index back to how they were at the last commit, you can (carefully) use the following command:

git reset --hard

I say "carefully" since git reset --hard will obliterate uncommitted changes in your working copy and index. However, in this situation it sounds as if you just want to go back to the state at your last commit, and the uncommitted changes have been lost anyway.

Update: it sounds from your comments on Amber's answer that you haven't yet created any commits (since HEAD cannot be resolved), so this won't help, I'm afraid.

As for how those pipes work: git ls-files -z and git diff --name-only --diff-filter=D -z both output a list of file names separated with the byte 0. (This is useful, since, unlike newlines, 0 bytes are guaranteed not to occur in filenames on Unix-like systems.) The program xargs essentially builds command lines from its standard input, by default by taking lines from standard input and adding them to the end of the command line. The -0 option says to expect standard input to by separated by 0 bytes. xargs may invoke the command several times to use up all the parameters from standard input, making sure that the command line never becomes too long.

As a simple example, if you have a file called test.txt, with the following contents:

hello
goodbye
hello again

... then the command xargs echo whatever < test.txt will invoke the command:

echo whatever hello goodbye hello again

Attach the Source in Eclipse of a jar

Simply import the package of the required source class in your code from jar.

You can find jar's sub packages in

Eclipse -- YourProject --> Referenced libraries --> yourJars --> Packages --> Clases

Like-- I was troubling with the mysql connector jar issue "the source attachment does not contain the source" by giving the path of source folder it display this statement

The source attachment does not contain the source for the file StatementImpl.class

Then I just import the package of mysql connector jar which contain the required class:

import com.mysql.jdbc.*;

Then program is working fine.

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

How do I convert a Python 3 byte-string variable into a regular string?

Call decode() on a bytes instance to get the text which it encodes.

str = bytes.decode()

How to print star pattern in JavaScript in a very simple manner?

You can try this

 var x, y, space = "",
    star = "",
    n = 4,
    m = n - 1;
for (x = 1; x <= n; x++) {
    for (y = m; y >= 1; y--) {
        space = space + (" ");
    }
    m--;
    for (let k = 1; k <= x * 2 - 1; k++) {
        star = star + "*"
    }
    console.log(space + star)
    space = '';
    star = "";
}

Implementing a HashMap in C

The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:

  • Separate chaining: one with an array of buckets (linked lists)
  • Open addressing: a single array allocated with extra space so index collisions may be resolved by placing the entry in an adjacent slot.

Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.

Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.

Some key performance metrics to evaluate when creating a hashmap would include:

  • Maximum load factor
  • Average collision count on insertion
  • Distribution of collisions: uneven distribution (clustering) could indicate a poor hash function.
  • Relative time for various operations: put, get, remove of existing and non-existing entries.

Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.

https://github.com/DavidLeeds/hashmap

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Tomcat is not running even though JAVA_HOME path is correct

Also ensure that you have the correct version of Tomcat for the CPU type. I had installed a 64bit tomcat on a 32bit O/S but it was giving me the JAVA_HOME exception when that wasn't the case at all.

How to set shape's opacity?

use this code below as progress.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#ff9d9e9d"
                    android:centerColor="#ff5a5d5a"
                    android:centerY="0.75"
                    android:endColor="#ff747674"
                    android:angle="270"
            />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="#00000000" />
            </shape>
        </clip>
    </item>

</layer-list>

where:

  • "progress" is current progress before the thumb and "secondaryProgress" is the progress after thumb.
  • color="#00000000" is a perfect transparency
  • NOTE: the file above is from default android res and is for 2.3.7, it is available on android sources at: frameworks/base/core/res/res/drawable/progress_horizontal.xml. For newer versions you must find the default drawable file for the seekbar corresponding to your android version.

after that use it in the layout containing the xml:

<SeekBar
    android:id="@+id/myseekbar"
    ...
    android:progressDrawable="@drawable/progress"
    />

you can also customize the thumb by using a custom icon seek_thumb.png:

android:thumb="@drawable/seek_thumb"

Difference between @click and v-on:click Vuejs

There is no difference between the two, one is just a shorthand for the second.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>

Source: official documentation.

Referencing another schema in Mongoose

It sounds like the populate method is what your looking for. First make small change to your post schema:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Then, when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

Get last n lines of a file, similar to tail

Posting an answer at the behest of commenters on my answer to a similar question where the same technique was used to mutate the last line of a file, not just get it.

For a file of significant size, mmap is the best way to do this. To improve on the existing mmap answer, this version is portable between Windows and Linux, and should run faster (though it won't work without some modifications on 32 bit Python with files in the GB range, see the other answer for hints on handling this, and for modifying to work on Python 2).

import io  # Gets consistent version of open for both Py2.7 and Py3.x
import itertools
import mmap

def skip_back_lines(mm, numlines, startidx):
    '''Factored out to simplify handling of n and offset'''
    for _ in itertools.repeat(None, numlines):
        startidx = mm.rfind(b'\n', 0, startidx)
        if startidx < 0:
            break
    return startidx

def tail(f, n, offset=0):
    # Reopen file in binary mode
    with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:
        # len(mm) - 1 handles files ending w/newline by getting the prior line
        startofline = skip_back_lines(mm, offset, len(mm) - 1)
        if startofline < 0:
            return []  # Offset lines consumed whole file, nothing to return
            # If using a generator function (yield-ing, see below),
            # this should be a plain return, no empty list

        endoflines = startofline + 1  # Slice end to omit offset lines

        # Find start of lines to capture (add 1 to move from newline to beginning of following line)
        startofline = skip_back_lines(mm, n, startofline) + 1

        # Passing True to splitlines makes it return the list of lines without
        # removing the trailing newline (if any), so list mimics f.readlines()
        return mm[startofline:endoflines].splitlines(True)
        # If Windows style \r\n newlines need to be normalized to \n, and input
        # is ASCII compatible, can normalize newlines with:
        # return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\n').splitlines(True)

This assumes the number of lines tailed is small enough you can safely read them all into memory at once; you could also make this a generator function and manually read a line at a time by replacing the final line with:

        mm.seek(startofline)
        # Call mm.readline n times, or until EOF, whichever comes first
        # Python 3.2 and earlier:
        for line in itertools.islice(iter(mm.readline, b''), n):
            yield line

        # 3.3+:
        yield from itertools.islice(iter(mm.readline, b''), n)

Lastly, this read in binary mode (necessary to use mmap) so it gives str lines (Py2) and bytes lines (Py3); if you want unicode (Py2) or str (Py3), the iterative approach could be tweaked to decode for you and/or fix newlines:

        lines = itertools.islice(iter(mm.readline, b''), n)
        if f.encoding:  # Decode if the passed file was opened with a specific encoding
            lines = (line.decode(f.encoding) for line in lines)
        if 'b' not in f.mode:  # Fix line breaks if passed file opened in text mode
            lines = (line.replace(os.linesep, '\n') for line in lines)
        # Python 3.2 and earlier:
        for line in lines:
            yield line
        # 3.3+:
        yield from lines

Note: I typed this all up on a machine where I lack access to Python to test. Please let me know if I typoed anything; this was similar enough to my other answer that I think it should work, but the tweaks (e.g. handling an offset) could lead to subtle errors. Please let me know in the comments if there are any mistakes.

ab load testing

Please walk me through the commands I should run to figure this out.

The simplest test you can do is to perform 1000 requests, 10 at a time (which approximately simulates 10 concurrent users getting 100 pages each - over the length of the test).

ab -n 1000 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://www.example.com/

-n 1000 is the number of requests to make.

-c 10 tells AB to do 10 requests at a time, instead of 1 request at a time, to better simulate concurrent visitors (vs. sequential visitors).

-k sends the KeepAlive header, which asks the web server to not shut down the connection after each request is done, but to instead keep reusing it.

I'm also sending the extra header Accept-Encoding: gzip, deflate because mod_deflate is almost always used to compress the text/html output 25%-75% - the effects of which should not be dismissed due to it's impact on the overall performance of the web server (i.e., can transfer 2x the data in the same amount of time, etc).

Results:

Benchmarking www.example.com (be patient)
Completed 100 requests
...
Finished 1000 requests


Server Software:        Apache/2.4.10
Server Hostname:        www.example.com
Server Port:            80

Document Path:          /
Document Length:        428 bytes

Concurrency Level:      10
Time taken for tests:   1.420 seconds
Complete requests:      1000
Failed requests:        0
Keep-Alive requests:    995
Total transferred:      723778 bytes
HTML transferred:       428000 bytes
Requests per second:    704.23 [#/sec] (mean)
Time per request:       14.200 [ms] (mean)
Time per request:       1.420 [ms] (mean, across all concurrent requests)
Transfer rate:          497.76 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       1
Processing:     5   14   7.5     12      77
Waiting:        5   14   7.5     12      77
Total:          5   14   7.5     12      77

Percentage of the requests served within a certain time (ms)
  50%     12
  66%     14
  75%     15
  80%     16
  90%     24
  95%     29
  98%     36
  99%     41
 100%     77 (longest request)

For the simplest interpretation, ignore everything BUT this line:

Requests per second:    704.23 [#/sec] (mean)

Multiply that by 60, and you have your requests per minute.

To get real world results, you'll want to test Wordpress instead of some static HTML or index.php file because you need to know how everything performs together: including complex PHP code, and multiple MySQL queries...

For example here is the results of testing a fresh install of Wordpress on the same system and WAMP environment (I'm using WampDeveloper, but there are also Xampp, WampServer, and others)...

Requests per second:    18.68 [#/sec] (mean)

That's 37x slower now!

After the load test, there are a number of things you can do to improve the overall performance (Requests Per Second), and also make the web server more stable under greater load (e.g., increasing the -n and the -c tends to crash Apache), that you can read about here:

Load Testing Apache with AB (Apache Bench)

How do I reference the input of an HTML <textarea> control in codebehind?

You need to use runat="server" like this:

<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>

You can use the runat=server attribute with any standard HTML element, and later use it from codebehind.

Help with packages in java - import does not work

Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ... Follow : Right Click My Computer>Properties>Advanced>Environment Variables

How do I set response headers in Flask?

Use make_response of Flask something like

@app.route("/")
def home():
    resp = make_response("hello") #here you could use make_response(render_template(...)) too
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

From flask docs,

flask.make_response(*args)

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

Replace transparency in PNG images with white background

The only one that worked for me was a mix of all the answers:

convert in.png -background white -alpha remove -flatten -alpha off out.png

HTML Image not displaying, while the src url works

The simple solution is:

1.keep the image file and HTML file in the same folder.

2.code: <img src="Desert.png">// your image name.

3.keep the folder in D drive.

Keeping the folder on the desktop(which is c drive) you can face the issue of permission.

How to create an empty array in Swift?

Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

How to center div vertically inside of absolutely positioned parent div

First of all note that vertical-align is only applicable to table cells and inline-level elements.

There are couple of ways to achieve vertical alignments which may or may not meet your needs. However I'll show you two methods from my favorites:

1. Using transform and top

_x000D_
_x000D_
.valign {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* vendor prefixes omitted due to brevity */
}
_x000D_
<div style="position: absolute; left: 50px; top: 50px;">
    <div style="text-align: left; position: absolute;height: 56px;background-color: pink;">
        <div class="valign" style="background-color: lightblue;">test</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

The key point is that a percentage value on top is relative to the height of the containing block; While a percentage value on transforms is relative to the size of the box itself (the bounding box).

If you experience font rendering issues (blurry font), the fix is to add perspective(1px) to the transform declaration so it becomes:

transform: perspective(1px) translateY(-50%);

It's worth noting that CSS transform is supported in IE9+.

2. Using inline-block (pseudo-)elements

In this method, we have two sibling inline-block elements which are aligned vertically at the middle by vertical-align: middle declaration.

One of them has a height of 100% of its parent and the other is our desired element whose we wanted to align it at the middle.

_x000D_
_x000D_
.parent {
    text-align: left;
    position: absolute;
    height: 56px;
    background-color: pink;
    white-space: nowrap;
    font-size: 0; /* remove the gap between inline level elements */
}

.dummy-child { height: 100%; }

.valign {
    font-size: 16px; /* re-set the font-size */
}

.dummy-child, .valign {
    display: inline-block;
    vertical-align: middle;
}
_x000D_
<div style="position: absolute; left: 50px; top: 50px;">
    <div class="parent">
        <div class="dummy-child"></div>
        <div class="valign" style="background-color: lightblue;">test</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

Finally, we should use one of the available methods to remove the gap between inline-level elements.

Directory-tree listing in Python

Try this:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)

How to find a whole word in a String in java

A much simpler way to do this is to use split():

String match = "123woods";
String text = "I will come and meet you at the 123woods";

String[] sentence = text.split();
for(String word: sentence)
{
    if(word.equals(match))
        return true;
}
return false;

This is a simpler, less elegant way to do the same thing without using tokens, etc.

Postgres: check if array field contains value?

Instead of IN we can use ANY with arrays casted to enum array, for example:

create type example_enum as enum (
  'ENUM1', 'ENUM2'
);

create table example_table (
  id integer,
  enum_field example_enum
);

select 
  * 
from 
  example_table t
where
  t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);

Or we can still use 'IN' clause, but first, we should 'unnest' it:

select 
  * 
from 
  example_table t
where
  t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));

Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0

How to count digits, letters, spaces for a string in Python?

You shouldn't be setting x = []. That is setting an empty list to your inputted parameter. Furthermore, use python's for i in x syntax as follows:

for i in x:
    if i.isalpha():
        letters+=1
    elif i.isnumeric():
        digit+=1
    elif i.isspace():
        space+=1
    else:
        other+=1

How to differ sessions in browser-tabs?

You have to realize that server-side sessions are an artificial add-on to HTTP. Since HTTP is stateless, the server needs to somehow recognize that a request belongs to a particular user it knows and has a session for. There are 2 ways to do this:

  • Cookies. The cleaner and more popular method, but it means that all browser tabs and windows by one user share the session - IMO this is in fact desirable, and I would be very annoyed at a site that made me login for each new tab, since I use tabs very intensively
  • URL rewriting. Any URL on the site has a session ID appended to it. This is more work (you have to do something everywhere you have a site-internal link), but makes it possible to have separate sessions in different tabs, though tabs opened through link will still share the session. It also means the user always has to log in when he comes to your site.

What are you trying to do anyway? Why would you want tabs to have separate sessions? Maybe there's a way to achieve your goal without using sessions at all?

Edit: For testing, other solutions can be found (such as running several browser instances on separate VMs). If one user needs to act in different roles at the same time, then the "role" concept should be handled in the app so that one login can have several roles. You'll have to decide whether this, using URL rewriting, or just living with the current situation is more acceptable, because it's simply not possible to handle browser tabs separately with cookie-based sessions.

How to return a value from try, catch, and finally?

It is because you are in a try statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally block, that way it will for sure be returned.

Make sure that you initialize sum outside the try/catch/finally so that it is in scope.

HashMap - getting First Key value

Java 8 way of doing,

String firstKey = map.keySet().stream().findFirst().get();

Efficiency of Java "Double Brace Initialization"?

Double-brace initialization is an unnecessary hack that can introduce memory leaks and other issues

There's no legitimate reason to use this "trick". Guava provides nice immutable collections that include both static factories and builders, allowing you to populate your collection where it's declared in a clean, readable, and safe syntax.

The example in the question becomes:

Set<String> flavors = ImmutableSet.of(
    "vanilla", "strawberry", "chocolate", "butter pecan");

Not only is this shorter and easier to read, but it avoids the numerous issues with the double-braced pattern described in other answers. Sure, it performs similarly to a directly-constructed HashMap, but it's dangerous and error-prone, and there are better options.

Any time you find yourself considering double-braced initialization you should re-examine your APIs or introduce new ones to properly address the issue, rather than take advantage of syntactic tricks.

Error-Prone now flags this anti-pattern.

How to send image to PHP file using Ajax?

Here is code that will upload multiple images at once, into a specific folder!

The HTML:

<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php">
<input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">

</ul>

The PHP:

<?php
$errors = $_FILES["images"]["error"];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
    $name = $_FILES["images"]["name"][$key];
    //$ext = pathinfo($name, PATHINFO_EXTENSION);
    $name = explode("_", $name);
    $imagename='';
    foreach($name as $letter){
        $imagename .= $letter;
    }

    move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" .  $imagename);

}
}


echo "<h2>Successfully Uploaded Images</h2>";

And finally, the JavaSCript/Ajax:

(function () {
var input = document.getElementById("images"), 
    formdata = false;

function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Uploading . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "submit_image.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("response").innerHTML = res;
            }
        });
    }
}, false);
}());

Hope this helps

Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

try
{
   ...
}
catch (Exception e)
{
   if (e instanceof FooException)
     throw e;
}

Change an image with onclick()

The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS.

I would name the images starting with bw_ and clr_ and just use JS to swap between them.

example:

$("#images").find('img').bind("click", function() {
  var src = $(this).attr("src"), 
      state = (src.indexOf("bw_") === 0) ? 'bw' : 'clr';

  (state === 'bw') ? src = src.replace('bw_','clr_') : src = src.replace('clr_','bw_');  

  $(this).attr("src", src);

});

link to fiddle: http://jsfiddle.net/felcom/J2ucD/

Excel VBA Run Time Error '424' object required

You have two options,

-If you want the value:

Dim MyValue as Variant ' or string/date/long/...
MyValue = ThisWorkbook.Sheets(1).Range("A1").Value

-if you want the cell object:

Dim oCell as Range  ' or object (but then you'll miss out on intellisense), and both can also contain more than one cell.
Set oCell = ThisWorkbook.Sheets(1).Range("A1")

Why does using an Underscore character in a LIKE filter give me all the results?

The underscore is the wildcard in a LIKE query for one arbitrary character.

Hence LIKE %_% means "give me all records with at least one arbitrary character in this column".

You have to escape the wildcard character, in sql-server with [] around:

SELECT m.* 
FROM Manager m 
WHERE m.managerid    LIKE  '[_]%'
AND   m.managername  LIKE '%[_]%'

See: LIKE (Transact-SQL)

Demo

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Another option to check your xpath is to use selenium IDE.

  1. Install Firefox Selenium IDE
  2. Open your application in FireFox and open IDE
  3. In IDE, on a new line, paste your xpath to the target and click Find. The corresponding element would be highlighted in your application

Selenium IDE

Finding moving average from data points in Python

A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.

import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)

I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.

Can I get JSON to load into an OrderedDict?

Simple version for Python 2.7+

my_ordered_dict = json.loads(json_str, object_pairs_hook=collections.OrderedDict)

Or for Python 2.4 to 2.6

import simplejson as json
import ordereddict

my_ordered_dict = json.loads(json_str, object_pairs_hook=ordereddict.OrderedDict)

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

Google Maps v2 - set both my location and zoom in

gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(9.491327, 76.571404), 10, 30, 0)));

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

For python 3, the default encoding would be "utf-8". Following steps are suggested in the base documentation:https://docs.python.org/2/library/csv.html#csv-examples in case of any problem

  1. Create a function

    def utf_8_encoder(unicode_csv_data):
        for line in unicode_csv_data:
            yield line.encode('utf-8')
    
  2. Then use the function inside the reader, for e.g.

    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data))
    

PowerShell script to return versions of .NET Framework on a machine?

[environment]::Version

Gives you an instance of Version for the CLR the current copy of PSH is using (as documented here).

Where does forever store console.log output?

By default forever places all of the files it needs into /$HOME/.forever. If you would like to change that location just set the FOREVER_ROOT environment variable when you are running forever:

FOREVER_ROOT=/etc/forever forever start index.js

Pandas count(distinct) equivalent

Here is another method, much simple, lets say your dataframe name is daat and column name is YEARMONTH

daat.YEARMONTH.value_counts()

grep using a character vector with multiple patterns

Take away the spaces. So do:

matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))

Waiting until the task finishes

In Swift 3, there is no need for completion handler when DispatchQueue finishes one task. Furthermore you can achieve your goal in different ways

One way is this:

    var a: Int?

    let queue = DispatchQueue(label: "com.app.queue")
    queue.sync {

        for  i in 0..<10 {

            print("??" , i)
            a = i
        }
    }

    print("After Queue \(a)")

It will wait until the loop finishes but in this case your main thread will block.

You can also do the same thing like this:

    let myGroup = DispatchGroup()
    myGroup.enter()
    //// Do your task

    myGroup.leave() //// When your task completes
     myGroup.notify(queue: DispatchQueue.main) {

        ////// do your remaining work
    }

One last thing: If you want to use completionHandler when your task completes using DispatchQueue, you can use DispatchWorkItem.

Here is an example how to use DispatchWorkItem:

let workItem = DispatchWorkItem {
    // Do something
}

let queue = DispatchQueue.global()
queue.async {
    workItem.perform()
}
workItem.notify(queue: DispatchQueue.main) {
    // Here you can notify you Main thread
}

How do I make Git ignore file mode (chmod) changes?

If you want to set this option for all of your repos, use the --global option.

git config --global core.filemode false

If this does not work you are probably using a newer version of git so try the --add option.

git config --add --global core.filemode false

If you run it without the --global option and your working directory is not a repo, you'll get

error: could not lock config file .git/config: No such file or directory

MySQL 'Order By' - sorting alphanumeric correctly

Instead of trying to write some function and slow down the SELECT query, I thought of another way of doing this...

Create an extra field in your database that holds the result from the following Class and when you insert a new row, run the field value that will be naturally sorted through this class and save its result in the extra field. Then instead of sorting by your original field, sort by the extra field.

String nsFieldVal = new NaturalSortString(getFieldValue(), 4).toString()

The above means:
- Create a NaturalSortString for the String returned from getFieldValue()
- Allow up to 4 bytes to store each character or number (4 bytes = ffff = 65535)

| field(32)  |  nsfield(161)                            |   
  a1            300610001

String sortString = new NaturalSortString(getString(), 4).toString()

import StringUtils;

/**
 * Creates a string that allows natural sorting in a SQL database
 * eg, 0 1 1a 2 3 3a 10 100 a a1 a1a1 b
 */
public class NaturalSortString {

    private String inStr;
    private int byteSize;
    private StringBuilder out = new StringBuilder();

    /**
     * A byte stores the hex value (0 to f) of a letter or number.
     * Since a letter is two bytes, the minimum byteSize is 2.
     *
     * 2 bytes = 00 - ff  (max number is 255)
     * 3 bytes = 000 - fff (max number is 4095)
     * 4 bytes = 0000 - ffff (max number is 65535)
     *
     * For example:
     * dog123 = 64,6F,67,7B and thus byteSize >= 2.      
     * dog280 = 64,6F,67,118 and thus byteSize >= 3.
     *
     * For example:
     * The String, "There are 1000000 spots on a dalmatian" would require a byteSize that can 
     * store the number '1000000' which in hex is 'f4240' and thus the byteSize must be at least 5
     *
     * The dbColumn size to store the NaturalSortString is calculated as:
     * > originalStringColumnSize x byteSize + 1
     * The extra '1' is a marker for String type - Letter, Number, Symbol
     * Thus, if the originalStringColumn is varchar(32) and the byteSize is 5:
     * > NaturalSortStringColumnSize = 32 x 5 + 1 = varchar(161)
     *
     * The byteSize must be the same for all NaturalSortStrings created in the same table.
     * If you need to change the byteSize (for instance, to accommodate larger numbers), you will
     * need to recalculate the NaturalSortString for each existing row using the new byteSize.
     *
     * @param str        String to create a natural sort string from
     * @param byteSize   Per character storage byte size (minimum 2)
     * @throws Exception See the error description thrown
     */
    public NaturalSortString(String str, int byteSize) throws Exception {
        if (str == null || str.isEmpty()) return;
        this.inStr = str;
        this.byteSize = Math.max(2, byteSize);  // minimum of 2 bytes to hold a character
        setStringType();
        iterateString();
    }

    private void setStringType() {
        char firstchar = inStr.toLowerCase().subSequence(0, 1).charAt(0);
        if (Character.isLetter(firstchar))     // letters third
            out.append(3);
        else if (Character.isDigit(firstchar)) // numbers second
            out.append(2);
        else                                   // non-alphanumeric first
            out.append(1);
    }

    private void iterateString() throws Exception {
        StringBuilder n = new StringBuilder();
        for (char c : inStr.toLowerCase().toCharArray()) { // lowercase for CASE INSENSITIVE sorting
            if (Character.isDigit(c)) {
                // group numbers
                n.append(c);
                continue;
            }
            if (n.length() > 0) {
                addInteger(n.toString());
                n = new StringBuilder();
            }
            addCharacter(c);
        }
        if (n.length() > 0) {
            addInteger(n.toString());
        }
    }

    private void addInteger(String s) throws Exception {
        int i = Integer.parseInt(s);
        if (i >= (Math.pow(16, byteSize)))
            throw new Exception("naturalsort_bytesize_exceeded");
        out.append(StringUtils.padLeft(Integer.toHexString(i), byteSize));
    }

    private void addCharacter(char c) {
        //TODO: Add rest of accented characters
        if (c >= 224 && c <= 229) // set accented a to a
            c = 'a';
        else if (c >= 232 && c <= 235) // set accented e to e
            c = 'e';
        else if (c >= 236 && c <= 239) // set accented i to i
            c = 'i';
        else if (c >= 242 && c <= 246) // set accented o to o
            c = 'o';
        else if (c >= 249 && c <= 252) // set accented u to u
            c = 'u';
        else if (c >= 253 && c <= 255) // set accented y to y
            c = 'y';

        out.append(StringUtils.padLeft(Integer.toHexString(c), byteSize));
    }

    @Override
    public String toString() {
        return out.toString();
    }
}

For completeness, below is the StringUtils.padLeft method:

public static String padLeft(String s, int n) {
    if (n - s.length() == 0) return s;
    return String.format("%0" + (n - s.length()) + "d%s", 0, s);
}

The result should come out like the following

-1
-a
0
1
1.0
1.01
1.1.1
1a
1b
9
10
10a
10ab
11
12
12abcd
100
a
a1a1
a1a2
a-1
a-2
áviacion
b
c1
c2
c12
c100
d
d1.1.1
e

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

Java - No enclosing instance of type Foo is accessible

Declare the INNER class Thing as a static and it will work with no issues.

I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:

1- To declare the inner class Dog as static. Or

2- To move the inner class Dog to a new class by itself.

Here is the Example:

public class ReturnDemo {

public static void main(String[] args) {
    
    int z = ReturnDemo.calculate(10, 12);
    System.out.println("z = " + z);
    
    ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
    System.out.println( dog.getDog());
}


public static int calculate (int x, int y) {
    return x + y;
}

public void print( ) {
    System.out.println("void method");
    return;
}

public String getString() {
    return "Retrun String type value";
}


static class Dog {
    
private String breed;
private String name;

public Dog(String breed, String name) {
    super();
    this.breed = breed;
    this.name = name;
}

public Dog getDog() {
    // return Dog type;
    return this;
    
}

public String toString() {
    return "breed" + breed.concat("name: " + name);
}
}

}

What are the differences in die() and exit() in PHP?

DIFFERENCE IN ORIGIN

The difference between die() and exit() in PHP is their origin.


FUNCTIONALLY EQUIVALENT

die() and exit() are equivalent functions.

PHP Manual

PHP Manual for die:

This language construct is equivalent to exit().

PHP Manual for exit:

Note: This language construct is equivalent to die().

PHP Manual for List of Function Aliases:

die is an alias for master function exit()


DIFFERENT IN OTHER LANGUAGES

die() and exit() are different in other languages but in PHP they are identical.

From Yet another PHP rant:

...As a C and Perl coder, I was ready to answer, "Why, exit() just bails off the program with a numeric exit status, while die() prints out the error message to stderr and exits with EXIT_FAILURE status." But then I remembered we're in messy-syntax-land of PHP.

In PHP, exit() and die() are identical.

The designers obviously thought "Hmm, let's borrow exit() from C. And Perl folks probably will like it if we take die() as is from Perl too. Oops! We have two exit functions now! Let's make it so that they both can take a string or integer as an argument and make them identical!"

The end result is that this didn't really make things any "easier", just more confusing. C and Perl coders will continue to use exit() to toss an integer exit value only, and die() to toss an error message and exit with a failure. Newbies and PHP-as-a-first-language people will probably wonder "umm, two exit functions, which one should I use?" The manual doesn't explain why there's exit() and die().

In general, PHP has a lot of weird redundancy like this - it tries to be friendly to people who come from different language backgrounds, but while doing so, it creates confusing redundancy.

How to remove any URL within a string in Python

The following regular expression in Python works well for detecting URL(s) in the text:

source_text = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6    '''

import re
url_reg  = r'[a-z]*[:.]+\S+'
result   = re.sub(url_reg, '', source_text)
print(result)

Output:

text1
text2

text3
text4

text5
text6

Creating for loop until list.length

I'd try to search for the solution by google and the string Python for statement, it is as simple as that. The first link says everything. (A great forum, really, but its usage seems to look sometimes like the usage of the Microsoft understanding of all their GUI products' benefits: windows inside, idiots outside.)

How to use radio on change event?

$(document).ready(function () {
    $('#allot').click(function () {
        if ($(this).is(':checked')) {
            alert("Allot Thai Gayo Bhai");
        }
    });

    $('#transfer').click(function () {
        if ($(this).is(':checked')) {
            alert("Transfer Thai Gayo");
        }
    });
});

JS Fiddle

Simple PHP Pagination script

This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.

try {

    // Find out how many items are in the table
    $total = $dbh->query('
        SELECT
            COUNT(*)
        FROM
            table
    ')->fetchColumn();

    // How many items to list per page
    $limit = 20;

    // How many pages will there be
    $pages = ceil($total / $limit);

    // What page are we currently on?
    $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
        'options' => array(
            'default'   => 1,
            'min_range' => 1,
        ),
    )));

    // Calculate the offset for the query
    $offset = ($page - 1)  * $limit;

    // Some information to display to the user
    $start = $offset + 1;
    $end = min(($offset + $limit), $total);

    // The "back" link
    $prevlink = ($page > 1) ? '<a href="?page=1" title="First page">&laquo;</a> <a href="?page=' . ($page - 1) . '" title="Previous page">&lsaquo;</a>' : '<span class="disabled">&laquo;</span> <span class="disabled">&lsaquo;</span>';

    // The "forward" link
    $nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">&rsaquo;</a> <a href="?page=' . $pages . '" title="Last page">&raquo;</a>' : '<span class="disabled">&rsaquo;</span> <span class="disabled">&raquo;</span>';

    // Display the paging information
    echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';

    // Prepare the paged query
    $stmt = $dbh->prepare('
        SELECT
            *
        FROM
            table
        ORDER BY
            name
        LIMIT
            :limit
        OFFSET
            :offset
    ');

    // Bind the query params
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    // Do we have any results?
    if ($stmt->rowCount() > 0) {
        // Define how we want to fetch the results
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $iterator = new IteratorIterator($stmt);

        // Display the results
        foreach ($iterator as $row) {
            echo '<p>', $row['name'], '</p>';
        }

    } else {
        echo '<p>No results could be displayed.</p>';
    }

} catch (Exception $e) {
    echo '<p>', $e->getMessage(), '</p>';
}

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

Hiding an Excel worksheet with VBA

I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.

So, for hiding the sheet:

Sub try()
    Worksheets("Sheet1").Visible = xlSheetHidden
End Sub

There are other methods also if you want to learn all Methods Click here

How to discover number of *logical* cores on Mac OS X?

This can be done in a more portable way:

$ nproc --all
32

Compatible with macOS and Linux.

How to set commands output as a variable in a batch file

Some notes and some tricks.

The 'official' way to assign result to a variable is with FOR /F though in the other answers is shown how a temporary file can be used also.

For command processing FOR command has two forms depending if the usebackq option is used. In the all examples below the whole output is used without splitting it.

FOR /f "tokens=* delims=" %%A in ('whoami') do @set "I-Am=%%A"
FOR /f "usebackq tokens=* delims=" %%A in (`whoami`) do @set "I-Am=%%A"

and if used directly in the console:

FOR /f "tokens=* delims=" %A in ('whoami') do set "I-Am=%A"
FOR /f "usebackq tokens=* delims=" %A in (`whoami`) do set "I-Am=%A"

%%A is a temporary variable available only on the FOR command context and is called token.The two forms can be useful in case when you are dealing with arguments containing specific quotes. It is especially useful with REPL interfaces of other languages or WMIC. Though in both cases the expression can be put in double quotes and it still be processed.

Here's an example with python (it is possible to transition the expression in the brackets on a separate line which is used for easier reading):

@echo off

for /f "tokens=* delims=" %%a in (
  '"python -c ""print("""Message from python""")"""'
) do (
    echo processed message from python: "%%a"
)

To use an assigned variable in the same FOR block check also the DELAYED EXPANSION

And some tricks

To save yourself from writing all the arguments for the FOR command you can use MACRO for assigning the result to variable:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

the first argument to the macro is the command and the second the name of the variable we want to use and both are separated by , (comma). Though this is suitable only for straight forward scenarios.

If we want a similar macro for the console we can use DOSKEY

doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"
rem  -- example --
assign WHOAMI /LOGONID,my-id
echo %my-id%

DOSKEY does accept double quotes as enclosion for arguments so this also is useful for more simple scenarios.

FOR also works well with pipes which can be used for chaining commands (though it is not so good for assigning a variable.

hostname |for /f "tokens=* delims=" %%# in ('more') do @(ping %%#)

Which also can be beautified with macros:

@echo off
:: --- defining chain command macros ---
set "result-as-[arg]:=|for /f "tokens=* delims=" %%# in ('more') do @("
set "[arg]= %%#)"
:::  --------------------------  :::

::Example:
hostname %result-as-[arg]:% ping %[arg]%

And for completnes macros for the temp file approach (no doskey definition ,but it also can be easy done.If you have a SSD this wont be so slow):

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1"
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

For /f with another macro:

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

How to have a a razor action link open in a new tab?

@Html.ActionLink(
"Pay Now",
"Add",
"Payment",
new { @id = 1 },htmlAttributes:new { @class="btn btn-success",@target= "_blank" } )

jQuery Force set src attribute for iframe

While generating the links set the target to the iframes name property and you probably wont have to deal with jquery at all.

<a href="inventory.aspx" target="contentframe"  title="Title Inventory">
<iframe id="iframe1" name="contentframe"  ></iframe>

How to make a redirection on page load in JSF 1.x

Set the GET query parameters as managed properties in faces-config.xml so that you don't need to gather them manually:

<managed-bean>
    <managed-bean-name>forward</managed-bean-name>
    <managed-bean-class>com.example.ForwardBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>action</property-name>
        <value>#{param.action}</value>
    </managed-property>
    <managed-property>
        <property-name>actionParam</property-name>
        <value>#{param.actionParam}</value>
    </managed-property>
</managed-bean>

This way the request forward.jsf?action=outcome1&actionParam=123 will let JSF set the action and actionParam parameters as action and actionParam properties of the ForwardBean.

Create a small view forward.xhtml (so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase of the f:view:

<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
    <f:view beforePhase="#{forward.navigate}" />
</html>

The ForwardBean can look like this:

public class ForwardBean {
    private String action;
    private String actionParam;

    public void navigate(PhaseEvent event) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = action; // Do your thing?
        facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
    }

    // Add/generate the usual boilerplate.
}

The navigation-rule speaks for itself (note the <redirect /> entries which would do ExternalContext#redirect() instead of ExternalContext#dispatch() under the covers):

<navigation-rule>
    <navigation-case>
        <from-outcome>outcome1</from-outcome>
        <to-view-id>/outcome1.xhtml</to-view-id>
        <redirect />
    </navigation-case>
    <navigation-case>
        <from-outcome>outcome2</from-outcome>
        <to-view-id>/outcome2.xhtml</to-view-id>
        <redirect />
    </navigation-case>
</navigation-rule>

An alternative is to use forward.xhtml as

<!DOCTYPE html>
<html>#{forward}</html>

and update the navigate() method to be invoked on @PostConstruct (which will be invoked after bean's construction and all managed property setting):

@PostConstruct
public void navigate() {
    // ...
}    

It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString() (and hereby implicitly constructing the bean if not present yet).


Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam> and more robust way of handling the redirect/navigation by <f:event type="preRenderView">. See also among others:

Bootstrap 3 Horizontal and Vertical Divider

I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)

Fiddle: https://jsfiddle.net/tqmfpwhv/1/


css based on OP information, media query at end is for med & lg view.

.vr-all {
    padding:0px;
    border-right:1px solid #CC0000;
}
.vr-xs {
    padding:0px;
}
.vr-md {
    padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
    border-color: #CC0000;
    border-style: solid;
    border-bottom: 1px;
    margin:0px;
    padding:0px;
}
/* for medium and up */
@media(min-width:992px){
    .vr-xs {
        border-right:1px solid #CC0000;
    }
    }

html adjustments to OP provided code. Red border and Img links for example.

<div class="container">
  <div class="row">
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
            <h5>Rich Media Ad Production</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
            <h5>Web Design & Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
            <h5>Mobile Apps Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
            <h5>Creative Design</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for for all viewports -->
        <div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
            <h5>Web Analytics</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
            <h5>Search Engine Marketing</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>

        <!-- hr for only x-small/small viewports -->
        <div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>

        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
            <h5>Mobile Apps Development</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>
        <div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
            <h5>Quality Assurance</h5>
            <img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
        </div>


    </div>
</div>

.trim() in JavaScript not working in IE

It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim() instead (http://api.jquery.com/jQuery.trim/).

Custom alert and confirm box in jquery

jQuery UI has it's own elements, but jQuery alone hasn't.

http://jqueryui.com/dialog/

Working example:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


</body>
</html>

How to install OpenSSL in windows 10?

Necroposting, but might be useful for others.

There's always the official page: [OpenSSL.Wiki]: Binaries which contains useful URLs.

I also want to mention: [GitHub]: CristiFati/Prebuilt-Binaries - Prebuilt-Binaries/OpenSSL

  • v1.0.2u is built with OpenSSL-FIPS 2.0.16
  • Artefacts are .zips that should be unpacked in "C:\Program Files" (please take a look at the Readme.md file, and also at the one at the repository root)

Fitting a Normal distribution to 1D data

There is a much simpler way to do it using seaborn:

import seaborn as sns
from scipy.stats import norm

data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want

sns.distplot(data)
plt.show()

output:

enter image description here

for more information:seaborn.distplot

moment.js 24h format

HH used 24 hour format while hh used for 12 format

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

Declaring & Setting Variables in a Select Statement

The SET command is TSQL specific - here's the PLSQL equivalent to what you posted:

v_date1 DATE := TO_DATE('03-AUG-2010', 'DD-MON-YYYY');

SELECT u.visualid
  FROM USAGE u 
 WHERE u.usetime > v_date1;

There's also no need for prefixing variables with "@"; I tend to prefix variables with "v_" to distinguish between variables & columns/etc.

See this thread about the Oracle equivalent of NOLOCK...

How to disable an Android button?

You can't enable it or disable it in your XML (since your layout is set at runtime), but you can set if it's clickable at the launch of the activity with android:clickable.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').