Programs & Examples On #Processing efficiency

What are the benefits to marking a field as `readonly` in C#?

The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.

Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).

how to open a jar file in Eclipse

The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

You can customize this by using

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>

on web.xml, or remove this listener if you don't need one.

Set icon for Android application

Goto File->new->ImageAsset.

From their you can create Image Assets for your icon.

After that we will get icon image in mipmap different formats like hdpi,mdpi,xhdpi,xxhdpi,xxxhdpi.

Now goto AndroidManifest.xml

<application android:icon="@mipmap/your_Icon"> ....</application>

How can I change the text inside my <span> with jQuery?

$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');

text() if just text content. html() if it contains, well, html content.

Delete a single record from Entity Framework?

Employer employer = context.Employers.First(x => x.EmployerId == 1);

context.Customers.DeleteObject(employer);
context.SaveChanges();

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

Eclipse: stop code from running (java)

Open the Console view, locate the console for your running app and hit the Big Red Button.

Alternatively if you open the Debug perspective you will see all running apps in (by default) the top left. You can select the one that's causing you grief and once again hit the Big Red Button.enter image description here

Try catch statements in C

In C99, you can use setjmp/longjmp for non-local control flow.

Within a single scope, the generic, structured coding pattern for C in the presence of multiple resource allocations and multiple exits uses goto, like in this example. This is similar to how C++ implements destructor calls of automatic objects under the hood, and if you stick to this diligently, it should allow you for a certain degree of cleanness even in complex functions.

Performing Inserts and Updates with Dapper

you can do it in such way:

sqlConnection.Open();

string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
sqlConnection.Execute(sqlQuery,
    new
    {
        customerEntity.FirstName,
        customerEntity.LastName,
        customerEntity.Address,
        customerEntity.City
    });

sqlConnection.Close();

Rotating videos with FFmpeg

This script that will output the files with the directory structure under "fixedFiles". At the moment is fixed to MOV files and will execute a number of transformations depending on the original "rotation" of the video. Works with iOS captured videos on a Mac running Mavericks, but should be easily exportable. Relies on having installed both exiftool and ffmpeg.

#!/bin/bash

# rotation of 90 degrees. Will have to concatenate.
#ffmpeg -i <originalfile> -metadata:s:v:0 rotate=0 -vf "transpose=1" <destinationfile>
#/VLC -I dummy -vvv <originalfile> --sout='#transcode{width=1280,vcodec=mp4v,vb=16384,vfilter={canvas{width=1280,height=1280}:rotate{angle=-90}}}:std{access=file,mux=mp4,dst=<outputfile>}\' vlc://quit

#Allowing blanks in file names
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

#Bit Rate
BR=16384

#where to store fixed files
FIXED_FILES_DIR="fixedFiles"
#rm -rf $FIXED_FILES_DIR
mkdir $FIXED_FILES_DIR

# VLC
VLC_START="/Applications/VLC.app/Contents/MacOS/VLC -I dummy -vvv"
VLC_END="vlc://quit"


#############################################
# Processing of MOV in the wrong orientation
for f in `find . -regex '\./.*\.MOV'` 
do
  ROTATION=`exiftool "$f" |grep Rotation|cut -c 35-38`
  SHORT_DIMENSION=`exiftool "$f" |grep "Image Size"|cut -c 39-43|sed 's/x//'`
  BITRATE_INT=`exiftool "$f" |grep "Avg Bitrate"|cut -c 35-38|sed 's/\..*//'`
  echo Short dimension [$SHORT_DIMENSION] $BITRATE_INT

  if test "$ROTATION" != ""; then
    DEST=$(dirname ${f})
    echo "Processing $f with rotation $ROTATION in directory $DEST"
    mkdir -p $FIXED_FILES_DIR/"$DEST"

    if test "$ROTATION" == "0"; then
      cp "$f" "$FIXED_FILES_DIR/$f"

    elif test "$ROTATION" == "180"; then
#      $(eval $VLC_START \"$f\" "--sout="\'"#transcode{vfilter={rotate{angle=-"$ROTATION"}},vcodec=mp4v,vb=$BR}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
      $(eval ffmpeg -i \"$f\" -vf hflip,vflip -r 30 -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\")

    elif test "$ROTATION" == "270"; then
      $(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=2,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )

    else
#      $(eval $VLC_START \"$f\" "--sout="\'"#transcode{scale=1,width=$SHORT_DIMENSION,vcodec=mp4v,vb=$BR,vfilter={canvas{width=$SHORT_DIMENSION,height=$SHORT_DIMENSION}:rotate{angle=-"$ROTATION"}}}:std{access=file,mux=mp4,dst=\""$FIXED_FILES_DIR/$f"\"}'" $VLC_END )
      echo ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" 
      $(eval ffmpeg -i \"$f\" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:\(ow-iw\)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy \"$FIXED_FILES_DIR/$f\" )

    fi

  fi

echo 
echo ==================================================================
sleep 1
done

#############################################
# Processing of AVI files for my Panasonic TV
# Use ffmpegX + QuickBatch. Bitrate at 16384. Camera res 640x424
for f in `find . -regex '\./.*\.AVI'` 
do
  DEST=$(dirname ${f})
  DEST_FILE=`echo "$f" | sed 's/.AVI/.MOV/'`
  mkdir -p $FIXED_FILES_DIR/"$DEST"
  echo "Processing $f in directory $DEST"
  $(eval ffmpeg -i \"$f\" -r 20 -acodec libvo_aacenc -b:a 128k -vcodec mpeg4 -b:v 8M -flags +aic+mv4 \"$FIXED_FILES_DIR/$DEST_FILE\" )
echo 
echo ==================================================================

done

IFS=$SAVEIFS

MySQL create stored procedure syntax with delimiter

Here is the sample MYSQL Stored Procedure with delimiter and how to call..

DELIMITER $$

DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
  IN loc_username VARCHAR(255),
  IN loc_password VARCHAR(255)
)
BEGIN

  SELECT user_id,
         user_name,
         user_emailid,
         user_profileimage,
         last_update
    FROM tbl_user
   WHERE user_name = loc_username
     AND password = loc_password
     AND status = 1;

END $$

DELIMITER ;

and call by, mysql_connection specification and

$loginCheck="call sp_user_login('".$username."','".$password."');";

it will return the result from the procedure.

What are the most common naming conventions in C?

You should also think about the order of the words to make the auto name completion easier.

A good practice: library name + module name + action + subject

If a part is not relevant just skip it, but at least a module name and an action always should be presented.

Examples:

  • function name: os_task_set_prio, list_get_size, avg_get
  • define (here usually no action part): OS_TASK_PRIO_MAX

Java: Check if enum contains a given string?

With guava it's even simpler:

boolean isPartOfMyEnum(String myString){

return Lists.newArrayList(MyEnum.values().toString()).contains(myString);

}

Resolve Javascript Promise outside function scope

Many of the answers here are similar to the last example in this article. I am caching multiple Promises, and the resolve() and reject() functions can be assigned to any variable or property. As a result I am able to make this code slightly more compact:

function defer(obj) {
    obj.promise = new Promise((resolve, reject) => {
        obj.resolve = resolve;
        obj.reject  = reject;
    });
}

Here is a simplified example of using this version of defer() to combine a FontFace load Promise with another async process:

function onDOMContentLoaded(evt) {
    let all = []; // array of Promises
    glob = {};    // global object used elsewhere
    defer(glob);
    all.push(glob.promise);
    // launch async process with callback = resolveGlob()

    const myFont = new FontFace("myFont", "url(myFont.woff2)");
    document.fonts.add(myFont);
    myFont.load();
    all.push[myFont];
    Promise.all(all).then(() => { runIt(); }, (v) => { alert(v); });
}
//...
function resolveGlob() {
    glob.resolve();
}
function runIt() {} // runs after all promises resolved 

Update: 2 alternatives in case you want to encapsulate the object:

function defer(obj = {}) {
    obj.promise = new Promise((resolve, reject) => {
        obj.resolve = resolve;
        obj.reject  = reject;
    });
    return obj;
}
let deferred = defer();

and

class Deferred {
    constructor() {
        this.promise = new Promise((resolve, reject) => {
            this.resolve = resolve;
            this.reject  = reject;
        });
    }
}
let deferred = new Deferred();

How to set HTTP headers (for cache-control)?

To use cache-control in HTML, you use the meta tag, e.g.

<meta http-equiv="Cache-control" content="public">

The value in the content field is defined as one of the four values below.

Some information on the Cache-Control header is as follows

HTTP 1.1. Allowed values = PUBLIC | PRIVATE | NO-CACHE | NO-STORE.

Public - may be cached in public shared caches.
Private - may only be cached in private cache.
No-Cache - may not be cached.
No-Store - may be cached but not archived.

The directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server. This directive has the same semantics as the PRAGMA:NO-CACHE.

Clients SHOULD include both PRAGMA: NO-CACHE and CACHE-CONTROL: NO-CACHE when a no-cache request is sent to a server not known to be HTTP/1.1 compliant. Also see EXPIRES.

Note: It may be better to specify cache commands in HTTP than in META statements, where they can influence more than the browser, but proxies and other intermediaries that may cache information.

RSA Public Key format

You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ---- to -----BEGIN RSA PUBLIC KEY----- and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).

This article has a good explanation about both formats.

What you get in an RSA PUBLIC KEY is closer to the content of a PUBLIC KEY, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse and -strparse 19, as described in this answer.

EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER:

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim: INTEGER           :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
  265:d=1  hl=2 l=   3 prim: INTEGER           :010001

To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:

   The "ssh-rsa" key format has the following specific encoding:

      string    "ssh-rsa"
      mpint     e
      mpint     n

For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61. The first four bytes (00 00 00 07) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61=ssh-rsa, followed by the exponent of length 1 (00 00 00 01 25) and the modulus of length 256 (00 00 01 00 7f ...).

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

How to amend a commit without changing commit message (reusing the previous one)?

git commit -C HEAD --amend will do what you want. The -C option takes the metadata from another commit.

Remove stubborn underline from link

In my case, I had poorly formed HTML. The link was within a <u> tag, and not a <ul> tag.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

This code simply worked for me

System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox 54\\firefox.exe");
String Firefoxdriverpath = "C:\\Users\\Hp\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", Firefoxdriverpath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);

