Programs & Examples On #Datawindow

The PowerBuilder DataWindow control is a container for database originated data in a PowerBuilder application. It can display the data and optionally let the user modify it and send changes back to the database. In addition to the DataWindow control, the DataStore object provides a non-visual container for server applications and other situations where on-screen viewing is not necessary.

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

How do I view the SQLite database on an Android device?

step 1 Copy this class in your package

step 2 put the following code in your class which extends SQLiteOpenHelper.

 //-----------------for show databasae table----------------------------------------

public ArrayList<Cursor> getData(String Query)
{
    //get writable database
    SQLiteDatabase sqlDB =this.getWritableDatabase();
    String[] columns = new String[] { "mesage" };
    //an array list of cursor to save two cursors one has results from the query
    //other cursor stores error message if any errors are triggered
    ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
    MatrixCursor Cursor2= new MatrixCursor(columns);
    alc.add(null);
    alc.add (null);


    try{
        String maxQuery = Query ;
        //execute the query results will be save in Cursor c
        Cursor c = sqlDB.rawQuery(maxQuery, null);

        //add value to cursor2
        Cursor2.addRow(new Object[] { "Success" });

        alc.set(1,Cursor2);
        if (null != c && c.getCount() > 0)
        {
            alc.set(0,c);
            c.moveToFirst();
            return alc ;
        }
        return alc;
    }
    catch(SQLException sqlEx)
    {
        Log.d("printing exception", sqlEx.getMessage());
        //if any exceptions are triggered save the error message to cursor an return the arraylist
        Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
        alc.set(1,Cursor2);
        return alc;
    }
    catch(Exception ex)
    {
        Log.d("printing exception",ex.getMessage());
        //if any exceptions are triggered save the error message to cursor an return the arraylist
        Cursor2.addRow(new Object[] { ""+ex.getMessage() });
        alc.set(1,Cursor2);
        return alc;
    }
}

step 3 register in manifest

<activity
        android:name=".database.AndroidDatabaseManager"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"/>

step 4

Intent i = new Intent(this, AndroidDatabaseManager.class);
startActivity(i);

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

Another git process seems to be running in this repository

just for clarification, for those wondering why rm and del.

rm .git/index.lock - on a unix/linux system
del .git/index.lock - on a windows cmd prompt

you could add -f to force the operation that works.

How do I make a div full screen?

For fullscreen of browser rendering area there is a simple solution supported by all modern browsers.

div#placeholder {
    height: 100vh;
}

The only notable exception is the Android below 4.3 - but ofc only in the system browser/webview element (Chrome works ok).

Browser support chart: http://caniuse.com/viewport-units

For fullscreen of monitor please use HTML5 Fullscreen API

regex error - nothing to repeat

Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat is a bit confusing. I was trying to use r'?.*' as a pattern, and thought it was complaining for some strange reason about the *, but the problem is actually that ? is a way of saying "repeat zero or one times". So I needed to say r'\?.*'to match a literal ?

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

I have implemented in my app ,taken referece from the pskink.thanx a lot

package com.example.htmltagimg;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity implements ImageGetter {
private final static String TAG = "TestImageGetter";
private TextView mTv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String source = "this is a test of <b>ImageGetter</b> it contains " +
            "two images: <br/>" +
            "<img src=\"http://developer.android.com/assets/images/dac_logo.png\"><br/>and<br/>" +
            "<img src=\"http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg\">";
    String imgs="<p><img alt=\"\" src=\"http://images.visitcanberra.com.au/images/canberra_hero_image.jpg\" style=\"height:50px; width:100px\" />Test Article, Test Article, Test Article, Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,v</p>";
    String src="<p><img alt=\"\" src=\"http://stylonica.com/wp-content/uploads/2014/02/Beauty-of-nature-random-4884759-1280-800.jpg\" />Test Attractions Test Attractions Test Attractions Test Attractions</p>";
    String img="<p><img alt=\"\" src=\"/site_media/photos/gallery/75b3fb14-3be6-4d14-88fd-1b9d979e716f.jpg\" style=\"height:508px; width:640px\" />Test Article, Test Article, Test Article, Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,v</p>";
    Spanned spanned = Html.fromHtml(imgs, this, null);
    mTv = (TextView) findViewById(R.id.text);
    mTv.setText(spanned);
}

@Override
public Drawable getDrawable(String source) {
    LevelListDrawable d = new LevelListDrawable();
    Drawable empty = getResources().getDrawable(R.drawable.ic_launcher);
    d.addLevel(0, 0, empty);
    d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());

    new LoadImage().execute(source, d);

    return d;
}

class LoadImage extends AsyncTask<Object, Void, Bitmap> {

    private LevelListDrawable mDrawable;