Is Fortran easier to optimize than C for heavy calculations?

I think the key point in favor of Fortran is that it is a language slightly more suited for expressing vector- and array-based math. The pointer analysis issue pointed out above is real in practice, since portable code cannot really assume that you can tell a compiler something. There is ALWAYS an advantage to expression computaitons in a manner closer to how the domain looks. C does not really have arrays at all, if you look closely, just something that kind of behaves like it. Fortran has real arrawys. Which makes it easier to compile for certain types of algorithms especially for parallel machines.

Deep down in things like run-time system and calling conventions, C and modern Fortran are sufficiently similar that it is hard to see what would make a difference. Note that C here is really base C: C++ is a totally different issue with very different performance characteristics.

Regex match one of two words

There are different regex engines but I think most of them will work with this:

apple|banana

Uploading Images to Server android

Main activity class to take pick and upload

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "Paste your URL here";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
       //ba1 = Base64.encodeBytes(ba);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }
}

php code to handle upload image and also create image from base64 encoded data

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
 echo "Image uploaded";
}else{
 echo "Error uploading image";
}
}
?>

jQuery - multiple $(document).ready ...?

Both will get called, first come first served. Take a look here.

$(document).ready(function(){
    $("#page-title").html("Document-ready was called!");
  });

$(document).ready(function(){
    $("#page-title").html("Document-ready 2 was called!");
  });

Output:

Document-ready 2 was called!

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

Right query to get the current number of connections in a PostgreSQL DB

Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)

select state, count(*) from pg_stat_activity  where pid <> pg_backend_pid() group by 1 order by 1;

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

Eloquent get only one column as an array

That can be done in short as:

Model::pluck('column')

where model is the Model such as User model & column as column name like id

if you do

User::pluck('id') // [1,2,3, ...]

& of course you can have any other clauses like where clause before pluck

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

How to use code to open a modal in Angular 2?

Simply, npm install --save @types/bootstrap try to match typing version with your bootstrap version. E.g. you have Bootstrap 4.3.1 then npm install --save @types/[email protected]

Disable mouse scroll wheel zoom on embedded Google Maps

Here's my take on the @nathanielperales answer extended by @chams, now extended again by me.

HTML

<div class='embed-container maps'>
    <iframe width='600' height='450' frameborder='0' src='http://foo.com'></iframe>
</div> 

jQuery

// we're doing so much with jQuery already, might as well set the initial state
$('.maps iframe').css("pointer-events", "none");

// as a safety, allow pointer events on click
$('.maps').click(function() {
  $(this).find('iframe').css("pointer-events", "auto");
});


$('.maps').mouseleave(function() {
  // set the default again on mouse out - disallow pointer events
  $(this).find('iframe').css("pointer-events", "none");
  // unset the comparison data so it doesn't effect things when you enter again
  $(this).removeData('oldmousepos');
});

$('.maps').bind('mousemove', function(e){
  $this = $(this);
  // check the current mouse X position
  $this.data('mousepos', e.pageX);
  // set the comparison data if it's null or undefined
  if ($this.data('oldmousepos') == null) {
    $this.data('oldmousepos', $this.data('mousepos'));
  }
  setTimeout(function(){
    // some left/right movement - allow pointer events
    if ($this.data('oldmousepos') != $this.data('mousepos')) {
      $this.find('iframe').css("pointer-events", "auto");
    }
    // set the compairison variable
    $this.data('oldmousepos', $this.data('mousepos'));
  }, 300);
  console.log($this.data('oldmousepos')+ ' ' + $this.data('mousepos'));
});

Checking if a folder exists (and creating folders) in Qt, C++

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

You can see more on Qt Documentation

How to get the next auto-increment id in mysql

You have to connect to MySQL and select a database before you can do this

$table_name = "myTable"; 
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'"); 
$row = mysql_fetch_array($query); 
$next_inc_value = $row["AUTO_INCREMENT"];  

Tracing XML request/responses with JAX-WS

with logback.xml configuration files, you can do :

<logger name="com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe" level="trace" additivity="false">
    <appender-ref ref="STDOUT"/>
</logger>

That will log the request and the response like this (depending on your configuration for the log output) :

09:50:23.266 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP request - http://xyz:8081/xyz.svc]---
Accept: application/soap+xml, multipart/related
Content-Type: application/soap+xml; charset=utf-8;action="http://xyz.Web.Services/IServiceBase/GetAccessTicket"
User-Agent: JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e
<?xml version="1.0" ?><S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">[CONTENT REMOVED]</S:Envelope>--------------------

09:50:23.312 [qtp1068445309-21] DEBUG c.s.x.i.w.t.h.c.HttpTransportPipe - ---[HTTP response - http://xyz:8081/xyz.svc - 200]---
null: HTTP/1.1 200 OK
Content-Length: 792
Content-Type: application/soap+xml; charset=utf-8
Date: Tue, 12 Feb 2019 14:50:23 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">[CONTENT REMOVED]</s:Envelope>--------------------

Xcode : Adding a project as a build dependency

Under TARGETS in your project, right-click on your project target (should be the same name as your project) and choose GET INFO, then on GENERAL tab you will see DIRECT DEPENDENCIES, simply click the [+] and select SoundCloudAPI.

Using jQuery to compare two arrays of Javascript objects

I don't think there's a good "jQuery " way to do this, but if you need efficiency, map one of the arrays by a certain key (one of the unique object fields), and then do comparison by looping through the other array and comparing against the map, or associative array, you just built.

If efficiency is not an issue, just compare every object in A to every object in B. As long as |A| and |B| are small, you should be okay.

Something like 'contains any' for Java set?

Use retainAll() in the Set interface. This method provides an intersection of elements common in both sets. See the API docs for more information.

Subtract two dates in Java

Assuming that you're constrained to using Date, you can do the following:

Date diff = new Date(d2.getTime() - d1.getTime());

Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date).

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

JavaScript error: "is not a function"

For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:

It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.

Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):

  • Missing script library
  • Typo
  • The function is within a scope that you currently do not have access to, e.g.:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
_x000D_
_x000D_

  • Your object/function does not have the function your calling:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
_x000D_
_x000D_

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           event.preventDefault();
           alert('it works!');
        }

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>
        </form>;
    }
});

Unable to compile class for JSP

Either you can Downgrade to JRE 1.7.49

or if you want to run on JRE 8

Step to fix:-

  • Go to Lib folder of Liferay Tomcat .

  • Replace :- ecj-3.7.2.jar with ecj-4.4.2.

  • Restart the Server

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I could not restart IIexpress. This is the solution that worked for me

  1. Cleaned the build
  2. Rebuild

How do I overload the [] operator in C#

public int this[int index]
{
    get => values[index];
}

What is the difference between a 'closure' and a 'lambda'?

Concept is same as described above, but if you are from PHP background, this further explain using PHP code.

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, function ($v) { return $v > 2; });

function ($v) { return $v > 2; } is the lambda function definition. We can even store it in a variable, so it can be reusable:

$max = function ($v) { return $v > 2; };

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, $max);

Now, what if you want to change the maximum number allowed in the filtered array? You would have to write another lambda function or create a closure (PHP 5.3):

$max_comp = function ($max) {
  return function ($v) use ($max) { return $v > $max; };
};

$input = array(1, 2, 3, 4, 5);
$output = array_filter($input, $max_comp(2));

A closure is a function that is evaluated in its own environment, which has one or more bound variables that can be accessed when the function is called. They come from the functional programming world, where there are a number of concepts in play. Closures are like lambda functions, but smarter in the sense that they have the ability to interact with variables from the outside environment of where the closure is defined.

Here is a simpler example of PHP closure:

$string = "Hello World!";
$closure = function() use ($string) { echo $string; };

$closure();

Nicely explained in this article.

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Best algorithm for detecting cycles in a directed graph

If a graph satisfy this property

|e| > |v| - 1

then the graph contains at least on cycle.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

Determine the type of an object?

As an aside to the previous answers, it's worth mentioning the existence of collections.abc which contains several abstract base classes (ABCs) that complement duck-typing.

For example, instead of explicitly checking if something is a list with:

isinstance(my_obj, list)

you could, if you're only interested in seeing if the object you have allows getting items, use collections.abc.Sequence:

from collections.abc import Sequence
isinstance(my_obj, Sequence) 

if you're strictly interested in objects that allow getting, setting and deleting items (i.e mutable sequences), you'd opt for collections.abc.MutableSequence.

Many other ABCs are defined there, Mapping for objects that can be used as maps, Iterable, Callable, et cetera. A full list of all these can be seen in the documentation for collections.abc.

Does C have a "foreach" loop construct?

C doesn't have a foreach, but macros are frequently used to emulate that:

#define for_each_item(item, list) \
    for(T * item = list->head; item != NULL; item = item->next)

And can be used like

for_each_item(i, processes) {
    i->wakeup();
}

Iteration over an array is also possible:

#define foreach(item, array) \
    for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
        keep && count != size; \
        keep = !keep, count++) \
      for(item = (array) + count; keep; keep = !keep)

And can be used like

int values[] = { 1, 2, 3 };
foreach(int *v, values) {
    printf("value: %d\n", *v);
}

Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

Converting any object to a byte array in java

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

Perhaps you could use something like this?

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

Opposite of %in%: exclude rows with values specified in a vector

The help for %in%, help("%in%"), includes, in the Examples section, this definition of not in,

"%w/o%" <- function(x, y) x[!x %in% y] #-- x without y

Lets try it:

c(2,3,4) %w/o% c(2,8,9)
[1] 3 4

Alternatively

"%w/o%" <- function(x, y) !x %in% y #--  x without y
c(2,3,4) %w/o% c(2,8,9)
# [1] FALSE  TRUE  TRUE

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

I had a similar problem. I created a new repository, NOT IN THE DIRECTORY THAT I WANTED TO MAKE A REPOSITORY. I then copied the files created to the directory I wanted to make a repository. Then open an existing repository using the directory I just copied the files to.

NOTE: I did use github desktop to make and open exiting repository.

error running apache after xampp install

I got the same error when xampp was installed on windows 10.

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

So I opened httpd-ssl.conf file in xampp folder and changed the following line

ServerName www.example.com:443

To

ServerName localhost

And the problem was fixed.

JS how to cache a variable

You have three options:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  3. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)

Ignore invalid self-signed ssl certificate in node.js with https.request?

Adding to @Armand answer:

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0 e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0 (with great thanks to Juanra)

If you on windows usage:

set NODE_TLS_REJECT_UNAUTHORIZED=0

Thanks to: @weagle08

How do I setup a SSL certificate for an express.js server?

See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):

var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );

https.createServer({
    key: privateKey,
    cert: certificate
}, app).listen(port);

Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Can't push to GitHub because of large file which I already deleted

rather than doing complicated stuff, copy your repo (on your computer) to another place. delete the large file. do a couple of push and pull. Then some of your files will be messed up having things like "<<<<<< HEAD". Just copy your backup into the old folder on the disk. Do another add, commit, push!

Adding a directory to the PATH environment variable in Windows

  • Command line changes will not be permanent and will be lost when the console closes.
  • The path works like first comes first served.
  • You may want to override other already included executables. For instance, if you already have another version on your path and you want to add different version without making a permanent change on path, you should put the directory at the beginning of the command.

To override already included executables;

set PATH=C:\xampp\php;%PATH%;

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

Alter MySQL table to add comments on columns

try:

 ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'  

How do I install SciPy on 64 bit Windows?

Try to install Python 2.6.3 over your 2.6.2 (this should also add correct Registry entry), or to register your existing installation using this script. Installer should work after that.

Building SciPy requires a Fortran compiler and libraries - BLAS and LAPACK.

How to run a cronjob every X minutes?

If you want to run a cron every n minutes, there are a few possible options depending on the value of n.

n divides 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)

Here, the solution is straightforward by making use of the / notation:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
m-59/n  *  *  *  *   command

In the above, n represents the value n and m represents a value smaller than n or *. This will execute the command at the minutes m,m+n,m+2n,...

n does NOT divide 60

If n does not divide 60, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC. Let's say we want to start to run the command the first time when Marty McFly arrived in Riverdale and then repeat it every n minutes later.

% date -d '2015-10-21 07:28:00' +%s 
1445412480

For a cronjob to run every 42nd minute after `2015-10-21 07:28:00', the crontab would look like this:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *   command to be executed
  *  *  *  *  *   minutetestcmd "2015-10-21 07:28:00" 42 && command

with minutetestcmd defined as

#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))

Remark: UNIX time is not influenced by leap seconds

Remark: cron has no sub-second accuracy

What does java.lang.Thread.interrupt() do?

If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Update May 28th, 2017: This method is no longer supported by me and doesn't work anymore as far as I know. Don't try it.


# How To Add Google Apps and ARM Support to Genymotion v2.0+ #

Original Source: [GUIDE] Genymotion | Installing ARM Translation and GApps - XDA-Developers

Note(Feb 2nd): Contrary to previous reports, it's been discovered that Android 4.4 does in fact work with ARM translation, although it is buggy. Follow the steps the same as before, just make sure you download the 4.4 GApps.

UPDATE-v1.1: I've gotten more up-to-date builds of libhoudini and have updated the ZIP file. This fixes a lot of app crashes and hangs. Just flash the new one, and it should work.


This guide is for getting back both ARM translation/support (this is what causes the "INSTALL_FAILED_CPU_ABI_INCOMPATIBLE" errors) and Google Play apps in your Genymotion VM.

  1. Download the following ZIPs:
  2. Next open your Genymotion VM and go to the home screen
  3. Now drag&drop the Genymotion-ARM-Translation_v1.1.zip onto the Genymotion VM window.
  4. It should say "File transfer in progress". Once it asks you to flash it, click 'OK'.
  5. Now reboot your VM using ADB (adb reboot) or an app like ROM Toolbox. If nescessary you can simply close the VM window, but I don't recommend it.
  6. Once you're on the home screen again drag&drop the gapps-*-signed.zip (the name varies) onto your VM, and click 'OK' when asked.
  7. Once it finishes, again reboot your VM and open the Google Play Store.
  8. Sign in using your Google account
  9. Once in the Store go to the 'My Apps' menu and let everything update (it fixes a lot of issues). Also try updating Google Play Services directly.
  10. Now try searching for 'Netflix' and 'Google Drive'
  11. If both apps show up in the results and you're able to Download/Install them, then congratulations: you now have ARM support and Google Play fully set up!

I've tested this on Genymotion v2.0.1-v2.1 using Android 4.3 and 4.4 images. Feel free to skip the GApps steps if you only want the ARM support. It'll work perfectly fine by itself.


Old Zips: v1.0. Don't download these as they will not solve your issues. It is left for archival and experimental purposes.

How can I convert a .jar to an .exe?

Launch4j works on both Windows and Linux/Mac. But if you're running Linux/Mac, there is a way to embed your jar into a shell script that performs the autolaunch for you, so you have only one runnable file:

exestub.sh:

#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt  0 -a -f "$0" ] && MYSELF="./$0"
JAVA_OPT=""
PROG_OPT=""
# Parse options to determine which ones are for Java and which ones are for the Program
while [ $# -gt 0 ] ; do
    case $1 in
        -Xm*) JAVA_OPT="$JAVA_OPT $1" ;;
        -D*)  JAVA_OPT="$JAVA_OPT $1" ;;
        *)    PROG_OPT="$PROG_OPT $1" ;;
    esac
    shift
done
exec java $JAVA_OPT -jar $MYSELF $PROG_OPT

Then you create your runnable file from your jar:

$ cat exestub.sh myrunnablejar.jar > myrunnable
$ chmod +x myrunnable

It works the same way launch4j works: because a jar has a zip format, which header is located at the end of the file. You can have any header you want (either binary executable or, like here, shell script) and run java -jar <myexe>, as <myexe> is a valid zip/jar file.

Add target="_blank" in CSS

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


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

Should 'using' directives be inside or outside the namespace?

There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using statements and has to be fully qualified.

Consider:

namespace MyNamespace
{
    using System;
    using MyAlias = System.DateTime;

    class MyClass
    {
    }
}

versus:

using System;

namespace MyNamespace
{
    using MyAlias = DateTime;

    class MyClass
    {
    }
}

This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):

using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;

With using statements inside the namespace, it suddenly becomes:

using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;

Not pretty.

Git reset --hard and push to remote repository

For users of GitHub, this worked for me:

  1. In any branch protection rules where you wish to make the change, make sure Allow force pushes is enabled
  2. git reset --hard <full_hash_of_commit_to_reset_to>
  3. git push --force

This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.

All everyone else needs to do is the git reset command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.

find without recursion

I think you'll get what you want with the -maxdepth 1 option, based on your current command structure. If not, you can try looking at the man page for find.

Relevant entry (for convenience's sake):

-maxdepth levels
          Descend at most levels (a non-negative integer) levels of direc-
          tories below the command line arguments.   `-maxdepth  0'  means
          only  apply the tests and actions to the command line arguments.

Your options basically are:

# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f

Or:

#  DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f

Add a custom attribute to a Laravel / Eloquent model on load?

If you rename your getAvailability() method to getAvailableAttribute() your method becomes an accessor and you'll be able to read it using ->available straight on your model.

Docs: https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators

EDIT: Since your attribute is "virtual", it is not included by default in the JSON representation of your object.

But I found this: Custom model accessors not processed when ->toJson() called?

In order to force your attribute to be returned in the array, add it as a key to the $attributes array.

class User extends Eloquent {
    protected $attributes = array(
        'ZipCode' => '',
    );

    public function getZipCodeAttribute()
    {
        return ....
    }
}

I didn't test it, but should be pretty trivial for you to try in your current setup.

Downloading a large file using curl

Find below code if you want to download the contents of the specified URL also want to saves it to a file.

<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');

$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_exec ($ch);

curl_close ($ch);
fclose($fp);
?>

If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>

Defining static const integer members in class definition

Not just int's. But you can't define the value in the class declaration. If you have:

class classname
{
    public:
       static int const N;
}

in the .h file then you must have:

int const classname::N = 10;

in the .cpp file.

What is a "bundle" in an Android application

Bundle is used to pass data between Activities. You can create a bundle, pass it to Intent that starts the activity which then can be used from the destination activity.

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Apache Solr


Apart from answering OP's queries, Let me throw some insights on Apache Solr from simple introduction to detailed installation and implementation.

Simple Introduction


Anyone who has had experience with the search engines above, or other engines not in the list -- I would love to hear your opinions.

Solr shouldn't be used to solve real-time problems. For search engines, Solr is pretty much game and works flawlessly.

Solr works fine on High Traffic web-applications (I read somewhere that it is not suited for this, but I am backing up that statement). It utilizes the RAM, not the CPU.

  • result relevance and ranking

The boost helps you rank your results show up on top. Say, you're trying to search for a name john in the fields firstname and lastname, and you want to give relevancy to the firstname field, then you need to boost up the firstname field as shown.

http://localhost:8983/solr/collection1/select?q=firstname:john^2&lastname:john

As you can see, firstname field is boosted up with a score of 2.

More on SolrRelevancy

  • searching and indexing speed

The speed is unbelievably fast and no compromise on that. The reason I moved to Solr.

Regarding the indexing speed, Solr can also handle JOINS from your database tables. A higher and complex JOIN do affect the indexing speed. However, an enormous RAM config can easily tackle this situation.

The higher the RAM, The faster the indexing speed of Solr is.

  • ease of use and ease of integration with Django

Never attempted to integrate Solr and Django, however you can achieve to do that with Haystack. I found some interesting article on the same and here's the github for it.

  • resource requirements - site will be hosted on a VPS, so ideally the search engine wouldn't require a lot of RAM and CPU

Solr breeds on RAM, so if the RAM is high, you don't to have to worry about Solr.

Solr's RAM usage shoots up on full-indexing if you have some billion records, you could smartly make use of Delta imports to tackle this situation. As explained, Solr is only a near real-time solution.

  • scalability