    @Override
    protected Bitmap doInBackground(Object... params) {
        String source = (String) params[0];
        mDrawable = (LevelListDrawable) params[1];
        Log.d(TAG, "doInBackground " + source);
        try {
            InputStream is = new URL(source).openStream();
            return BitmapFactory.decodeStream(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        Log.d(TAG, "onPostExecute drawable " + mDrawable);
        Log.d(TAG, "onPostExecute bitmap " + bitmap);
        if (bitmap != null) {
            BitmapDrawable d = new BitmapDrawable(bitmap);
            mDrawable.addLevel(1, 1, d);
            mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
            mDrawable.setLevel(1);
            // i don't know yet a better way to refresh TextView
            // mTv.invalidate() doesn't work as expected
            CharSequence t = mTv.getText();
            mTv.setText(t);
        }
    }
}
}

As per below @rpgmaker comment i added this answer

yes you can do using ResolveInfo class

check your file is supported with already installed apps or not

using below code:

private boolean isSupportedFile(File file) throws PackageManager.NameNotFoundException {
    PackageManager pm = mContext.getPackageManager();
    java.io.File mFile = new java.io.File(file.getFileName());
    Uri data = Uri.fromFile(mFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(data, file.getMimeType());
    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    if (resolveInfos != null && resolveInfos.size() > 0) {
        Drawable icon = mContext.getPackageManager().getApplicationIcon(resolveInfos.get(0).activityInfo.packageName);
        Glide.with(mContext).load("").placeholder(icon).into(binding.fileAvatar);
        return true;
    } else {
        Glide.with(mContext).load("").placeholder(R.drawable.avatar_defaultworkspace).into(binding.fileAvatar);
        return false;
    }
}

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.

How to run Java program in terminal with external library JAR

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

Should I use @EJB or @Inject

It may also be usefull to understand the difference in term of Session Bean Identity when using @EJB and @Inject. According to the specifications the following code will always be true:

@EJB Cart cart1;
@EJB Cart cart2;
… if (cart1.equals(cart2)) { // this test must return true ...}

Using @Inject instead of @EJB there is not the same.

see also stateless session beans identity for further info

ElasticSearch: Unassigned Shards, how to fix?

The only thing that worked for me was changing the number_of_replicas (I had 2 replicas, so I changed it to 1 and then changed back to 2).

First:

PUT /myindex/_settings
{
    "index" : {
        "number_of_replicas" : 1
     }
}

Then:

PUT /myindex/_settings
{
    "index" : {
        "number_of_replicas" : 2
     }
}

(I Already asnwered it in this question)

C#, Looping through dataset and show each record from a dataset column

DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());

How to disable button in React.js

Using refs is not best practice because it reads the DOM directly, it's better to use React's state instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.

You can use setState together with an onChange event listener to render the component again every time the input field changes:

// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />

// Button is disabled when input state is empty.
<button disabled={!this.state.value} />

Here's a working example:

_x000D_
_x000D_
class AddItem extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = { value: '' };_x000D_
    this.onChange = this.onChange.bind(this);_x000D_
    this.add = this.add.bind(this);_x000D_
  }_x000D_
_x000D_
  add() {_x000D_
    this.props.onButtonClick(this.state.value);_x000D_
    this.setState({ value: '' });_x000D_
  }_x000D_
_x000D_
  onChange(e) {_x000D_
    this.setState({ value: e.target.value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <div className="add-item">_x000D_
        <input_x000D_
          type="text"_x000D_
          className="add-item__input"_x000D_
          value={this.state.value}_x000D_
          onChange={this.onChange}_x000D_
          placeholder={this.props.placeholder}_x000D_
        />_x000D_
        <button_x000D_
          disabled={!this.state.value}_x000D_
          className="add-item__button"_x000D_
          onClick={this.add}_x000D_
        >_x000D_
          Add_x000D_
        </button>_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,_x000D_
  document.getElementById('View')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id='View'></div>
_x000D_
_x000D_
_x000D_

How to create a oracle sql script spool file

To spool from a BEGIN END block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop. Sample code is given below.

BEGIN

FOR x IN 
(
    SELECT COLUMN1,COLUMN2 FROM TABLE1
    UNION ALL
    SELECT COLUMN1,COLUMN2 FROM TABLEB
)    
LOOP
    dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;

END;
/

Finding Key associated with max Value in a Java Map

Java 8 way to get all keys with max value.

Integer max = PROVIDED_MAP.entrySet()
            .stream()
            .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
            .get()
            .getValue();

List listOfMax = PROVIDED_MAP.entrySet()
            .stream()
            .filter(entry -> entry.getValue() == max)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

System.out.println(listOfMax);

Also you can parallelize it by using parallelStream() instead of stream()

go get results in 'terminal prompts disabled' error for github private repo

From go 1.13 onwards, if you had already configured your terminal with the git credentials and yet facing this issue, then you could try setting the GOPRIVATE environment variable. Setting this environment variable solved this issue for me.

export GOPRIVATE=github.com/{organizationName/userName of the package}/*  

Convert string in base64 to image and save on filesystem in Python

You can also save it to a string buffer and then do as you wish with it,

import cStringIO
data = json.loads(request.POST['imgData'])  # Getting the object from the post request
image_output = cStringIO.StringIO()
image_output.write(data.decode('base64'))   # Write decoded image to buffer
image_output.seek(0)  # seek beginning of the image string
# image_output.read()  # Do as you wish with it!

In django, you can save it as an uploaded file to save to a model:

from django.core.files.uploadedfile import SimpleUploadedFile
suf = SimpleUploadedFile('uploaded_file.png', image_output.read(), content_type='image/png')

Or send it as an email:

email = EmailMessage('Hello', 'Body goes here', '[email protected]',
                                     ['[email protected]', ])
                email.attach('design.png', image_output.read(), 'image/png')
                email.send()

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

Key hash for Android-Facebook app

For Linux

Open Terminal :

For Debug Build

keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64

you wil find debug.keystore from ".android" folder copy it from and paste on desktop and run above command

For release Build

keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> | openssl sha1 -binary | openssl base64

NOTE : Make sure In Both case it must ask for password. If it does not asks for password that means something is wrong in command.

Cannot find Dumpbin.exe

Visual Studio Commmunity 2017 - dumpbin.exe became available once I installed the C++ profiling tools in Modify menu from the Visual Studio Installer.

enter image description here

Get real path from URI, Android KitKat new storage access framework

I had the exact same problem. I need the filename so to be able to upload it to a website.

It worked for me, if I changed the intent to PICK. This was tested in AVD for Android 4.4 and in AVD for Android 2.1.

Add permission READ_EXTERNAL_STORAGE :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Change the Intent :

Intent i = new Intent(
  Intent.ACTION_PICK,
  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
  );
startActivityForResult(i, 66453666);

/* OLD CODE
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
  Intent.createChooser( intent, "Select Image" ),
  66453666
  );
*/

I did not have to change my code the get the actual path:

// Convert the image URI to the direct file system path of the image file
 public String mf_szGetRealPathFromURI(final Context context, final Uri ac_Uri )
 {
     String result = "";
     boolean isok = false;

     Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(ac_Uri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
        isok = true;
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }

      return isok ? result : "";
 }

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

Difference between JOIN and INNER JOIN

No, there is no difference, pure syntactic sugar.

How to connect to a MySQL Data Source in Visual Studio

In order to get the MySQL Database item in the Choose Data Source window, one should install the MySQL for Visual Studio package available here (the last version today is 1.2.6):

https://dev.mysql.com/downloads/windows/visualstudio/

What is the standard way to add N seconds to datetime.time in Python?

Thanks to @Pax Diablo, @bvmou and @Arachnid for the suggestion of using full datetimes throughout. If I have to accept datetime.time objects from an external source, then this seems to be an alternative add_secs_to_time() function:

def add_secs_to_time(timeval, secs_to_add):
    dummy_date = datetime.date(1, 1, 1)
    full_datetime = datetime.datetime.combine(dummy_date, timeval)
    added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
    return added_datetime.time()

This verbose code can be compressed to this one-liner:

(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()

but I think I'd want to wrap that up in a function for code clarity anyway.

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

Enable vertical scrolling on textarea

Simply, change

<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>

to

<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>

ie, add:

data-role="none"

How to break out of the IF statement

Try adding a control variable:

public void Method()
{
    bool doSomethingElse = true;
    if(something)
    {
        //some code
        if(!something2)
        {
            doSomethingElse = false;
        }
    }
    if(doSomethingElse)
    {
        // The code i want to go if the second if is true
    }
}

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This version allows you to have more than one case y or Y, n or N

  1. Optionally: Repeat the question until an approve question is provided

  2. Optionally: Ignore any other answer

  3. Optionally: Exit the terminal if you want

    confirm() {
        echo -n "Continue? y or n? "
        read REPLY
        case $REPLY in
        [Yy]) echo 'yup y' ;; # you can change what you do here for instance
        [Nn]) break ;;        # exit case statement gracefully
        # Here are a few optional options to choose between
        # Any other answer:
    
        # 1. Repeat the question
        *) confirm ;;
    
        # 2. ignore
        # *) ;;
    
        # 3. Exit terminal
        # *) exit ;;
    
        esac
        # REPLY=''
    }
    

Notice this too: On the last line of this function clear the REPLY variable. Otherwise if you echo $REPLY you will see it is still set until you open or close your terminal or set it again.

Dropping Unique constraint from MySQL table

The constraint could be removed with syntax:

ALTER TABLE

As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name: ALTER TABLE tbl_name DROP CONSTRAINT symbol;

Example:

CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));

-- checking constraint name if autogenerated
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';

-- dropping constraint
ALTER TABLE tab DROP CONSTRAINT unq_tab_id;

db<>fiddle demo

Why is C so fast, and why aren't other languages as fast or faster?

The lack of abstraction is what makes C faster. If you write an output statement you know exactly what is happening. If you write an output statement in java it is getting compiled to a class file which then gets run on a virtual machine introducing a layor of abstraction. The lack of object oriented features as a part of the language also increases it's speed do to less code being generated. If you use C as an object oriented language then you are doing all the coding for things such as classes, inharitence, etc. This means rather then make something generalized enough for everyone with the amount of code and the performance penelty that requires you only write what you need to get the job done.

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

How to validate phone number using PHP?

I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....

Take a look at this similar question to get some ideas.

Then there is E.164 which is a numbering standard recommendation from ITU-T

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

How to use OpenFileDialog to select a folder?

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

Install-Package Microsoft.WindowsAPICodePack-Shell

For the include line:

using Microsoft.WindowsAPICodePack.Dialogs;

Usage:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

Gradient text color

_x000D_
_x000D_
@import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400);_x000D_
_x000D_
body {_x000D_
  background: #222;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  display: table;_x000D_
  margin: 0 auto;_x000D_
  font-family: "Roboto Slab";_x000D_
  font-weight: 600;_x000D_
  font-size: 7em;_x000D_
  background: linear-gradient(330deg, #e05252 0%, #99e052 25%, #52e0e0 50%, #9952e0 75%, #e05252 100%);_x000D_
  -webkit-background-clip: text;_x000D_
  -webkit-text-fill-color: transparent;_x000D_
  line-height: 200px;_x000D_
}
_x000D_
<h1>beautiful</h1>
_x000D_
_x000D_
_x000D_

How can I clear the Scanner buffer in Java?

Try this:

in.nextLine();

This advances the Scanner to the next line.

WPF loading spinner

This repo on github seems to do the job quite well:

https://github.com/blackspikeltd/Xaml-Spinners-WPF

The spinners are all light weight and can easily be placed wherever needed. There is a sample project included in the repo that shows how to use them.

No nasty code-behinds with a bunch of logic either. If MVVM support is needed, one can just take these and throw them in a Grid with a Visibility binding.

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

How to Detect Browser Window /Tab Close Event?

You can't detect it with javascript.

Only events that do detect page unloading/closing are window.onbeforeunload and window.unload. Neither of these events can tell you the way that you closed the page.

How to make the first option of <select> selected with jQuery

One subtle point I think I've discovered about the top voted answers is that even though they correctly change the selected value, they do not update the element that the user sees (only when they click the widget will they see a check next to the updated element).

Chaining a .change() call to the end will also update the UI widget as well.

$("#target").val($("#target option:first").val()).change();

(Note that I noticed this while using jQuery Mobile and a box on Chrome desktop, so this may not be the case everywhere).

How to convert date to timestamp?

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

If you are using the Chrome Driver you can set the capabilities

    var capabilities = new DesiredCapabilities();

    var switches = new List<string>
                       {
                           "--start-maximized"
                       };

    capabilities.SetCapability("chrome.switches", switches);

    new ChromeDriver(chromedriver_path, capabilities);

How to get $(this) selected option in jQuery?

This should work:

$(this).find('option:selected').text();

SQL server stored procedure return a table

create procedure PSaleCForms
as
begin
declare 
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar    (max),invoicenumber     nvarchar(max),invoicedate datetime,sp decimal    18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for 
select x.DBTitle,y.CurrentFinancialYear from [Accounts     Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on        y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int)     when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr],     l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from     ['+@c+'].dbo.invoicemain i inner join  ['+@c+'].dbo.ledgermain l on     l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''

insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

'str' object does not support item assignment in Python

Hi you should try the string split method:

i = "Hello world"
output = i.split()

j = 'is not enough'

print 'The', output[1], j

How to completely remove borders from HTML table

This is what resolved the problem for me:

In your HTML tr tag, add this:

style="border-collapse: collapse; border: none;"

That removed all the borders that were showing on the table row.

How exactly does the python any() function work?

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

Creating a range of dates in Python

Marginally better...

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]

background-size in shorthand background property (CSS3)

Just a note for reference: I was trying to do shorthand like so:

background: url('../images/sprite.png') -312px -234px / 355px auto no-repeat;

but iPhone Safari browsers weren't showing the image properly with a fixed position element. I didn't check with a non-fixed, because I'm lazy. I had to switch the css to what's below, being careful to put background-size after the background property. If you do them in reverse, the background reverts the background-size to the original size of the image. So generally I would avoid using the shorthand to set background-size.

background: url('../images/sprite.png') -312px -234px no-repeat;
background-size: 355px auto;

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

Your HTML is fine, but update your JS jQuery script to look like this:

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

How to add element to C++ array?

If you are writing in C++ -- it is a way better to use data structures from standard library such as vector.

C-style arrays are very error-prone, and should be avoided whenever possible.

Setting maxlength of textbox with JavaScript or jQuery

You can make it like this:

$('#inputID').keypress(function () {
    var maxLength = $(this).val().length;
    if (maxLength >= 5) {
        alert('You cannot enter more than ' + maxLength + ' chars');
        return false;
    }
});

how to change onclick event with jquery?

@Amirali

console.log(document.getElementById("SAVE_FOOTER"));
document.getElementById("SAVE_FOOTER").attribute("onclick","console.log('c')");

throws:

Uncaught TypeError: document.getElementById(...).attribute is not a function

in chrome.

Element exists and is dumped in console;

When should I use curly braces for ES6 import?

This is a default import:

// B.js
import A from './A'

It only works if A has the default export:

// A.js
export default 42

In this case it doesn’t matter what name you assign to it when importing:

// B.js
import A from './A'
import MyA from './A'
import Something from './A'

Because it will always resolve to whatever is the default export of A.


This is a named import called A:

import { A } from './A'

It only works if A contains a named export called A:

export const A = 42

In this case the name matters because you’re importing a specific thing by its export name:

// B.js
import { A } from './A'
import { myA } from './A' // Doesn't work!
import { Something } from './A' // Doesn't work!

To make these work, you would add a corresponding named export to A:

// A.js
export const A = 42
export const myA = 43
export const Something = 44

A module can only have one default export, but as many named exports as you'd like (zero, one, two, or many). You can import them all together:

// B.js
import A, { myA, Something } from './A'

Here, we import the default export as A, and named exports called myA and Something, respectively.

// A.js
export default 42
export const myA = 43
export const Something = 44

We can also assign them all different names when importing:

// B.js
import X, { myA as myX, Something as XSomething } from './A'

The default exports tend to be used for whatever you normally expect to get from the module. The named exports tend to be used for utilities that might be handy, but aren’t always necessary. However it is up to you to choose how to export things: for example, a module might have no default export at all.

This is a great guide to ES modules, explaining the difference between default and named exports.

ReactJS - Does render get called any time "setState" is called?

Yes. It calls the render() method every time we call setState only except when "shouldComponentUpdate" returns false.

Android - How to get application name? (Not package name)

In Kotlin, use the following codes to get Application Name:

        // Get App Name
        var appName: String = ""
        val applicationInfo = this.getApplicationInfo()
        val stringId = applicationInfo.labelRes
        if (stringId == 0) {
            appName = applicationInfo.nonLocalizedLabel.toString()
        }
        else {
            appName = this.getString(stringId)
        }

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I want to add to the answers posted on above that none of the solutions proposed here worked for me. My WAMP, is working on port 3308 instead of 3306 which is what it is installed by default. I found out that when working in a local environment, if you are using mysqladmin in your computer (for testing environment), and if you are working with port other than 3306, you must define your variable DB_SERVER with the value localhost:NumberOfThePort, so it will look like the following: define("DB_SERVER", "localhost:3308"). You can obtain this value by right-clicking on the WAMP icon in your taskbar (on the hidden icons section) and select Tools. You will see the section: "Port used by MySQL: NumberOfThePort"

This will fix your connection to your database.

This was the error I got: Error: SQLSTATE[HY1045] Access denied for user 'username'@'localhost' on line X.

I hope this helps you out.

:)

Add key value pair to all objects in array

You may also try this:

arrOfObj.forEach(function(item){item.isActive = true;});

console.log(arrOfObj);

Using <style> tags in the <body> with other HTML

BREAKING BAD NEWS for "style in body" lovers: W3C has recently lost the HTML war against WHATWG, whose versionless HTML "Living Standard" has now become the official one, which, alas, does not allow STYLE in the BODY. The short-lived happy days are over. ;) The W3C validator also works by the WHATWG specs now. (Thanks @FrankConijn for the heads-up!)