Solr is highly scalable. Have a look on SolrCloud. Some key features of it.

  • Shards (or sharding is the concept of distributing the index among multiple machines, say if your index has grown too large)
  • Load Balancing (if Solrj is used with Solr cloud it automatically takes care of load-balancing using it's Round-Robin mechanism)
  • Distributed Search
  • High Availability
  • extra features such as "did you mean?", related searches, etc

For the above scenario, you could use the SpellCheckComponent that is packed up with Solr. There are a lot other features, The SnowballPorterFilterFactory helps to retrieve records say if you typed, books instead of book, you will be presented with results related to book.


This answer broadly focuses on Apache Solr & MySQL. Django is out of scope.

Assuming that you are under LINUX environment, you could proceed to this article further. (mine was an Ubuntu 14.04 version)

Detailed Installation

Getting Started

Download Apache Solr from here. That would be version is 4.8.1. You could download new versions, I found this stable.

After downloading the archive , extract it to a folder of your choice. Say .. Downloads or whatever.. So it will look like Downloads/solr-4.8.1/

On your prompt.. Navigate inside the directory

shankar@shankar-lenovo: cd Downloads/solr-4.8.1

So now you are here ..

shankar@shankar-lenovo: ~/Downloads/solr-4.8.1$

Start the Jetty Application Server

Jetty is available inside the examples folder of the solr-4.8.1 directory , so navigate inside that and start the Jetty Application Server.

shankar@shankar-lenovo:~/Downloads/solr-4.8.1/example$ java -jar start.jar

Now , do not close the terminal , minimize it and let it stay aside.

( TIP : Use & after start.jar to make the Jetty Server run in the background )

To check if Apache Solr runs successfully, visit this URL on the browser. http://localhost:8983/solr

Running Jetty on custom Port

It runs on the port 8983 as default. You could change the port either here or directly inside the jetty.xml file.

java -Djetty.port=9091 -jar start.jar

Download the JConnector

This JAR file acts as a bridge between MySQL and JDBC , Download the Platform Independent Version here

After downloading it, extract the folder and copy themysql-connector-java-5.1.31-bin.jar and paste it to the lib directory.

shankar@shankar-lenovo:~/Downloads/solr-4.8.1/contrib/dataimporthandler/lib

Creating the MySQL table to be linked to Apache Solr

To put Solr to use, You need to have some tables and data to search for. For that, we will use MySQL for creating a table and pushing some random names and then we could use Solr to connect to MySQL and index that table and it's entries.

1.Table Structure

CREATE TABLE test_solr_mysql
 (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(45) NULL,
  created TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
 );

2.Populate the above table

INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jean');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jack');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jason');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Vego');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Grunt');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jasper');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Fred');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jenna');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Rebecca');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Roland');

Getting inside the core and adding the lib directives

1.Navigate to

shankar@shankar-lenovo: ~/Downloads/solr-4.8.1/example/solr/collection1/conf

2.Modifying the solrconfig.xml

Add these two directives to this file..

  <lib dir="../../../contrib/dataimporthandler/lib/" regex=".*\.jar" />
  <lib dir="../../../dist/" regex="solr-dataimporthandler-\d.*\.jar" />

Now add the DIH (Data Import Handler)

<requestHandler name="/dataimport" 
  class="org.apache.solr.handler.dataimport.DataImportHandler" >
    <lst name="defaults">
      <str name="config">db-data-config.xml</str>
    </lst>
</requestHandler>

3.Create the db-data-config.xml file

If the file exists then ignore, add these lines to that file. As you can see the first line, you need to provide the credentials of your MySQL database. The Database name, username and password.

<dataConfig>
    <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/yourdbname" user="dbuser" password="dbpass"/>
    <document>
   <entity name="test_solr" query="select CONCAT('test_solr-',id) as rid,name from test_solr_mysql WHERE '${dataimporter.request.clean}' != 'false'
      OR `created` > '${dataimporter.last_index_time}'" >
    <field name="id" column="rid" />
    <field name="solr_name" column="name" />
    </entity>
   </document>
</dataConfig>

( TIP : You can have any number of entities but watch out for id field, if they are same then indexing will skipped. )

4.Modify the schema.xml file

Add this to your schema.xml as shown..

<uniqueKey>id</uniqueKey>
<field name="solr_name" type="string" indexed="true" stored="true" />

Implementation

Indexing

This is where the real deal is. You need to do the indexing of data from MySQL to Solr inorder to make use of Solr Queries.

Step 1: Go to Solr Admin Panel

Hit the URL http://localhost:8983/solr on your browser. The screen opens like this.

This is the main Apache Solr Administration Panel

As the marker indicates, go to Logging inorder to check if any of the above configuration has led to errors.

Step 2: Check your Logs

Ok so now you are here, As you can there are a lot of yellow messages (WARNINGS). Make sure you don't have error messages marked in red. Earlier, on our configuration we had added a select query on our db-data-config.xml, say if there were any errors on that query, it would have shown up here.

This is the logging section of your Apache Solr engine

Fine, no errors. We are good to go. Let's choose collection1 from the list as depicted and select Dataimport

Step 3: DIH (Data Import Handler)

Using the DIH, you will be connecting to MySQL from Solr through the configuration file db-data-config.xml from the Solr interface and retrieve the 10 records from the database which gets indexed onto Solr.

To do that, Choose full-import , and check the options Clean and Commit. Now click Execute as shown.

Alternatively, you could use a direct full-import query like this too..

http://localhost:8983/solr/collection1/dataimport?command=full-import&commit=true

The Data Import Handler

After you clicked Execute, Solr begins to index the records, if there were any errors, it would say Indexing Failed and you have to go back to the Logging section to see what has gone wrong.

Assuming there are no errors with this configuration and if the indexing is successfully complete., you would get this notification.

Indexing Success

Step 4: Running Solr Queries

Seems like everything went well, now you could use Solr Queries to query the data that was indexed. Click the Query on the left and then press Execute button on the bottom.

You will see the indexed records as shown.

The corresponding Solr query for listing all the records is

http://localhost:8983/solr/collection1/select?q=*:*&wt=json&indent=true

The indexed data

Well, there goes all 10 indexed records. Say, we need only names starting with Ja , in this case, you need to target the column name solr_name, Hence your query goes like this.

http://localhost:8983/solr/collection1/select?q=solr_name:Ja*&wt=json&indent=true

The JSON data starting with Ja*

That's how you write Solr Queries. To read more about it, Check this beautiful article.

Convert String with Dot or Comma as decimal separator to number in JavaScript

All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.

function detectFloat(source) {
    let float = accounting.unformat(source);
    let posComma = source.indexOf(',');
    if (posComma > -1) {
        let posDot = source.indexOf('.');
        if (posDot > -1 && posComma > posDot) {
            let germanFloat = accounting.unformat(source, ',');
            if (Math.abs(germanFloat) > Math.abs(float)) {
                float = germanFloat;
            }
        } else {
            // source = source.replace(/,/g, '.');
            float = accounting.unformat(source, ',');
        }
    }
    return float;
}

This was tested with the following cases:

        const cases = {
            "0": 0,
            "10.12": 10.12,
            "222.20": 222.20,
            "-222.20": -222.20,
            "+222,20": 222.20,
            "-222,20": -222.20,
            "-2.222,20": -2222.20,
            "-11.111,20": -11111.20,
        };

Suggestions welcome.

How to use ClassLoader.getResources() correctly?

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

How should I use Outlook to send code snippets?

When I paste code into Outlook or have sentences containing code or technical syntax I get annoyed by all of the red squiggles that identify spelling errors. If you want Outlook to clear all of the red spellcheck squiggles you can add a button to the Quick Access Toolbar that calls a VBA macro and removes all squiggles from the current document.

I prefer to run this macro separate from my style choice because I often use it on a selection of text that has mixed content.

For syntax highlighting I use the Notepad++ technique already listed by @srujanreddy, though I discovered that the right-click context menu option a bit handier than navigating the Plugins menu.

Image showing you can right-click on selected text and choose to copy text with syntax highlighting

If you get annoyed by spell check while you are preparing your email you can add a button to your quick access toolbar that will remove the red squiggles from the message body.
See this article: https://stackoverflow.com/a/49865743/1898524

Remove Spell Check Squiggles

Assigning strings to arrays of characters

You can use this:

yylval.sval=strdup("VHDL + Volcal trance...");

Where yylval is char*. strdup from does the job.

Python 3.4.0 with MySQL database

sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient

that worked for me!

PHP __get and __set magic methods

I'd recommend to use an array for storing all values via __set().

class foo {

    protected $values = array();

    public function __get( $key )
    {
        return $this->values[ $key ];
    }

    public function __set( $key, $value )
    {
        $this->values[ $key ] = $value;
    }

}

This way you make sure, that you can't access the variables in another way (note that $values is protected), to avoid collisions.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

Vba macro to copy row from table if value in table meets condition

Selects are slow and unnescsaary. The following code will be far faster:

Sub CopyRowsAcross() 
Dim i As Integer 
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1") 
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2") 

For i = 2 To ws1.Range("B65536").End(xlUp).Row 
    If ws1.Cells(i, 2) = "Your Critera" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1) 
Next i 
End Sub 

java: use StringBuilder to insert at the beginning

Maybe I'm missing something but you want to wind up with a String that looks like this, "999897969594...543210", correct?

StringBuilder sb = new StringBuilder();
for(int i=99;i>=0;i--){
    sb.append(String.valueOf(i));
}

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

What's the difference between nohup and ampersand

Correct me if I'm wrong

  nohup myprocess.out &

nohup catches the hangup signal, which mean it will send a process when terminal closed.

 myprocess.out &

Process can run but will stopped once the terminal is closed.

nohup myprocess.out

Process able to run even terminal closed, but you are able to stop the process by pressing ctrl + z in terminal. Crt +z not working if & is existing.

100% Min Height CSS layout

Probably the shortest solution (works only in modern browsers)

This small piece of CSS makes "the middle content part fill 100% of the space in between with the footer fixed to the bottom":

html, body { height: 100%; }
your_container { min-height: calc(100% - height_of_your_footer); }

the only requirement is that you need to have a fixed height footer.

For example for this layout:

    <html><head></head><body>
      <main> your main content </main>
      </footer> your footer content </footer>
    </body></html>

you need this CSS:

    html, body { height: 100%; }
    main { min-height: calc(100% - 2em); }
    footer { height: 2em; }