(Note: this is the case "as of today", but since there's no versioning, links can become invalid at any moment without notice or control. Unless you're willing to link to its individual source commits at GitHub, you basically can no longer make stable references to the new official HTML standard, AFAIK. Please correct me if there's a canonical way of doing this properly.)

OBSOLETED GOOD NEWS:

Yay, STYLE is finally valid in BODY, as of HTML5.2! (And scoped is gone, too.)

From the W3C specs (relish the last line!):

4.2.6. The style element

...

Contexts in which this element can be used:

Where metadata content is expected.

In a noscript element that is a child of a head element.

In the body, where flow content is expected.


META SIDE-NOTE:

The mere fact that despite the damages of the "browser war" we still had to keep developing against two ridiculously competing "official" HTML "standards" (quotes for 1 standard + 1 standard < 1 standard) means that the "fallback to in-the-trenches common sense" approach to web development has never really ceased to apply.

This may finally change now, but citing the conventional wisdom: web authors/developers and thus, in turn, browsers should ultimately decide what should (and shouldn't) be in the specifications, when there's no good reason against what's already been done in reality. And most browsers have long supported STYLE in BODY (in one way or another; see e.g. the scoped attr.), despite its inherent performance (and possibly other) penalties (which we should decide to pay or not, not the specs.). So, for one, I'll keep betting on them, and not going to give up hope. ;) If WHATWG has the same respect for reality/authors as they claim, they may just end up doing here what the W3C did.

PostgreSQL error: Fatal: role "username" does not exist

For Windows users : psql -U postgres

You should see then the command-line interface to PostgreSQL: postgres=#

Why does jQuery or a DOM method such as getElementById not find the element?

This solution is for the people who don't use jQuery and to improve performance by not moving the script to bottom of the page, and the problem is that the script is loaded before the html elements are loaded. Add your code in this function body

window.onload=()=>{
    
    // your code here

    // example
    let element=document.getElementById("elementId");
    console.log(element);

};

add everything that has to work only after the document is loaded and keep other functions that has to be executed as soon as the script is loaded outside the function.

I recommend this method instead of moving down the script, because if the script is on top, the browser will try to download it as soon as it sees the script tag, if it is on the bottom of the page, it will take some more time to load it and until that time no event listeners in the script will work. in this case all other functions could be called and the window.onload will get called once everything is loaded.

How many spaces will Java String.trim() remove?

Javadoc for String has all the details. Removes white space (space, tabs, etc ) from both end and returns a new string.

Renaming columns in Pandas

As documented in Working with text data:

df.columns = df.columns.str.replace('$', '')

How to make fixed header table inside scrollable div?

I needed the same and this solution worked the most simple and straightforward way:

http://www.farinspace.com/jquery-scrollable-table-plugin/

I just give an id to the table I want to scroll and put one line in Javascript. That's it!

By the way, first I also thought I want to use a scrollable div, but it is not necessary at all. You can use a div and put it into it, but this solution does just what we need: scrolls the table.

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

How to compile C program on command line using MinGW?

I've had this problem and couldn't find why it kept happening. The reason is simple: Once you have set up the environment paths, you have to close the CMD window, and open it again for it be aware of new environment paths.

How to set breakpoints in inline Javascript in Google Chrome?

Refresh the page containing the script whilst the developer tools are open on the scripts tab. This will add a (program) entry in the file list which shows the html of the page including the script. From here you can add breakpoints.

ORA-01008: not all variables bound. They are bound

I know this is an old question, but it hasn't been correctly addressed, so I'm answering it for others who may run into this problem.

By default Oracle's ODP.net binds variables by position, and treats each position as a new variable.

Treating each copy as a different variable and setting it's value multiple times is a workaround and a pain, as furman87 mentioned, and could lead to bugs, if you are trying to rewrite the query and move things around.

The correct way is to set the BindByName property of OracleCommand to true as below:

var cmd = new OracleCommand(cmdtxt, conn);
cmd.BindByName = true;

You could also create a new class to encapsulate OracleCommand setting the BindByName to true on instantiation, so you don't have to set the value each time. This is discussed in this post

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

so it tells you that they cannot find the socket file at '/var/lib/mysql/mysql.sock'

what you'll do is you need to connect the mysql.sock file to it most probably it is at /tmp/mysql.sock if the file doesn' exist create it using

touch /tmp/mysql.sock

and then execute

sudo ln -s /tmp/mysql.sock /var/lib/mysql/mysql.sock

note if there is no mysql directory inside /var/lib create it

mkdir mysql

refresh your app

Android Debug Bridge (adb) device - no permissions

You udev rule seems wrong. I used this and it worked:

SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev"

(ATTR instead of SYSFS)

Can I use a min-height for table, tr or td?

Tables and table cells don't use the min-height property, setting their height will be the min-height as tables will expand if the content stretches them.

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version> Your Version Here </version>
    <configuration>
            <!-- put your configurations here -->
    </configuration>
    <executions>
            <execution>
                    <phase>package</phase>
                    <goals>
                            <goal>shade</goal>
                    </goals>
            </execution>
    </executions>
</plugin>

php codeigniter count rows

public function number_row()
 {
    $query = $this->db->select("count(user_details.id) as number")
                       ->get('user_details');              
      if($query-> num_rows()>0)
      {
          return $query->row();
      } 
      else
      {
          return false;
      } 
   }

get url content PHP

Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

"Non-static method cannot be referenced from a static context" error

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want

public void loanItem() {
    this.media.setLoanItem("Yes");
}

or

public void loanItem(Media object) {
    object.setLoanItem("Yes");
}

depending on how you want to pass that instance around.

What is a MIME type?

A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.

So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."

You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).

How can one change the timestamp of an old commit in Git?

Set the date of the last commit to the current date

GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"

Set the date of the last commit to an arbitrary date

GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"

Set the date of an arbitrary commit to an arbitrary or current date

Rebase to before said commit and stop for amendment:

  1. git rebase <commit-hash>^ -i
  2. Replace pick with e (edit) on the line with that commit (the first one)
  3. quit the editor (ESC followed by :wq in VIM)
  4. Either:
  • GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"
  • GIT_COMMITTER_DATE="Mon 20 Aug 2018 20:19:19 BST" git commit --amend --no-edit --date "Mon 20 Aug 2018 20:19:19 BST"

Source: https://codewithhugo.com/change-the-date-of-a-git-commit/

Different class for the last element in ng-repeat

It's easier and cleaner to do it with CSS.

HTML:

<div ng-repeat="file in files" class="file">
  {{ file.name }}
</div>

CSS:

.file:last-of-type {
    color: #800;
}

The :last-of-type selector is currently supported by 98% of browsers

How to edit HTML input value colour?

Add a style = color:black !important; in your input type.

filtering a list using LINQ

Based on http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b,

EqualAll is the approach that best meets your needs.

public void Linq96() 
{ 
    var wordsA = new string[] { "cherry", "apple", "blueberry" }; 
    var wordsB = new string[] { "cherry", "apple", "blueberry" }; 

    bool match = wordsA.SequenceEqual(wordsB); 

    Console.WriteLine("The sequences match: {0}", match); 
} 

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

How to change the color of a CheckBox?

Programmatic version:

int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));

Android video streaming example

I was facing the same problem and found a solution to get the code to work.

The code given in the android-Sdk/samples/android-?/ApiDemos works fine. Copy paste each folder in the android project and then in the MediaPlayerDemo_Video.java put the path of the video you want to stream in the path variable. It is left blank in the code.

The following video stream worked for me: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

I know that RTSP protocol is to be used for streaming, but mediaplayer class supports http for streaming as mentioned in the code.

I googled for the format of the video and found that the video if converted to mp4 or 3gp using Quicktime Pro works fine for streaming.

I tested the final apk on android 2.1. The application dosent work on emulators well. Try it on devices.

I hope this helps..

How can I generate a list or array of sequential integers in Java?

You can use the Interval class from Eclipse Collections.

List<Integer> range = Interval.oneTo(10);
range.forEach(System.out::print);  // prints 12345678910

The Interval class is lazy, so doesn't store all of the values.

LazyIterable<Integer> range = Interval.oneTo(10);
System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10

Your method would be able to be implemented as follows:

public List<Integer> makeSequence(int begin, int end) {
    return Interval.fromTo(begin, end);
}

If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList with IntInterval from Eclipse Collections.

public IntList makeSequence(int begin, int end) {
    return IntInterval.fromTo(begin, end);
}

IntList has the methods sum(), min(), minIfEmpty(), max(), maxIfEmpty(), average() and median() available on the interface.

Update for clarity: 11/27/2017

An Interval is a List<Integer>, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List, Set or Bag as follows:

Interval integers = Interval.oneTo(10);
Set<Integer> set = integers.toSet();
List<Integer> list = integers.toList();
Bag<Integer> bag = integers.toBag();

An IntInterval is an ImmutableIntList which extends IntList. It also has converter methods.

IntInterval ints = IntInterval.oneTo(10);
IntSet set = ints.toSet();
IntList list = ints.toList();
IntBag bag = ints.toBag();

An Interval and an IntInterval do not have the same equals contract.

Update for Eclipse Collections 9.0

You can now create primitive collections from primitive streams. There are withAll and ofAll methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));

Note: I am a committer for Eclipse Collections

Passing just a type as a parameter in C#

You can do this, just wrap it in typeof()

foo.GetColumnValues(typeof(int))

public void GetColumnValues(Type type)
{
    //logic
}