How to get MD5 sum of a string using python?

Have you tried using the MD5 implementation in hashlib? Note that hashing algorithms typically act on binary data rather than text data, so you may want to be careful about which character encoding is used to convert from text to binary data before hashing.

The result of a hash is also binary data - it looks like Flickr's example has then been converted into text using hex encoding. Use the hexdigest function in hashlib to get this.

Download and open PDF file using Ajax

What worked for me is the following code, as the server function is retrieving File(memoryStream.GetBuffer(), "application/pdf", "fileName.pdf");:

$http.get( fullUrl, { responseType: 'arraybuffer' })
            .success(function (response) {
                var blob = new Blob([response], { type: 'application/pdf' });

                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob); // for IE
                }
                else {
                    var fileURL = URL.createObjectURL(blob);
                    var newWin = window.open(fileURL);
                    newWin.focus();
                    newWin.reload();
                }
});

How to get different colored lines for different plots in a single figure?

Matplotlib does this by default.

E.g.:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Basic plot with legend

If you want to control the colors that will be cycled through:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Unique colors for 20 lines based on a given colormap

How do I revert my changes to a git submodule?

my way to reset all submodules (WITHOUT detaching & keeping their "master" branch):

git submodule foreach 'git checkout master && git reset --hard $sha1'

What is the difference between document.location.href and document.location?

document.location is an object, while document.location.href is a string. But the former has a toString method, so you can read from it as if it was a string and get the same value as document.location.href.

In some browsers - most modern ones, I think - you can also assign to document.location as if it were a string. According to the Mozilla documentation however, it is better to use window.location for this purpose as document.location was originally read-only and so may not be as widely supported.

Makefile ifeq logical or

Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:

ifeq ($(shell test ".$(GCC_MINOR)" = .4  -o  \
                   ".$(GCC_MINOR)" = .5  -o  \
                   ".$(TODAY)"     = .Friday  &&  printf "true"), true)
    CFLAGS += -fno-strict-overflow
endif

Visual Studio 2015 is very slow

Update PC Drivers

In my case, and I had bad lag doing the simplest of things, it helped to update my pc drivers. The system drivers are the foundation for everything.

I was fortunate that I have Dell and they have awesome website support to do this. I googled

dell <my model name> update drivers

or go to the drivers home page

I let it update all the drivers it wanted to (Dell driver update is pretty much automatic).

Much of the lag seems to have gone away.

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Iterator over HashMap in Java

You are getting a keySet iterator on the HashMap and expecting to iterate over entries.

Correct code:

    HashMap hm = new HashMap();

    hm.put(0, "zero");
    hm.put(1, "one");

    //Here we get the keyset iterator not the Entry iterator
    Iterator iter = (Iterator) hm.keySet().iterator();

    while(iter.hasNext()) {

        //iterator's next() return an Integer that is the key
        Integer key = (Integer) iter.next();
        //already have the key, now get the value using get() method
        System.out.println(key + " - " + hm.get(key));

    }

Iterating over a HashMap using EntrySet:

     HashMap hm = new HashMap();
     hm.put(0, "zero");
     hm.put(1, "one");
     //Here we get the iterator on the entrySet
     Iterator iter = (Iterator) hm.entrySet().iterator();


     //Traversing using iterator on entry set  
     while (iter.hasNext()) {  
         Entry<Integer,String> entry = (Entry<Integer,String>) iter.next();  
         System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
     }  

     System.out.println();


    //Iterating using for-each construct on Entry Set
    Set<Entry<Integer, String>> entrySet = hm.entrySet();
    for (Entry<Integer, String> entry : entrySet) {  
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
    }           

Look at the section -Traversing Through a HashMap in the below link. java-collection-internal-hashmap and Traversing through HashMap

Contain an image within a div?

  <div id ="container">
    <img src = "http://animalia-life.com/data_images/duck/duck9.jpg"/>
#container img {
        max-width:250px;
        max-height:250px;
        width: 250px;
        height: 250px;
        border:1px solid #000;
    }

The img will lose aspect ratio

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

How do I download the Android SDK without downloading Android Studio?

Sadly, straight from google, which is where you will want to download if your company firewall blocks other sources, Release 1.6 r1 September 2009 is the latest SDK they have.

Convert laravel object to array

UPDATE since version 5.4 of Laravel it is no longer possible.

You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

DB::setFetchMode(PDO::FETCH_ASSOC);

// then
DB::table(..)->get(); // array of arrays instead of objects

// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);

For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

Event::listen(StatementPrepared::class, function ($event) {
    $event->statement->setFetchMode(...);
});

Token based authentication in Web API without any user interface

ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

All you have to do is to post URL encoded username and password inside query string.

/Token/userName=johndoe%40example.com&password=1234&grant_type=password

If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.

Get last record of a table in Postgres

If you accept a tip, create an id in this table like serial. The default of this field will be:

nextval('table_name_field_seq'::regclass).

So, you use a query to call the last register. Using your example:

pg_query($connection, "SELECT currval('table_name_field_seq') AS id;

I hope this tip helps you.

Inline instantiation of a constant List

const is for compile-time constants. You could just make it static readonly, but that would only apply to the METRICS variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");

You may want to use a ReadOnlyCollection<T> to wrap it. For example:

public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
    (new List<String> { 
         SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
         SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
         SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });

ReadOnlyCollection<T> just wraps a potentially-mutable collection, but as nothing else will have access to the List<T> afterwards, you can regard the overall collection as immutable.

(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)

Whether you declare it as IList<string>, IEnumerable<string>, ReadOnlyCollection<string> or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string> would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T> may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T> could be handy - but inflexible.

How can I trim beginning and ending double quotes from a string?

Groovy

You can subtract a substring from a string using a regular expression in groovy:

String unquotedString = theString - ~/^"/ - ~/"$/

How to change default text file encoding in Eclipse?

To change the default encoding used for all workspaces you can do the following:

Create a defaults.ini file in the Eclipse configuration folder. For example, if Eclipse is installed in C:/Eclipse create C:/Eclipse/configuration/defaults.ini. The file should contain:

org.eclipse.core.resources/encoding=UTF-8

If you want to set the line terminator to UNIX values you can also add:

org.eclipse.core.runtime/line.separator=\n

In eclipse.ini in the Eclipse install folder (e.g., C:/Eclipse) add the following lines:

-plugincustomization 
D:/Java/Eclipse/configuration/defaults.ini

You might need to play around with where you put it. Inserting it before the "-product" option seemed to work.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="author" content="Sandro Alvares - KingRider">
    </head>
    <body>
        <style type="text/css">
            li.title { 
                font-size: 20px; 
                font-weight: lighter; 
                padding: 15px; 
                counter-increment: ordem; 
            }
            .foo { 
                counter-reset: foo; 
                padding-left: 15px; 
            }
            .foo li { 
                list-style-type: none; 
            }
            .foo li:before { 
                counter-increment: foo; 
                content: counter(ordem) "." counter(foo) " "; 
            }
        </style>
        <ol>
            <li class="title">TITLE ONE</li>
            <ol class="foo">
                <li>text 1 one</li>
                <li>text 1 two</li>
                <li>text 1 three</li>
                <li>text 1 four</li>
            </ol>
            <li class="title">TITLE TWO</li>
            <ol class="foo">
                <li>text 2 one</li>
                <li>text 2 two</li>
                <li>text 2 three</li>
                <li>text 2 four</li>
            </ol>
            <li class="title">TITLE THREE</li>
            <ol class="foo">
                <li>text 3 one</li>
                <li>text 3 two</li>
                <li>text 3 three</li>
                <li>text 3 four</li>
            </ol>
        </ol>
    </body>
</html>

Result: http://i.stack.imgur.com/78bN8.jpg

Show which git tag you are on?

Show all tags on current HEAD (or commit)

git tag --points-at HEAD

navbar color in Twitter Bootstrap

If you havent got time to learn "less" or do it properly, here's a dirty hack...

Add this above where you render the bootstrap nav bar HTML - update the colours as required..

<style type="text/css">   

.navbar-inner {
    background-color: red;
    background-image: linear-gradient(to bottom, blue, green);
    background-repeat: repeat-x;
    border: 1px solid yellow;
    border-radius: 4px 4px 4px 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.067);
    min-height: 40px;
    padding-left: 20px;
    padding-right: 20px;
}

.dropdown-menu {
    background-clip: padding-box;
    background-color: red;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 6px 6px 6px 6px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    display: none;
    float: left;
    left: 0;
    list-style: none outside none;
    margin: 2px 0 0;
    min-width: 160px;
    padding: 5px 0;
    position: absolute;
    top: 100%;
    z-index: 1000;
}

.btn-group.open .btn.dropdown-toggle {
  background-color: red;
}

.btn-group.open .btn.dropdown-toggle {
  background-color:lime;
}

.navbar .nav li.dropdown.open > .dropdown-toggle,
.navbar .nav li.dropdown.active > .dropdown-toggle,
.navbar .nav li.dropdown.open.active > .dropdown-toggle {
  color:white;
  background-color:Teal;
}

.navbar .nav > li > a {
    color: white;
    float: none;
    padding: 10px 15px;
    text-decoration: none;
    text-shadow: 0 0px 0 #ffffff;
}

.navbar .brand {
  display: block;
  float: left;
  padding: 10px 20px 10px;
  margin-left: -20px;
  font-size: 20px;
  font-weight: 200;
  color: white;
  text-shadow: 0 0px 0 #ffffff;
}

.navbar .nav > li > a:focus,
.navbar .nav > li > a:hover {
  color: white;
  text-decoration: none;
  background-color: transparent;
}

.navbar-text {
  margin-bottom: 0;
  line-height: 40px;
  color: white;
}

.dropdown-menu li > a {
  display: block;
  padding: 3px 20px;
  clear: both;
  font-weight: normal;
  line-height: 20px;
  color: white;
  white-space: nowrap;
}

.navbar-link {
  color: white;
}

.navbar-link:hover {
  color: white;
}

</style>

Compare 2 arrays which returns difference

This should work with unsorted arrays, double values and different orders and length, while giving you the filtered values form array1, array2, or both.