How to upload (FTP) files to server in a bash script?

You can use a heredoc to do this e.g.

ftp -n $Server <<End-Of-Session
# -n option disables auto-logon

user anonymous "$Password"
binary
cd $Directory
put "$Filename.lsm"
put "$Filename.tar.gz"
bye
End-Of-Session

so the ftp process is fed on stdin with everything up to End-Of-Session. A useful tip for spawning any process, not just ftp! Note that this saves spawning a separate process (echo, cat etc.). Not a major resource saving, but worth bearing in mind.

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Unzip files (7-zip) via cmd command

In Windows 10 I had to run the batch file as an administrator.

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Replace transparency in PNG images with white background

It appears that your command is correct so the problem might be due to missing support for PNG (). You can check with convert -list configure or just try the following:

sudo yum install libpng libpng-devel

Side-by-side list items as icons within a div (css)

give the LI float: left (or right)

They will all be in the same line until there will be no more room in the container (your case, a ul). (forgot): If you have a block element after the floating elements, he will also stick to them, unless you give him a clear:both, OR put an empty div before it with clear:both

Dynamic variable names in Bash

For zsh (newers mac os versions), you should use

real_var="holaaaa"
aux_var="real_var"
echo ${(P)aux_var}
holaaaa

Instead of "!"

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

What's the difference between Sender, From and Return-Path?

A minor update to this: a sender should never set the Return-Path: header. There's no such thing as a Return-Path: header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From unless the local system needs some kind of quirky routing.

It's a common misunderstanding because users rarely see an email without a Return-Path: header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path: header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4

File.Move Does Not Work - File Already Exists

Personally I prefer this method. This will overwrite the file on the destination, removes the source file and also prevent removing the source file when the copy fails.

string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";

try
{
    File.Copy(source, destination, true);
    File.Delete(source);
}
catch
{
    //some error handling
}

How to get root access on Android emulator?

Here my pack with all you need. Or you can use this script:

echo on
set device=emulator-5554
set avd_name=
set adb=d:\Poprygun\DevTools\Android\Android-sdk\platform-tools\adb -s %device%
set emulator=d:\Poprygun\DevTools\Android\Android-sdk\emulator\emulator
set arch=x86
set pie=

echo Close all ANDROID emulators and press any key
pause
start %emulator% -avd Nexus_One_API_25 -verbose -writable-system
echo Wait until ANDROID emulator loading and press any key
pause

%adb% start-server
%adb% root
%adb% remount
%adb% shell setenforce 0
%adb% install D:\SuperSU\SuperSU.apk
%adb% push D:\SuperSU\su\%arch%\su.pie /system/bin/su
%adb% shell chmod 0755 /system/bin/su
%adb% push D:\SuperSU\su\%arch%\su.pie /system/xbin/su
%adb% shell chmod 0755 /system/xbin/su
%adb% shell su --install
%adb% shell "su --daemon&"
pause
exit /b

Change the name of a key in dictionary

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value. Several of the other answers illustrate different ways this can be accomplished.

How do you Make A Repeat-Until Loop in C++?

For an example if you want to have a loop that stopped when it has counted all of the people in a group. We will consider the value X to be equal to the number of the people in the group, and the counter will be used to count all of the people in the group. To write the

while(!condition)

the code will be:

int x = people;

int counter = 0;

while(x != counter)

{

counter++;

}

return 0;

Make git automatically remove trailing whitespace before committing

Here is an ubuntu+mac os x compatible version:

#!/bin/sh
#

# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
#

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | (sed -r 's/:[0-9]+:.*//' > /dev/null 2>&1 || sed -E 's/:[0-9]+:.*//') | uniq` ; do
  # Fix them!
  (sed -i 's/[[:space:]]*$//' "$FILE" > /dev/null 2>&1 || sed -i '' -E 's/[[:space:]]*$//' "$FILE")
  git add "$FILE"
done

# Now we can commit
exit

Have fun

How can I find the number of elements in an array?

sizeof returns the size in bytes of it's argument. This is not what you want, but it can help.

Let's say you have an array:

int array[4];

If you apply sizeof to the array (sizeof(array)), it will return its size in bytes, which in this case is 4 * the size of an int, so a total of maybe 16 bytes (depending on your implementation).

If you apply sizeof to an element of the array (sizeof(array[0])), it will return its size in bytes, which in this case is the size of an int, so a total of maybe 4 bytes (depending on your implementation).

If you divide the first one by the second one, it will be: (4 * the size of an int) / (the size of an int) = 4; That's exactly what you wanted.

So this should do:

sizeof(array) / sizeof(array[0])

Now you would probably like to have a macro to encapsulate this logic and never have to think again how it should be done:

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))

You need the parentheses enclosing all the macro as in any other complex macro, and also enclosing every variable, just to avoid unexpected bugs related to operators precedence.

Now you can use it on any array like this:

int array[6];
ptrdiff_t nmemb;

nmemb = ARRAY_SIZE(array);
/* nmemb == 6 */

Remember that arguments of functions declared as arrays are not really arrays, but pointers to the first element of the array, so this will NOT work on them:

void foo(int false_array[6])
{
        ptrdiff_t nmemb;

        nmemb = ARRAY_SIZE(false_array);
        /* nmemb == sizeof(int *) / sizeof(int) */
        /* (maybe  ==2) */
}

But it can be used in functions if you pass a pointer to an array instead of just the array:

void bar(int (*arrptr)[7])
{
        ptrdiff_t nmemb;

        nmemb = ARRAY_SIZE(*arrptr);
        /* nmemb == 7 */
}

Can jQuery get all CSS styles associated with an element?

Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.

How can I rename a field for all documents in MongoDB?

If you are using MongoMapper, this works:

Access.collection.update( {}, { '$rename' => { 'location' => 'location_info' } }, :multi => true )

Writing MemoryStream to Response Object

I had the same issue. try this: copy to MemoryStream -> delete file -> download.

string absolutePath = "~/your path";
try {
    //copy to MemoryStream
    MemoryStream ms = new MemoryStream();
    using (FileStream fs = File.OpenRead(Server.MapPath(absolutePath))) 
    { 
        fs.CopyTo(ms); 
    }

    //Delete file
    if(File.Exists(Server.MapPath(absolutePath)))
       File.Delete(Server.MapPath(absolutePath))

    //Download file
    Response.Clear()
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + absolutePath + "\"");
    Response.BinaryWrite(ms.ToArray())
}
catch {}

Response.End();

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Important Update

Go to project level build.gradle, define global variables

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlinVersion = '1.2.61'

    ext.global_minSdkVersion = 16
    ext.global_targetSdkVersion = 28
    ext.global_buildToolsVersion = '28.0.1'
    ext.global_supportLibVersion = '27.1.1'
}

Go to app level build.gradle, and use global variables

app build.gradle

android {
    compileSdkVersion global_targetSdkVersion
    buildToolsVersion global_buildToolsVersion
    defaultConfig {
        minSdkVersion global_minSdkVersion
        targetSdkVersion global_targetSdkVersion
}
...

dependencies {
    implementation "com.android.support:appcompat-v7:$global_supportLibVersion"
    implementation "com.android.support:recyclerview-v7:$global_supportLibVersion"
    // and so on...
}

some library build.gradle

android {
    compileSdkVersion global_targetSdkVersion
    buildToolsVersion global_buildToolsVersion
    defaultConfig {
        minSdkVersion global_minSdkVersion
        targetSdkVersion global_targetSdkVersion
}
...

dependencies {
    implementation "com.android.support:appcompat-v7:$global_supportLibVersion"
    implementation "com.android.support:recyclerview-v7:$global_supportLibVersion"
    // and so on...
}

The solution is to make your versions same as in all modules. So that you don't have conflicts.

Important Tips

I felt when I have updated versions of everything- gradle, sdks, libraries etc. then I face less errors. Because developers are working hard to make it easy development on Android Studio.

Always have latest but stable versions Unstable versions are alpha, beta and rc, ignore them in developing.

I have updated all below in my projects, and I don't face these errors anymore.

Happy coding! :)

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

you could try

$('*').not('#div').bind('touchmove', false);

add this if necessary

$('#div').bind('touchmove');

note that everything is fixed except #div

Run Excel Macro from Outside Excel Using VBScript From Command Line

Ok, it's actually simple. Assuming that your macro is in a module,not in one of the sheets, you use:

  objExcel.Application.Run "test.xls!dog" 
  'notice the format of 'workbook name'!macro

For a filename with spaces, encase the filename with quotes.

If you've placed the macro under a sheet, say sheet1, just assume sheet1 owns the function, which it does.

    objExcel.Application.Run "'test 2.xls'!sheet1.dog"

Notice: You don't need the macro.testfunction notation you've been using.

How to install Visual Studio 2015 on a different drive

Run the installer from command line with argument /CustomInstallPath InstallationDirectory

See more command-line parameters and other installation information.

Note: this won't change location of all files, but only of those which can be (by design) installed onto different location. Be warned that there is many shared components which will be installed into shared repositories on drive C: without any possibility to change their path (unless you do some hacking using mklink /j (directory junction, i.e."hard link for folder"), but it is questionable whether it is worth it, because any Visual Studio updates will break those hard links. This is confirmed by people who tried that, although on Visual Studio 2012.)


Update: per recent comment, uninstallation of Visual Studio might be required before the above applies. Uninstallation command is like this: vs_community_ENU.exe /uninstall /force

Finding square root without using sqrt function?

As I found this question is old and have many answers but I have an answer which is simple and working great..

#define EPSILON 0.0000001 // least minimum value for comparison
double SquareRoot(double _val) {
    double low = 0; 
    double high = _val;
    double mid = 0; 

    while (high - low > EPSILON) {
            mid = low + (high - low) / 2; // finding mid value
            if (mid*mid > _val) {
                high = mid;
            } else {
                low = mid;
            }    
    }   
    return mid;
}

I hope it will be helpful for future users.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.

You can either disable it by editing web.config to include the following:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Or better yet properly configure it by modifying the Application_Start method in global.asax:

void Application_Start(object sender, EventArgs e) 
{
    RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
        new ScriptResourceDefinition
        {
            Path = "/~Scripts/jquery-2.1.1.min.js"
        }
    );
}

Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.

For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;

namespace @default
{
    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }
    }
}

jQuery - Click event on <tr> elements with in a table and getting <td> element values

This work for me!

$(document).ready(function() {
    $(document).on("click", "#tableId tbody tr", function() {
        //some think
    });
});

error: package com.android.annotations does not exist

You can find here the official javadoc of the support-annotationslibrary.

Error:(3, 31) error: package com.android.annotations does not exist

As you can see all the classes are in the same package android.support.annotation and not com.android.annotations.

Error:(7, 2) error: cannot find symbol class NonNullByDefault

Also the class NonNullByDefault doesn't exist in that package.

Jackson how to transform JsonNode to ArrayNode without casting?

Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode to use. Here's an example:

JSON:

{
    "objects" : ["One", "Two", "Three"]
}

Code:

final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";

final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
    for (final JsonNode objNode : arrNode) {
        System.out.println(objNode);
    }
}

Output:

"One"
"Two"
"Three"

Note the use of isArray to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).

Using varchar(MAX) vs TEXT on SQL Server

The VARCHAR(MAX) type is a replacement for TEXT. The basic difference is that a TEXT type will always store the data in a blob whereas the VARCHAR(MAX) type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.

Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX) gives you is that it is also can be used with = and GROUP BY as any other VARCHAR column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.

In regard to if you should use LIKE to search, or if you should use Full Text Indexing and CONTAINS. This question is the same regardless of VARCHAR(MAX) or TEXT.

If you are searching large amounts of text and performance is key then you should use a Full Text Index.

LIKE is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.

When is layoutSubviews called?

https://developer.apple.com/library/prerelease/tvos/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html#//apple_ref/doc/uid/TP40009503-CH5-SW1

Layout changes can occur whenever any of the following events happens in a view:

a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling the setNeedsLayout or layoutIfNeeded method of a view.
e. Your application forces layout by calling the setNeedsLayout method of the view’s underlying layer object.

hexadecimal string to byte array in python

def hex2bin(s):
    hex_table = ['0000', '0001', '0010', '0011',
                 '0100', '0101', '0110', '0111',
                 '1000', '1001', '1010', '1011',
                 '1100', '1101', '1110', '1111']
    bits = ''
    for i in range(len(s)):
        bits += hex_table[int(s[i], base=16)]
    return bits

Setting up maven dependency for SQL Server

There is also an alternative: you could use the open-source jTDS driver for MS-SQL Server, which is compatible although not made by Microsoft. For that driver, there is a maven artifact that you can use:

http://jtds.sourceforge.net/

From http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds :

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.3.1</version>
</dependency>

UPDATE nov 2016, Microsoft now published its MSSQL JDBC driver on github and it's also available on maven now:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

Tooltips with Twitter Bootstrap

I included the JS and CSS file and was wondering why it is not working, what made it work was when I added the following in <head>:

<script>
jQuery(function ($) {
    $("a").tooltip()
});
</script>

Finding first and last index of some value in a list in Python

Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).

You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)

removeEventListener on anonymous functions in JavaScript

I just experienced similiar problem with copy-protection wordpress plugin. The code was:

function disableSelection(target){
 if (typeof target.onselectstart!="undefined") //For IE 
  target.onselectstart=function(){return false}
 else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
  target.style.MozUserSelect="none"
 else //All other route (For Opera)
  target.onmousedown=function(){return false}
target.style.cursor = "default"
}

And then it was initiated by loosely put

<script type="text/javascript">disableSelection(document.body)</script>.

I came around this simply by attaching other annonymous function to this event:

document.body.onselectstart = function() { return true; };

java: ArrayList - how can I check if an index exists?

If your index is less than the size of your list then it does exist, possibly with null value. If index is bigger then you may call ensureCapacity() to be able to use that index.

If you want to check if a value at your index is null or not, call get()

Changing ImageView source

Changing ImageView source:

Using setBackgroundResource() method:

  myImgView.setBackgroundResource(R.drawable.monkey);

you are putting that monkey in the background.

I suggest the use of setImageResource() method:

  myImgView.setImageResource(R.drawable.monkey);

or with setImageDrawable() method:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));

*** With new android API 22 getResources().getDrawable() is now deprecated. This is an example how to use now:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));

and how to validate for old API versions:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
   } else {
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
}

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

How to get the cell value by column name not by index in GridView in asp.net

Although its a long time but this relatively small piece of code seems easy to read and get:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   int index;
   string cellContent;

    foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
    {
       if( tc.Text.Equals("yourColumnName") )
       {
         index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
         cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
         break;
       }
    }
}

Static nested class in Java, why?

The Sun page you link to has some key differences between the two:

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
...

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

There is no need for LinkedList.Entry to be top-level class as it is only used by LinkedList (there are some other interfaces that also have static nested classes named Entry, such as Map.Entry - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.

As Jon Skeet points out, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.

Execute method on startup in Spring

If you want to configure a bean before your application is running fully, you can use @Autowired:

@Autowired
private void configureBean(MyBean: bean) {
    bean.setConfiguration(myConfiguration);
}

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

How to zoom div content using jquery?

Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/

 <script>
    $(document).ready(function(){
        $('#ex1').zoom();

    });
</script>

Add Foreign Key to existing table

To add a foreign key (grade_id) to an existing table (users), follow the following steps:

ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

How to toggle boolean state of react component?

You could also use React's useState hook to declare local state for a function component. The initial state of the variable toggled has been passed as an argument to the method .useState.

import { render } from 'react-dom';
import React from "react";

type Props = {
  text: string,
  onClick(event: React.MouseEvent<HTMLButtonElement>): void,
};

export function HelloWorldButton(props: Props) {
  const [toggled, setToggled] = React.useState(false); // returns a stateful value, and a function to update it
  return <button
  onClick={(event) => {
    setToggled(!toggled);
    props.onClick(event);
  }}
  >{props.text} (toggled: {toggled.toString()})</button>;
}


render(<HelloWorldButton text='Hello World' onClick={() => console.log('clicked!')} />, document.getElementById('root'));

https://stackblitz.com/edit/react-ts-qga3vc

Batch program to to check if process exists

TASKLIST does not set errorlevel.

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

GROUP BY without aggregate function

Given this data:

Col1  Col2  Col3
 A     X     1
 A     Y     2
 A     Y     3
 B     X     0
 B     Y     3
 B     Z     1

This query:

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3

Would result in exactly the same table.

However, this query:

SELECT Col1, Col2 FROM data GROUP BY Col1, Col2

Would result in:

Col1  Col2
 A     X  
 A     Y  
 B     X  
 B     Y  
 B     Z  

Now, a query:

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2

Would create a problem: the line with A, Y is the result of grouping the two lines

 A     Y     2
 A     Y     3

So, which value should be in Col3, '2' or '3'?

Normally you would use a GROUP BY to calculate e.g. a sum:

SELECT Col1, Col2, SUM(Col3) FROM data GROUP BY Col1, Col2

So in the line, we had a problem with we now get (2+3) = 5.

Grouping by all your columns in your select is effectively the same as using DISTINCT, and it is preferable to use the DISTINCT keyword word readability in this case.

So instead of

SELECT Col1, Col2, Col3 FROM data GROUP BY Col1, Col2, Col3

use

SELECT DISTINCT Col1, Col2, Col3 FROM data

Max or Default?

Think about what you're asking!

The max of {1, 2, 3, -1, -2, -3} is obviously 3. The max of {2} is obviously 2. But what is the max of the empty set { }? Obviously that is a meaningless question. The max of the empty set is simply not defined. Attempting to get an answer is a mathematical error. The max of any set must itself be an element in that set. The empty set has no elements, so claiming that some particular number is the max of that set without being in that set is a mathematical contradiction.

Just as it is correct behavior for the computer to throw an exception when the programmer asks it to divide by zero, so it is correct behavior for the computer to throw an exception when the programmer asks it to take the max of the empty set. Division by zero, taking the max of the empty set, wiggering the spacklerorke, and riding the flying unicorn to Neverland are all meaningless, impossible, undefined.

Now, what is it that you actually want to do?

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I had similar issue on Windows 7. At first I setup M2, M2_HOME under User variable but when I echoed %PATH% , I did not see maven bin directory listed under PATH. Then I setup M2, M2_HOME under system variable and it worked.

why is plotting with Matplotlib so slow?

Matplotlib makes great publication-quality graphics, but is not very well optimized for speed. There are a variety of python plotting packages that are designed with speed in mind:

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...

Creating a button in Android Toolbar

They are called menu items or action buttons in toolbar/actionbar. Here you have Google tutorial how it works and how to add them https://developer.android.com/training/basics/actionbar/adding-buttons.html

How to disable GCC warnings for a few lines of code

#pragma GCC diagnostic ignored "-Wformat"

Replace "-Wformat" with the name of your warning flag.

AFAIK there is no way to use push/pop semantics for this option.

Convert boolean result into number/integer

I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.

var j = bool & 1;

A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.

function toInt( val ) {
    return val & 1;
}

var j = toInt(bool);

Edit - September 10th, 2014

No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.

var j = boolValue === true ? 1 : 0;

Test for yourself: http://jsperf.com/boolean-int-conversion/2

In FireFox and Internet Explorer, using the version I posted is faster generally.

Edit - July 14th, 2017

Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.

Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.

Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
    return this & 1;
}});

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

How to reset Jenkins security settings from the command line?

To disable Jenkins security in simple steps in Linux, run these commands:

sudo ex +g/useSecurity/d +g/authorizationStrategy/d -scwq /var/lib/jenkins/config.xml
sudo /etc/init.d/jenkins restart

It will remove useSecurity and authorizationStrategy lines from your config.xml root config file and restart your Jenkins.

See also: Disable security at Jenkins website


After gaining the access to Jenkins, you can re-enable security in your Configure Global Security page by choosing the Access Control/Security Realm. After than don't forget to create the admin user.

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

Link statically to libstdc++ with -static-libstdc++ gcc option.

Removing empty rows of a data file in R

Alternative solution for rows of NAs using janitor package

myData %>% remove_empty("rows")

Remove an item from a dictionary when its key is unknown

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping

How to search through all Git and Mercurial commits in the repository for a certain string?

In Mercurial you use hg log --keyword to search for keywords in the commit messages and hg log --user to search for a particular user. See hg help log for other ways to limit the log.

How do I format date in jQuery datetimepicker?

Here you go.

$('#timePicker').datetimepicker({
   // dateFormat: 'dd-mm-yy',
   format:'DD/MM/YYYY HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

function getFormattedDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear().toString().slice(2);
    return day + '-' + month + '-' + year;
}

You need to pass datepicker() the date formatted correctly.

How to concatenate multiple column values into a single column in Panda dataframe

@derchambers I found one more solution:

import pandas as pd

# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'

def eval_join(df, columns):

    sum_elements = [f"df['{col}']" for col in list('1234')]
    to_eval = "+ '_' + ".join(sum_elements)

    return eval(to_eval)


#profile
%timeit df3 = eval_join(df, list('1234')) # 504 ms

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

The most upvoted answer is not implementing a real slide in/out (or down/up), as:

  1. It's not doing a soft transition on the height attribute. At time zero the element already has the 100% of its height producing a sudden glitch on the elements below it.
  2. When sliding out/up, the element does a translateY(-100%) and then suddenly disappears, causing another glitch on the elements below it.

You can implement a slide in and slide out like so:

my-component.ts

import { animate, style, transition, trigger } from '@angular/animations';

@Component({
  ...
  animations: [
    trigger('slideDownUp', [
      transition(':enter', [style({ height: 0 }), animate(500)]),
      transition(':leave', [animate(500, style({ height: 0 }))]),
    ]),
  ],
})

my-component.html

<div @slideDownUp *ngIf="isShowing" class="box">
  I am the content of the div!
</div>

my-component.scss

.box {
  overflow: hidden;
}

Remove commas from the string using JavaScript

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

Create MSI or setup project with Visual Studio 2012

Please see:

Visual Studio setup projects (vdproj) will not ship with future versions of VS

Windows Installer Deployment

It was announced 1 1/2 years ago that the project types were being killed. Alternatives are:

  1. Use A VS2008/2010 Solution to build your installer
  2. Switch to another tool such as InstallShield or Windows Installer XML

Convert base-2 binary number string to int

A recursive Python implementation:

def int2bin(n):
    return int2bin(n >> 1) + [n & 1] if n > 1 else [1] 

Select last row in MySQL

Yes, there's an auto_increment in there

If you want the last of all the rows in the table, then this is finally the time where MAX(id) is the right answer! Kind of:

SELECT fields FROM table ORDER BY id DESC LIMIT 1;

How to get cell value from DataGridView in VB.Net?

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

How to set cookie in node js using express framework?

The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.

If express.static is handling the request, you need to move your middleware up:

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
  // check if client sent cookie
  var cookie = req.cookies.cookieName;
  if (cookie === undefined) {
    // no: set a new cookie
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
    console.log('cookie created successfully');
  } else {
    // yes, cookie was already present 
    console.log('cookie exists', cookie);
  } 
  next(); // <-- important!
});

// let static middleware do its job
app.use(express.static(__dirname + '/public'));

Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next() when the cookie has been set.

Update

As of now the cookie parser is a seperate npm package, so instead of using

app.use(express.cookieParser());

you need to install it separately using npm i cookie-parser and then use it as:

const cookieParser = require('cookie-parser');
app.use(cookieParser());

Regex to match alphanumeric and spaces

I suspect ^ doesn't work the way you think it does outside of a character class.

What you're telling it to do is replace everything that isn't an alphanumeric with an empty string, OR any leading space. I think what you mean to say is that spaces are ok to not replace - try moving the \s into the [] class.

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Pandas DataFrame concat vs append

So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.

I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.

In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))

In [18]: df1
Out[18]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A    10000  non-null values
dtypes: int64(1)

In [19]: df4 = pd.DataFrame()

The concat

In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop

This is equavalent of your append

In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of 

 3: 56.8 ms per loop

How to initailize byte array of 100 bytes in java with all 0's

byte[] bytes = new byte[100];

Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.

Where is adb.exe in windows 10 located?

You can look in C:\android\sdk\platform-tools . This was where I found it on my computer.

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

Use ffmpeg to add text subtitles

I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.

ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>

As you can see, it's all about the -map 0, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.

You can create a simple batch mkv2mp4.bat, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.

@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"

Now you can simply run

mkv2mp4 "Video with subtitles etc.mkv"

And it will create "Video with subtitles etc.mp4" with the maximum of information included.

Pretty graphs and charts in Python

You can also use pygooglechart, which uses the Google Chart API. This isn't something you'd always want to use, but if you want a small number of good, simple, charts, and are always online, and especially if you're displaying in a browser anyway, it's a good choice.

Difference between string object and string literal

Some disassembly is always interesting...

$ cat Test.java 
public class Test {
    public static void main(String... args) {
        String abc = "abc";
        String def = new String("def");
    }
}

$ javap -c -v Test
Compiled from "Test.java"
public class Test extends java.lang.Object
  SourceFile: "Test.java"
  minor version: 0
  major version: 50
  Constant pool:
const #1 = Method  #7.#16;  //  java/lang/Object."<init>":()V
const #2 = String  #17;     //  abc
const #3 = class   #18;     //  java/lang/String
const #4 = String  #19;     //  def
const #5 = Method  #3.#20;  //  java/lang/String."<init>":(Ljava/lang/String;)V
const #6 = class   #21;     //  Test
const #7 = class   #22;     //  java/lang/Object
const #8 = Asciz   <init>;
...

{
public Test(); ...    

public static void main(java.lang.String[]);
  Code:
   Stack=3, Locals=3, Args_size=1
    0:    ldc #2;           // Load string constant "abc"
    2:    astore_1          // Store top of stack onto local variable 1
    3:    new #3;           // class java/lang/String
    6:    dup               // duplicate top of stack
    7:    ldc #4;           // Load string constant "def"
    9:    invokespecial #5; // Invoke constructor
   12:    astore_2          // Store top of stack onto local variable 2
   13:    return
}

How do I format a date with Dart?

handling yearly quarters, from string to DateTime, I didn't find proper solution so made this:

    List<String> dateAsList = 'Q1 2001'.split(' ');
    DateTime dateTime = DateTime.now();
    String quarter = dateAsList[0];
    int year = int.parse(dateAsList[1]);
    switch(quarter) {
      case "Q1": dateTime = DateTime(year, 1);
      break;
      case "Q2": dateTime = DateTime(year, 4);
      break;
      case "Q3": dateTime = DateTime(year, 7);
      break;
      case "Q4": dateTime = DateTime(year, 10);
      break;
    }

How to use SQL Select statement with IF EXISTS sub query?

Use a CASE statement and do it like this:

SELECT 
    T1.Id [Id]
    ,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2]
FROM
    TABLE1 [T1]
    LEFT OUTER JOIN
        TABLE2 [T2]
        ON
        T2.Id = T1.Id

Way to get all alphabetic chars in an array in PHP?

All good answers, in case someone is looking for an array of lower and upper case alphabets, here it is:

$alpha = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');

Why isn't Python very good for functional programming?

Guido has a good explanation of this here. Here's the most relevant part:

I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn't view Python as a functional programming language. However, earlier on, it was clear that users wanted to do much more with lists and functions.

...

It is also worth noting that even though I didn't envision Python as a functional language, the introduction of closures has been useful in the development of many other advanced programming features. For example, certain aspects of new-style classes, decorators, and other modern features rely upon this capability.

Lastly, even though a number of functional programming features have been introduced over the years, Python still lacks certain features found in “real” functional programming languages. For instance, Python does not perform certain kinds of optimizations (e.g., tail recursion). In general, because Python's extremely dynamic nature, it is impossible to do the kind of compile-time optimization known from functional languages like Haskell or ML. And that's fine.

I pull two things out of this:

  1. The language's creator doesn't really consider Python to be a functional language. Therefore, it's possible to see "functional-esque" features, but you're unlikely to see anything that is definitively functional.
  2. Python's dynamic nature inhibits some of the optimizations you see in other functional languages. Granted, Lisp is just as dynamic (if not more dynamic) as Python, so this is only a partial explanation.

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

It happened to me before.

When the table has been created and I added in .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) later, the code migration somehow could not assign default value for the Guid column.

The fix:

All we need is to go to the database, select the Id column and add newsequentialid() manually into Default Value or Binding.

No need to update dbo.__MigrationHistory table.

Hope it helps.


The solution of adding New Guid() is generally not preferred, because in theory there is possibility that you might get a duplicate accidentally.


And you shouldn't worry about directly editing in the database. All Entity Framework do is automate part of our database work.

Translating

.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)

into

[Id] [uniqueidentifier] NOT NULL DEFAULT newsequentialid(),

If somehow our EF missed one thing and did not add in the default value for us, just go ahead and add it manually.

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

I had same issue after the server has been attacked using a DDoS (actually a penetration testing tool).

I've headed to /etc/var/mysql/error.log first to see the InnoDB had a file lock.

The issue was immediately fixed by restarting the server, however that's not future-proof.

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

How to update specific key's value in an associative array in PHP?

This will work too!

foreach($data as &$value) {
  $value['transaction_date'] = date('d/m/Y', $value['transaction_date']);
}

Yay for alternatives!

Select first and last row from grouped data

There is probably a faster way:

df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  filter(row_number()==1 | row_number()==n())

Show how many characters remaining in a HTML text box using JavaScript

try this code in here...this is done using javascript onKeyUp() function...

<script>
function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
length=0;  
text='<span class="disable"> '+text+' <\/span>';  
entranceObj.value=entranceObj.value.substr(0,characters);  
}  
exitObj.innerHTML = text.replace("{CHAR}",length);  
}
</script>

textarea counter demo

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

11. R (or another dependency) is out of date and you don't want to update it.

Warning this is not exactly best practice.

  • Download the package source.
  • Navigate to the DESCRIPTION file.
  • Remove the offending line with your text editor e.g.

    Depends: R (>= 3.1.1)
    
  • Install from local (i.e. from the parent directory of DESCRIPTION) e.g.

    install.packages("foo", type="source", repos=NULL)
    

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

Your virtualhost filename should be mysite.com.conf and should contain this info

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    ServerName mysite.com
    ServerAlias www.mysite.com

    ServerAdmin [email protected]
    DocumentRoot /var/www/mysite

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory "/var/www/mysite">
Options All
AllowOverride All
Require all granted
</Directory>


    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

i faced the same issue while using eclipse kepler and maven version 3.2,

while building the project, it showed me the same error in eclipse

there are two versions (2.5 and 2.6) of plugin under

.m2/repository/org/apache/maven/plugins/maven-resources-plugin/

i removed 2.5 version then it worked for me

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

If you use vagrant, try this:

First remove config.php in current/vendor.

Run these command:

php artisan config:clear
php artisan clear-compiled
php artisan optimize

NOT RUN php artisan config:cache.

Hope this help.

Catch checked change event of a checkbox

For JQuery 1.7+ use:

$('input[type=checkbox]').on('change', function() {
  ...
});

How to shutdown my Jenkins safely?

Use http://[jenkins-server]/exit

This page shows how to use URL commands.

How to cache data in a MVC application

Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.

How do I discard unstaged changes in Git?

No matter what state your repo is in you can always reset to any previous commit:

git reset --hard <commit hash>

This will discard all changes which were made after that commit.

Django check for any exists for a query

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.


If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
try:
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(Header__id=qp.id).exists():
    ....

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Best Practices: working with long, multiline strings in PHP?

Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.

If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:

$text = "Hello, {$vars->name},\r\n\r\n"
    . "The second line starts two lines below.\r\n"
    . ".. Third line... etc";

This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.

How to fix error with xml2-config not found when installing PHP from sources?

For the latest versions it is needed to install libxml++2.6-dev like that:

apt-get install libxml++2.6-dev

Using different Web.config in development and production environment

You can also use the extension "Configuration Transform" works the same as "SlowCheetah",