function arrayDiff(arr1, arr2) {
    var diff = {};

    diff.arr1 = arr1.filter(function(value) {
        if (arr2.indexOf(value) === -1) {
            return value;
        }
    });

    diff.arr2 = arr2.filter(function(value) {
        if (arr1.indexOf(value) === -1) {
            return value;
        }
    });

    diff.concat = diff.arr1.concat(diff.arr2);

    return diff;
};

var firstArray = [1,2,3,4];
var secondArray = [4,6,1,4];

console.log( arrayDiff(firstArray, secondArray) );
console.log( arrayDiff(firstArray, secondArray).arr1 );
// => [ 2, 3 ]
console.log( arrayDiff(firstArray, secondArray).concat );
// => [ 2, 3, 6 ]

Get the year from specified date php

I would use this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

It appears the date is coming from a source where it is always the same, much quicker this way using explode.

How to zoom in/out an UIImage object when user pinches screen?

The simplest way to do this, if all you want is pinch zooming, is to place your image inside a UIWebView (write small amount of html wrapper code, reference your image, and you're basically done). The more complcated way to do this is to use touchesBegan, touchesMoved, and touchesEnded to keep track of the user's fingers, and adjust your view's transform property appropriately.

Python memory leaks

As far as best practices, keep an eye for recursive functions. In my case I ran into issues with recursion (where there didn't need to be). A simplified example of what I was doing:

def my_function():
    # lots of memory intensive operations
    # like operating on images or huge dictionaries and lists
    .....
    my_flag = True
    if my_flag:  # restart the function if a certain flag is true
        my_function()

def main():
    my_function()

operating in this recursive manner won't trigger the garbage collection and clear out the remains of the function, so every time through memory usage is growing and growing.

My solution was to pull the recursive call out of my_function() and have main() handle when to call it again. this way the function ends naturally and cleans up after itself.

def my_function():
    # lots of memory intensive operations
    # like operating on images or huge dictionaries and lists
    .....
    my_flag = True
    .....
    return my_flag

def main():
    result = my_function()
    if result:
        my_function()

Get names of all keys in the collection

I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq to return a list of the keys.

var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());

Repeat a task with a time delay?

Timer works fine. Here, I use Timer to search text after 1.5s and update UI. Hope that helps.

private Timer _timer = new Timer();

_timer.schedule(new TimerTask() {
    @Override
    public void run() {
        // use runOnUiThread(Runnable action)
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                search();
            }
        });
    }
}, timeInterval);

How to use Java property files?

  • You can store the file anywhere you like. If you want to keep it in your jar file, you'll want to use Class.getResourceAsStream() or ClassLoader.getResourceAsStream() to access it. If it's on the file system it's slightly easier.

  • Any extension is fine, although .properties is more common in my experience

  • Load the file using Properties.load, passing in an InputStream or a StreamReader if you're using Java 6. (If you are using Java 6, I'd probably use UTF-8 and a Reader instead of the default ISO-8859-1 encoding for a stream.)

  • Iterate through it as you'd iterate through a normal Hashtable (which Properties derives from), e.g. using keySet(). Alternatively, you can use the enumeration returned by propertyNames().

Attach IntelliJ IDEA debugger to a running Java process

in AndroidStudio or idea

  1. Config the application will be debug, open Edit Configurations

add "VM Options" Config “-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005” remember "address"

enter image description here

  1. Config Remote Debugger if not exits, Click + to add

specify "Port" same as in Step 1 "address" enter image description here

A simple command line to download a remote maven2 artifact to the local repository?

As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used

mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
    -DremoteRepositories=http://download.java.net/maven/2 \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
    -Ddest=c:\temp\robo-guice.jar

In JavaScript can I make a "click" event fire programmatically for a file input element?

For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.

HTML (Somewhere):

<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>

HTML (Somewhere you don't care about):

<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file" />
    </form>
</div>

JavaScript:

function pageY(el) {
    var ot = 0;
    while (el && el.offsetParent != el) {
        ot += el.offsetTop ? el.offsetTop : 0;
        el = el.offsetParent;
    }
    return ot;
}

function pageX(el) {
    var ol = 0;
    while (el && el.offsetParent != el) {
        ol += el.offsetLeft ? el.offsetLeft : 0;
        el = el.offsetParent;
    }
    return ol;
}

function fileMove() {
    if (navigator.appName == "Microsoft Internet Explorer") {
        return; // Don't need to do this in IE. 
    }
    var link = document.getElementById("fileLink");
    var form = document.getElementById("uploadForm");
    var x = pageX(link);
    var y = pageY(link);
    form.style.position = 'absolute';
    form.style.left = x + 'px';
    form.style.top = y + 'px';
}

function fileBrowse() {
    // This works in IE only. Doesn't do jack in FF. :( 
    var browseField = document.getElementById("uploadForm").file;
    browseField.click();
}

Getting value of selected item in list box as string

You can Use This One To get the selected ListItme Name ::

String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();

Make sure that Your each ListBoxItem have a Name property

Moving all files from one directory to another using Python

For example, if I wanted to move all .txt files from one location to another ( on a Windows OS for instance ) I would do it something like this:

import shutil
import os,glob

inpath = 'R:/demo/in' 
outpath = 'R:/demo/out'

os.chdir(inpath)
for file in glob.glob("*.txt"):

    shutil.move(inpath+'/'+file,outpath)

Rebase feature branch onto another feature branch

  1. Switch to Branch2

    git checkout Branch2
    
  2. Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:

    git rebase Branch1
    

Which would leave you with the desired result in Branch2:

a -- b -- c                      <-- Master
           \
            d -- e               <-- Branch1
           \
            d -- e -- f' -- g'   <-- Branch2

You can delete Branch1.

FormsAuthentication.SignOut() does not log the user out

I have been writing a base class for all of my Pages and I came to the same issue. I had code like the following and It didn't work. By tracing, control passes from RedirectToLoginPage() statement to the next line without to be redirected.

if (_requiresAuthentication)
{
    if (!User.Identity.IsAuthenticated)
        FormsAuthentication.RedirectToLoginPage();

    // check authorization for restricted pages only
    if (_isRestrictedPage) AuthorizePageAndButtons();
}

I found out that there are two solutions. Either to modify FormsAuthentication.RedirectToLoginPage(); to be

if (!User.Identity.IsAuthenticated)
    Response.Redirect(FormsAuthentication.LoginUrl);

OR to modify the web.config by adding

<authorization>
  <deny users="?" />
</authorization>

In the second case, while tracing, control didn't reach the requested page. It has been redirected immediately to the login url before hitting the break point. Hence, The SignOut() method isn't the issue, the redirect method is the one.

I hope that may help someone

Regards

PowerShell Script to Find and Replace for all Files with a Specific Extension

PowerShell is a good choice ;) It is very easy to enumerate files in given directory, read them and process.

The script could look like this:

Get-ChildItem C:\Projects *.config -recurse |
    Foreach-Object {
        $c = ($_ | Get-Content) 
        $c = $c -replace '<add key="Environment" value="Dev"/>','<add key="Environment" value="Demo"/>'
        [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
    }

I split the code to more lines to be readable for you. Note that you could use Set-Content instead of [IO.File]::WriteAllText, but it adds new line at the end. With WriteAllText you can avoid it.

Otherwise the code could look like this: $c | Set-Content $_.FullName.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

Screen width in React Native

If you have a Style component that you can require from your Component, then you could have something like this at the top of the file:

const Dimensions = require('Dimensions');

const window = Dimensions.get('window');

And then you could provide fulscreen: {width: window.width, height: window.height}, in your Style component. Hope this helps

How to create id with AUTO_INCREMENT on Oracle?

Starting with Oracle 12c there is support for Identity columns in one of two ways:

  1. Sequence + Table - In this solution you still create a sequence as you normally would, then you use the following DDL:

    CREATE TABLE MyTable (ID NUMBER DEFAULT MyTable_Seq.NEXTVAL, ...)

  2. Table Only - In this solution no sequence is explicitly specified. You would use the following DDL:

    CREATE TABLE MyTable (ID NUMBER GENERATED AS IDENTITY, ...)

If you use the first way it is backward compatible with the existing way of doing things. The second is a little more straightforward and is more inline with the rest of the RDMS systems out there.

How do I import a .dmp file into Oracle?

imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Uninstallation :

sudo /Library/PostgreSQL/9.6/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

Removing the data file :

sudo rm -rf /Library/PostgreSQL

Removing the configs :

sudo rm /etc/postgres-reg.ini

And thats it.

Print an integer in binary format in Java

Old school:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

How to remove all elements in String array in java?

list.clear() is documented for clearing the ArrayList.

list.removeAll() has no documentation at all in Eclipse.

How to avoid scientific notation for large numbers in JavaScript?

Your question:

number :0x68656c6c6f206f72656f
display:4.9299704811152646e+23

You can use this: https://github.com/MikeMcl/bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.

like this:

let ten =new BigNumber('0x68656c6c6f206f72656f',16);
console.log(ten.toString(10));
display:492997048111526447310191

How to center images on a web page for all screen sizes

text-align:center

Applying the text-align:center style to an element containing elements will center those elements.

<div id="method-one" style="text-align:center">
  CSS `text-align:center`
</div>

Thomas Shields mentions this method



margin:0 auto

Applying the margin:0 auto style to a block element will center it within the element it is in.

<div id="method-two" style="background-color:green">
  <div style="margin:0 auto;width:50%;background-color:lightblue">
    CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
  </div>
</div>

user1468562 mentions this method


Center tag

My original answer was that you can use the <center></center> tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center> is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.

<h3>Method 3</h1>
<div id="method-three">
  <center>Center tag (not recommended and deprecated in HTML4)</center>
</div>

You can see these three code samples in action in this jsfiddle.

I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.

How to have Android Service communicate with Activity

Besides LocalBroadcastManager , Event Bus and Messenger already answered in this question,we can use Pending Intent to communicate from service.

As mentioned here in my blog post

Communication between service and Activity can be done using PendingIntent.For that we can use createPendingResult().createPendingResult() creates a new PendingIntent object which you can hand to service to use and to send result data back to your activity inside onActivityResult(int, int, Intent) callback.Since a PendingIntent is Parcelable , and can therefore be put into an Intent extra,your activity can pass this PendingIntent to the service.The service, in turn, can call send() method on the PendingIntent to notify the activity via onActivityResult of an event.

Activity

public class PendingIntentActivity extends AppCompatActivity
{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

PendingIntent pendingResult = createPendingResult(
100, new Intent(), 0);
Intent intent = new Intent(getApplicationContext(), PendingIntentService.class);
intent.putExtra("pendingIntent", pendingResult);
startService(intent);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode==200) {
Toast.makeText(this,data.getStringExtra("name"),Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Service

public class PendingIntentService extends Service {

    private static final String[] items= { "lorem", "ipsum", "dolor",
            "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi",
            "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam",
            "vel", "erat", "placerat", "ante", "porttitor", "sodales",
            "pellentesque", "augue", "purus" };
    private PendingIntent data;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        data = intent.getParcelableExtra("pendingIntent");

        new LoadWordsThread().start();
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class LoadWordsThread extends Thread {
        @Override
        public void run() {
            for (String item : items) {
                if (!isInterrupted()) {

                    Intent result = new Intent();
                    result.putExtra("name", item);
                    try {
                        data.send(PendingIntentService.this,200,result);
                    } catch (PendingIntent.CanceledException e) {

                        e.printStackTrace();
                    }
                    SystemClock.sleep(400);

                }
            }
        }
    }
}

Find duplicate values in R

You could use table, i.e.

n_occur <- data.frame(table(vocabulary$id))

gives you a data frame with a list of ids and the number of times they occurred.

n_occur[n_occur$Freq > 1,]

tells you which ids occurred more than once.

vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]

returns the records with more than one occurrence.

Reactjs - Form input validation

Try powerform-react . It is based upon powerform which is a super portable Javascript form library. Once learnt, it can be used in any framework. It works even with vanilla Javascript.

Checkout this simple form that uses powerform-react

There is also a complex example.

Unrecognized escape sequence for path string containing backslashes

Try this:

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

The problem is that in a string, a \ is an escape character. By using the @ sign you tell the compiler to ignore the escape characters.

You can also get by with escaping the \:

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

Creating a new database and new connection in Oracle SQL Developer

This tutorial should help you:

Getting Started with Oracle SQL Developer

See the prerequisites:

  1. Install Oracle SQL Developer. You already have it.
  2. Install the Oracle Database. Download available here.
  3. Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:

    alter user hr identified by hr account unlock;

  4. Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.


Another version from May 2011: Getting Started with Oracle SQL Developer


For more info check this related question:

How to create a new database after initally installing oracle database 11g Express Edition?

What could cause java.lang.reflect.InvocationTargetException?

I was facing the same problem. I used e.getCause().getCause() then I found that it was because of wrong parameters I was passing. There was nullPointerException in fetching the value of one of the parameters. Hope this will help you.

How to include file in a bash shell script

In my situation, in order to include color.sh from the same directory in init.sh, I had to do something as follows.

. ./color.sh

Not sure why the ./ and not color.sh directly. The content of color.sh is as follows.

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

Making use of File color.sh does not error but, the color do not display. I have tested this in Ubuntu 18.04 and the Bash version is:

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

Popup window in winform c#

If you mean to create a new form when a button is clicked, the below code may be of some use to you:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

From here, you could also use the 'Show Dialog' method

Android ImageView setImageResource in code

One easy way to map that country name that you have to an int to be used in the setImageResource method is:

int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);

But you should really try to use different folders resources for the countries that you want to support.

How do I center a window onscreen in C#?

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

How to call a method daily, at specific time, in C#?

I have a simple approach to this. This creates a 1 minute delay before the action happens. You could add seconds as well to make the Thread.Sleep(); shorter.

private void DoSomething(int aHour, int aMinute)
{
    bool running = true;
    while (running)
    {
        Thread.Sleep(1);
        if (DateTime.Now.Hour == aHour && DateTime.Now.Minute == aMinute)
        {
            Thread.Sleep(60 * 1000); //Wait a minute to make the if-statement false
            //Do Stuff
        }
    }
}

How can I show line numbers in Eclipse?

Windows ? Preferences ? General ? Text Editors ? Show numberlines

Aren't Python strings immutable? Then why does a + " " + b work?

The built-in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory.

\>>a='dog'
\>>print(id(a))

139831803293008

\>>a=a+'cat'
\>>print(id(a))

139831803293120

Initially, 'a' is stored in 139831803293008 memory location, as the string object is immutable in python if you try to modify and reassign the reference will be removed and will be a pointer to a new memory location(139831803293120).

Comparing results with today's date?

If you have a table with just a stored date (no time) and want to get those by "now", then you can do this:

SELECT * FROM tbl WHERE DATEDIFF(d, yourdate, GETDATE())=0

This results in rows which day difference is 0 (so today).

ipad safari: disable scrolling, and bounce effect?

For those of you who don't want to get rid of the bouncing but just to know when it stops (for example to start some calculation of screen distances), you can do the following (container is the overflowing container element):

    const isBouncing = this.container.scrollTop < 0 ||
    this.container.scrollTop + this.container.offsetHeight >
        this.container.scrollHeight

How to call URL action in MVC with javascript function?

I'm going to give you 2 way's to call an action from the client side

first

If you just want to navigate to an action you should call just use the follow

window.location = "/Home/Index/" + youid

Notes: that you action need to handle a get type called

Second

If you need to render a View you could make the called by ajax

//this if you want get the html by get
public ActionResult Foo()
{
    return View(); //this return the render html   
}

And the client called like this "Assuming that you're using jquery"

$.get('your controller path', parameters to the controler , function callback)

or

$.ajax({
    type: "GET",
    url: "your controller path",
    data: parameters to the controler
    dataType: "html",
    success: your function
});

or

$('your selector').load('your controller path') 

Update

In your ajax called make this change to pass the data to the action

function onDropDownChange(e) {
var url = '/Home/Index' 
$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            //put your code here
        }
    });
}

UPDATE 2

You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div in your view and do something like this

in the view where you are that have the combo in some place

<div id="theNewView"> </div> <---you're going to load the other view here

in the javascript client

$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

With this i think that you solve your problem

PHP array printing using a loop

I also find that using <pre></pre> tags around your var_dump or print_r results in a much more readable dump.

Ambiguous overload call to abs(double)

The header <math.h> is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath> is the C++ version of that header. It defines essentially the same stuff in namespace std. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h> doesn't exist.

Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std. Or there's some macro magic for parsing the same header with or without namespace std wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath> be a one-liner including some other header with a .h extension. Or some would map all includes matching <cblah> to <blah.h> (which, through macro magic, becomes the C++ header when __cplusplus is defined, and otherwise becomes the C header) or <cblah.h> or whatever.

That's the reason why on some platforms including things like <cmath.h>, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.

I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath> maps to <cmath.h> with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.

Note, however, that this code still ought not to compile:

#include <cmath>

double f(double d)
{
  return abs(d);
}

There shouldn't be an abs() in the global namespace (it's std::abs()). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.

Laravel 5 - How to access image uploaded in storage within View?

One option would be to create a symbolic link between a subfolder in your storage directory and public directory.

For example

ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars

This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.

How can I replace newlines using PowerShell?

In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)

React component initialize state from props

You don't need to call setState in a Component's constructor - it's idiomatic to set this.state directly:

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      x: props.initialX
    };
  }
  // ...
}

See React docs - Adding Local State to a Class.

There is no advantage to the first method you describe. It will result in a second update immediately before mounting the component for the first time.

Determine the number of NA values in a column

If you are looking to count the number of NAs in the entire dataframe you could also use

sum(is.na(df))

How to make child process die after parent exits?

Inspired by another answer here, I came up with the following all-POSIX solution. The general idea is to create an intermediate process between the parent and the child, that has one purpose: Notice when the parent dies, and explicitly kill the child.

This type of solution is useful when the code in the child can't be modified.

int p[2];
pipe(p);
pid_t child = fork();
if (child == 0) {
    close(p[1]); // close write end of pipe
    setpgid(0, 0); // prevent ^C in parent from stopping this process
    child = fork();
    if (child == 0) {
        close(p[0]); // close read end of pipe (don't need it here)
        exec(...child process here...);
        exit(1);
    }
    read(p[0], 1); // returns when parent exits for any reason
    kill(child, 9);
    exit(1);
}

There are two small caveats with this method:

  • If you deliberately kill the intermediate process, then the child won't be killed when the parent dies.
  • If the child exits before the parent, then the intermediate process will try to kill the original child pid, which could now refer to a different process. (This could be fixed with more code in the intermediate process.)

As an aside, the actual code I'm using is in Python. Here it is for completeness:

def run(*args):
    (r, w) = os.pipe()
    child = os.fork()
    if child == 0:
        os.close(w)
        os.setpgid(0, 0)
        child = os.fork()
        if child == 0:
            os.close(r)
            os.execl(args[0], *args)
            os._exit(1)
        os.read(r, 1)
        os.kill(child, 9)
        os._exit(1)
    os.close(r)

Saving an image in OpenCV

sorry if this is too obvious. Are you sure the webcam is properly seen and detected by OpenCV in other words, do you get an image when you redirect the captured frame to a "highGui" window? For instance like so:

 frame = cvQueryFrame( capture );
 cvNamedWindow( "myWindow", CV_WINDOW_AUTOSIZE );
 cvShowImage( "myWindow", frame );

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

diff current working copy of a file with another branch's committed copy

Also: git diff master..feature foo

Since git diff foo master:foo doesn't work on directories for me.

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Things to be done to free port 80:

  1. check if skype is running, exit from skype
  2. check services.msc if web deployment agent service is running
  3. check if IIS is running, stop it.

Once you start apache, you can sign into skype.

How to get the mouse position without events (without moving the mouse)?

What you can do is create variables for the x and y coordinates of your cursor, update them whenever the mouse moves and call a function on an interval to do what you need with the stored position.

The downside to this of course is that at least one initial movement of the mouse is required to have it work. As long as the cursor updates its position at least once, we are able to find its position regardless of whether it moves again.

var cursor_x = -1;
var cursor_y = -1;
document.onmousemove = function(event)
{
 cursor_x = event.pageX;
 cursor_y = event.pageY;
}
setInterval(check_cursor, 1000);
function check_cursor(){console.log('Cursor at: '+cursor_x+', '+cursor_y);}

The preceding code updates once a second with a message of where your cursor is. I hope this helps.

remove all variables except functions

Here's a pretty convenient function I picked up somewhere and adjusted a little. Might be nice to keep in the directory.

list.objects <- function(env = .GlobalEnv) 
{
    if(!is.environment(env)){
        env <- deparse(substitute(env))
        stop(sprintf('"%s" must be an environment', env))
    }
    obj.type <- function(x) class(get(x, envir = env))
    foo <- sapply(ls(envir = env), obj.type)
    object.name <- names(foo)
    names(foo) <- seq(length(foo))
    dd <- data.frame(CLASS = foo, OBJECT = object.name, 
                     stringsAsFactors = FALSE)
    dd[order(dd$CLASS),]
}

> x <- 1:5
> d <- data.frame(x)
> list.objects()
#        CLASS       OBJECT
# 1 data.frame            d
# 2   function list.objects
# 3    integer            x 
> list.objects(env = x)
# Error in list.objects(env = x) : "x" must be an environment

How to create an 2D ArrayList in java?

This can be achieve by creating object of List data structure, as follows

List list = new ArrayList();

For more information refer this link

How to create a Multidimensional ArrayList in Java?

scipy.misc module has no attribute imread?

I have all the packages required for the image extraction on jupyter notebook, but even then it shows me the same error.

Error on Jupyter Notebook

Reading the above comments, I have installed the required packages. Please do tell if I have missed some packages.

pip3 freeze | grep -i -E "pillow|scipy|scikit-image"
Pillow==5.4.1
scikit-image==0.14.2

scipy==1.2.1

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

How do you use math.random to generate random ints?

Cast abc to an integer.

(int)(Math.random()*100);

jQuery lose focus event

If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

So you can setup variables like so:

var $coolOptions= $("<div id='options'></div>").text("Some cool options");

and then append (or prepend) on focus

$("input[name='input_name']").focus(function() {
    $(this).append($coolOptions);
});

and then remove when the focus ends

$("input[name='input_name']").focusout(function() {
    $('#options').remove();
});

SQL Server IN vs. EXISTS Performance

Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.

  1. In the first, the correlated subquery will likely cause the subquery to be run for each row.
  2. In the second example, the subquery should only run once, since not correlated.
  3. In the second example, the IN will short-circuit as soon as it finds a match.

Disable vertical scroll bar on div overflow: auto

This rules are compatible whit all browser:

body {overflow: hidden; }
body::-webkit-scrollbar { width: 0 !important; }
body { overflow: -moz-scrollbars-none; }
body { -ms-overflow-style: none; }

Write HTML to string

The most straight forward way is to use an XmlWriter object. This can be used to produce valid HTML and will take care of all of the nasty escape sequences for you.

Most simple code to populate JTable from ResultSet

go here java tips weblog

then,put in your project : listtabelmodel.java and rowtablemodel.java add another class with this code:

    enter code here
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package comp;

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.*;

public class TableFromDatabase extends JPanel {

    private Connection conexao = null;

    public TableFromDatabase() {
        Vector columnNames = new Vector();
        Vector data = new Vector();

        try {
            //  Connect to an Access Database
            conexao = DriverManager.getConnection("jdbc:mysql://" + "localhost"
                    + ":3306/yourdatabase", "root", "password");

            //  Read data from a table
            String sql = "select * from tb_something";
            Statement stmt = conexao.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++) {
                columnNames.addElement(md.getColumnName(i));
            }

            //  Get row data
            while (rs.next()) {
                Vector row = new Vector(columns);

                for (int i = 1; i <= columns; i++) {
                    row.addElement(rs.getObject(i));
                }

                data.addElement(row);
            }

            rs.close();
            stmt.close();
            conexao.close();
        } catch (Exception e) {
            System.out.println(e);
        }

        //  Create table with database data
        JTable table = new JTable(data, columnNames) {
            public Class getColumnClass(int column) {
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);

                    if (o != null) {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        JPanel buttonPanel = new JPanel();
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("any");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                //Create and set up the content pane.
                TableFromDatabase newContentPane = new TableFromDatabase();
                newContentPane.setOpaque(true); //content panes must be opaque
                frame.setContentPane(newContentPane);

                //Display the window.
                frame.pack();
                frame.setVisible(true);
            }
        });

    }
}

then drag this class to you jframe,and it's done

it's deprecated,but it works.........

How to make an introduction page with Doxygen

Have a look at the mainpage command.

Also, have a look this answer to another thread: How to include custom files in Doxygen. It states that there are three extensions which doxygen classes as additional documentation files: .dox, .txt and .doc. Files with these extensions do not appear in the file index but can be used to include additional information into your final documentation - very useful for documentation that is necessary but that is not really appropriate to include with your source code (for example, an FAQ)

So I would recommend having a mainpage.dox (or similarly named) file in your project directory to introduce you SDK. Note that inside this file you need to put one or more C/C++ style comment blocks.

firestore: PERMISSION_DENIED: Missing or insufficient permissions

For me it was the issue with the date. Updated it and the issue was resolved.

Allow read/write:

 if request.time < timestamp.date(2020, 5, 21);

Edit: If you are still confused and unable to figure out what's the issue just have a look at the rules section in your firebase console.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

In my case the issue was the Google services gradle plugin with the following line in the gradle file:

apply plugin: 'com.google.gms.google-services'

Removing this resolved the issue

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

What's default HTML/CSS link color?

The default colours in Gecko, assuming the user hasn't changed their preferences, are:

  • standard link: #0000EE (blue)
  • visited link: #551A8B (purple)
  • active link: #EE0000 (red)

Source

Gecko also provides names for the user's colours; they are -moz-hyperlinktext -moz-visitedhyperlinktext and -moz-activehyperlinktext and they also provide -moz-nativehyperlinktext which is the system link colour.

Check if a value is in an array (C#)

Consider using HashSet<T> Class for the sake of lookup performance:

This method is an O(1) operation.

HashSet<T>.Contains Method (T), MSDN.

For example:

class PrinterInstaller
{
    private static readonly HashSet<string> PrinterNames = new HashSet<string>
        {
            "jupiter", "neptune", "pangea", "mercury", "sonic"
        };

    public void Setup(string printerName)
    {
        if (!PrinterNames.Contains(printerName))
        {
            throw new ArgumentException("Unknown printer name", "printerName");
        }
        // ...
    }
}

Exception thrown in catch and finally clause

A method can't throw two exceptions at the same time. It will always throw the last thrown exception, which in this case it will be always the one from the finally block.

When the first exception from method q() is thrown, it will catch'ed and then swallowed by the finally block thrown exception.

q() -> thrown new Exception -> main catch Exception -> throw new Exception -> finally throw a new exception (and the one from the catch is "lost")

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

How to manually install an artifact in Maven 2?

According to maven's Guide to installing 3rd party JARs, the command is:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

You need indeed the packaging option. This answers the original question.

Now, in your context, you are fighting with a jar provided by Sun. You should read the Coping with Sun JARs page too. There, you'll learn how to help maven to provide you better information about Sun jars location and how to add Java.net Maven 2 repository which contains jta-1.0.1B.jar. Add this in your settings.xml (not portable) or pom.xml (portable):

  <repositories>
    <repository>
      <id>maven2-repository.dev.java.net</id>
      <name>Java.net Repository for Maven</name>
      <url>http://download.java.net/maven/2/</url>
      <layout>default</layout>
    </repository>
  </repositories>

Determine the line of code that causes a segmentation fault?

GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:

gcc program.c -g

Then use gdb:

$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>

Here is a nice tutorial to get you started with GDB.

Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.

How do I output an ISO 8601 formatted string in JavaScript?

function timeStr(d) { 
  return ''+
    d.getFullYear()+
    ('0'+(d.getMonth()+1)).slice(-2)+
    ('0'+d.getDate()).slice(-2)+
    ('0'+d.getHours()).slice(-2)+
    ('0'+d.getMinutes()).slice(-2)+
    ('0'+d.getSeconds()).slice(-2);
}

Passing variables through handlebars partial

This is very possible if you write your own helper. We are using a custom $ helper to accomplish this type of interaction (and more):

/*///////////////////////

Adds support for passing arguments to partials. Arguments are merged with 
the context for rendering only (non destructive). Use `:token` syntax to 
replace parts of the template path. Tokens are replace in order.

USAGE: {{$ 'path.to.partial' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}

///////////////////////////////*/

Handlebars.registerHelper('$', function(partial) {
    var values, opts, done, value, context;
    if (!partial) {
        console.error('No partial name given.');
    }
    values = Array.prototype.slice.call(arguments, 1);
    opts = values.pop();
    while (!done) {
        value = values.pop();
        if (value) {
            partial = partial.replace(/:[^\.]+/, value);
        }
        else {
            done = true;
        }
    }
    partial = Handlebars.partials[partial];
    if (!partial) {
        return '';
    }
    context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
    return new Handlebars.SafeString( partial(context) );
});

Java 8, Streams to find the duplicate elements

Basic example. First-half builds the frequency-map, second-half reduces it to a filtered list. Probably not as efficient as Dave's answer, but more versatile (like if you want to detect exactly two etc.)

List<Integer> duplicates = IntStream.of( 1, 2, 3, 2, 1, 2, 3, 4, 2, 2, 2 )
   .boxed()
   .collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) )
   .entrySet()
   .stream()
   .filter( p -> p.getValue() > 1 )
   .map( Map.Entry::getKey )
   .collect( Collectors.toList() );

Force SSL/https using .htaccess and mod_rewrite

try this code, it will work for all version of URLs like

  • website.com
  • www.website.com
  • http://website.com
  • http://www.website.com

    RewriteCond %{HTTPS} off
    RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
    RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
    

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Get Month name from month number

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(4)

This method return April

If you need some special language, you can add:

<system.web>
    <globalization culture="es-ES" uiCulture="es-ES"></globalization>
     <compilation debug="true"
</system.web>

Or your preferred language.

For example, with es-ES culture:

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(4)

Returns: Abril

Returns: Abril (in spanish, because, we configured the culture as es-ES in our webconfig file, else, you will get April)

That should work.