Programs & Examples On #68000

The 68000 is a 16/32 bit CISC CPU, originally designed by Motorola, Inc.

Get driving directions using Google Maps API v2

I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

Find timestamp from DateTime:

private long ConvertToTimestamp(DateTime value)
{
    TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
    TimeZone localZone = TimeZone.CurrentTimeZone;
    System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
    NyTime = NyTime.AddHours(-1);
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (NyTime - epoch);
    return (long)Convert.ToDouble(span.TotalSeconds);
}

Suppress Scientific Notation in Numpy When Creating Array From Nested List

Python Force-suppress all exponential notation when printing numpy ndarrays, wrangle text justification, rounding and print options:

What follows is an explanation for what is going on, scroll to bottom for code demos.

Passing parameter suppress=True to function set_printoptions works only for numbers that fit in the default 8 character space allotted to it, like this:

import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential 
                                   #notation on print, default False

#            tiny     med  large
a = np.array([1.01e-5, 22, 1.2345678e7])  #notice how index 2 is 8 
                                          #digits wide

print(a)    #prints [ 0.0000101   22.     12345678. ]

However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:

np.set_printoptions(suppress=True)

a = np.array([1.01e-5, 22, 1.2345678e10])    #notice how index 2 is 10
                                             #digits wide, too wide!

#exponential notation where we've told it not to!
print(a)    #prints [1.01000000e-005   2.20000000e+001   1.23456780e+10]

numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.

Here comes set_printoptions(formatter=...) to the rescue to specify options for printing and rounding. Tell set_printoptions to just print bare a bare float:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:f}'.format})

a = np.array([1.01e-5, 22, 1.2345678e30])  #notice how index 2 is 30
                                           #digits wide.  

#Ok good, no exponential notation in the large numbers:
print(a)  #prints [0.000010 22.000000 1234567799999999979944197226496.000000] 

We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:0.2f}'.format})  #float, 2 units 
                                               #precision right, 0 on left

a = np.array([1.01e-5, 22, 1.2345678e30])   #notice how index 2 is 30
                                            #digits wide

print(a)  #prints [0.00 22.00 1234567799999999979944197226496.00]

The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.

Full example Demo 1:

from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
           [9.55, 116, 189688622.37, 260332262.0, 1.97],
           [2.2, 768, 6004865.13, 5759960.98, 1.21],
           [3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
           [1.91, 474, 44555062.72, 44555062.72, 0.41],
           [5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
           [4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
           [7.03, 116, 66252511.46, 81109291.0, 1.56],
           [6.52, 116, 47674230.76, 57686991.0, 1.43],
           [1.85, 623, 3002631.96, 2899484.08, 0.64],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]

#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)

#This is a little recursive helper function converts all nested 
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
    if type(arr) == type(np.array):
        #If the passed type is an ndarray then convert it to a list and
        #recursively convert all nested types
        return arrayToList(arr.tolist())
    else:
        #if item isn't an ndarray leave it as is.
        return arr

#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))

Prints:

array([[           3.740,         5162.000,  13683628846.640,  12783387559.860,            1.810],
       [           9.550,          116.000,    189688622.370,    260332262.000,            1.970],
       [           2.200,          768.000,      6004865.130,      5759960.980,            1.210],
       [           3.740,         4062.000,   3263822121.390,   3066869087.900,            1.930],
       [           1.910,          474.000,     44555062.720,     44555062.720,            0.410],
       [           5.800,         5006.000,   8254968918.100,   7446788272.740,            3.250],
       [           4.500,         7887.000,  30078971595.460,  27814989471.310,            2.180],
       [           7.030,          116.000,     66252511.460,     81109291.000,            1.560],
       [           6.520,          116.000,     47674230.760,     57686991.000,            1.430],
       [           1.850,          623.000,      3002631.960,      2899484.080,            0.640],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320]])

Full example Demo 2:

import numpy as np  
#chaotic python list of lists with very different numeric magnitudes 

#            very tiny      medium size            large sized
#            numbers        numbers                numbers

my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81], 
           [1.000000000055,  116, 189688622.37, 260332262.0, 1.97], 
           [0.010000000022,  768, 6004865.13,   -99e13, 1.21], 
           [1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93], 
           [2.91,            474, 44555062.72, 44555062.72, 0.41], 
           [5,              5006, 8254968918.1, 7446788272.74, 3.25], 
           [0.01,           7887, 30078971595.46, 27814989471.31, 2.18], 
           [7.03,            116, 66252511.46, 81109291.0, 1.56], 
           [6.52,            116, 47674230.76, 57686991.0, 1.43], 
           [1.85,            623, 3002631.96, 2899484.08, 0.64], 
           [13.76,          1227, 1737874137.5, 1446511574.32, 4.32], 
           [13.76,          1337, 1737874137.5, 1446511574.32, 4.32]] 
import sys 
#convert python list of lists to numpy ndarray called my_array 
my_array = np.array(my_list) 
#following two lines do the same thing, showing that np.savetxt can 
#correctly handle python lists of lists and numpy 2D ndarrays. 
np.savetxt(sys.stdout, my_list, '%19.2f') 
np.savetxt(sys.stdout, my_array, '%19.2f') 

Prints:

 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32
 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32

Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x and very small e-x ranges.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Here is your relief for the problem :

I have a problem of running different versions of STS this morning, the application crash with the similar way as the question did.

Excerpt of my log file.

A fatal error has been detected by the Java Runtime Environment:
#a
#  SIGSEGV (0xb) at pc=0x00007f459db082a1, pid=4577, tid=139939015632640
#
# JRE version: 6.0_30-b12
# Java VM: Java HotSpot(TM) 64-Bit Server VM 
(20.5-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  [libsoup-2.4.so.1+0x6c2a1]  short+0x11

note that exception occured at # C [libsoup-2.4.so.1+0x6c2a1] short+0x11

Okay then little below the line:

R9 =0x00007f461829e550: <offset 0xa85550> in /usr/share/java/jdk1.6.0_30/jre/lib/amd64/server/libjvm.so at 0x00007f4617819000
R10=0x00007f461750f7c0 is pointing into the stack for thread: 0x00007f4610008000
R11=0x00007f459db08290: soup_session_feature_detach+0 in /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1 at 0x00007f459da9c000
R12=0x0000000000000000 is an unknown value
R13=0x000000074404c840 is an oop
{method} 

This line tells you where the actual bug or crash is to investigate more on this crash issue please use below links to see more, but let's continue the crash investigation and how I resolved it and the novelty of this bug :)

links are :

a fATAL ERROR JAVA THIS ONE IS GREAT LOTS OF USER!

a fATAL ERROR JAVA 2

Okay, after that here's what I found out to casue this case and why it happens as general advise.

  1. Most of the time, check that if you have installed, updated recently on Ubunu and Windows there are libraries like libsoup in linux which were the casuse of my crash.

  2. Check also for a new hardware problem and try to investigate the Logfile which STS or Java generated and also syslog in linux by

    tail - f /var/lib/messages or some other file
    

Then by carfully looking at those files the one you have the crash log for ... you can really solve the issue as follows:

sudo unlink /usr/lib/i386-linux-gnu/libsoup-2.4.so.1

or

sudo unlink /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1

Done !! Cheers!!

Converting json results to a date

You need to extract the number from the string, and pass it into the Date constructor:

var x = [{
    "id": 1,
    "start": "\/Date(1238540400000)\/"
}, {
    "id": 2,
    "start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

Invalid application path

Problem was installing iis manager after .net framework aspnet_regiis had run. Run run aspnet_regiis from x64 .net framework directory

aspnet_regiis -iru // From x64 .net framework directory

IIS Manager can't configure .NET Compilation on .NET 4 Applications

Nodejs - Redirect url

I used a switch statement, with the default as a 404:

var fs = require("fs");
var http = require("http");

function send404Response (response){
    response.writeHead(404, {"Content-Type": "text/html"});
    fs.createReadStream("./path/to/404.html").pipe(response);
}

function onRequest (request, response){
    switch (request.url){
        case "/page1":
            //statements
            break;
        case "/page2":
            //statements
            break;
        default:
        //if no 'match' is found
            send404Response(response);
            break;
    }
}

http.createServer(onRequest).listen(8080);

Order columns through Bootstrap4

Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).

<div class="container">
<div class="row">
    <div class="col-3 col-md-6">
        <div class="card card-block">1</div>
    </div>
    <div class="col-6 col-md-12  flex-md-last">
        <div class="card card-block">3</div>
    </div>
    <div class="col-3 col-md-6 ">
        <div class="card card-block">2</div>
    </div>
</div>

Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.

Returning IEnumerable<T> vs. IQueryable<T>

In general terms I would recommend the following:

  • Return IQueryable<T> if you want to enable the developer using your method to refine the query you return before executing.

  • Return IEnumerable if you want to transport a set of Objects to enumerate over.

Imagine an IQueryable as that what it is - a "query" for data (which you can refine if you want to). An IEnumerable is a set of objects (which has already been received or was created) over which you can enumerate.

How to give ASP.NET access to a private key in a certificate in the certificate store?

I figured out how to do this in Powershell that someone asked about:

$keyname=(((gci cert:\LocalMachine\my | ? {$_.thumbprint -like $thumbprint}).PrivateKey).CspKeyContainerInfo).UniqueKeyContainerName
$keypath = $env:ProgramData + “\Microsoft\Crypto\RSA\MachineKeys\”
$fullpath=$keypath+$keyname

$Acl = Get-Acl $fullpath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool\$iisAppPoolName", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $fullpath $Acl

HTML to PDF with Node.js

Extending upon Mustafa's answer.

A) Install http://phantomjs.org/ and then

B) install the phantom node module https://github.com/amir20/phantomjs-node

enter image description here

C) Here is an example of rendering a pdf

var phantom = require('phantom');   

phantom.create().then(function(ph) {
    ph.createPage().then(function(page) {
        page.open("http://www.google.com").then(function(status) {
            page.render('google.pdf').then(function() {
                console.log('Page Rendered');
                ph.exit();
            });
        });
    });
});

Output of the PDF:

enter image description here

EDIT: Silent printing that PDF

java -jar pdfbox-app-2.0.2.jar PrintPDF -silentPrint C:\print_mypdf.pdf

How to clear the cache in NetBeans

I'll just add that I have tried to resolve reference problems caused by a missing library in the cache, and deleting the cache was not enough to solve the problem.

I closed NetBeans (7.2.1), deleted the cache, then reopened NetBeans, and it regenerated the cache, but the library was still missing (checked by looking in .../Cache/7.2.1/index/archives.properties).

To resolve the problem I had to close my open projects before closing NetBeans and deleting the cache.

Android Reading from an Input stream efficiently

Maybe rather then read 'one line at a time' and join the strings, try 'read all available' so as to avoid the scanning for end of line, and to also avoid string joins.

ie, InputStream.available() and InputStream.read(byte[] b), int offset, int length)

Android - how to make a scrollable constraintlayout?

Take out bottom button from the nestedscrollview and take linearlayout as parent. Add bottom and nestedscrollview as thier children. It will work absolutely fine. In manifest for the activity use this - this will raise the button when the keyboard is opened

android:windowSoftInputMode="adjustResize|stateVisible"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.core.widget.NestedScrollView xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:fillViewport="true">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/input_city_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="20dp"
                android:layout_marginTop="32dp"
                android:layout_marginEnd="20dp"
                android:hint="@string/city_name"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/city_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    android:lines="1"
                    android:maxLength="100"
                    android:textSize="16sp" />

            </com.google.android.material.textfield.TextInputLayout>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.core.widget.NestedScrollView>

    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:onClick="onSubmit"
        android:padding="12dp"
        android:text="@string/string_continue"
        android:textColor="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="parent" />

</LinearLayout>

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

New location for mysql config file is

/etc/mysql/mysql.conf.d/mysqld.cnf

Getting files by creation date in .NET

            DirectoryInfo dirinfo = new DirectoryInfo(strMainPath);
            String[] exts = new string[] { "*.jpeg", "*.jpg", "*.gif", "*.tiff", "*.bmp","*.png", "*.JPEG", "*.JPG", "*.GIF", "*.TIFF", "*.BMP","*.PNG" };
            ArrayList files = new ArrayList();
            foreach (string ext in exts)
                files.AddRange(dirinfo.GetFiles(ext).OrderBy(x => x.CreationTime).ToArray());

Rename a table in MySQL

According to mysql docs: "to rename TEMPORARY tables, RENAME TABLE does not work. Use ALTER TABLE instead."

So this is the most portable method:

ALTER TABLE `old_name` RENAME `new_name`;

Regex: match everything but specific pattern

You can put a ^ in the beginning of a character set to match anything but those characters.

[^=]*

will match everything but =

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

How to check status of PostgreSQL server Mac OS X

The pg_ctl status command suggested in other answers checks that the postmaster process exists and if so reports that it's running. That doesn't necessarily mean it is ready to accept connections or execute queries.

It is better to use another method like using psql to run a simple query and checking the exit code, e.g. psql -c 'SELECT 1', or use pg_isready to check the connection status.

RelativeLayout center vertical

Adding both android:layout_centerInParent and android:layout_centerVertical work for me to center ImageView both vertical and horizontal:

<ImageView
    ..
    android:layout_centerInParent="true"
    android:layout_centerVertical="true"
    />

Cannot find vcvarsall.bat when running a Python script

In case anyone comes here looking for an answer for Python 3.5; you need Visual Studio 2015.

Get Visual Studio 2015 Community here: https://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs.aspx, this worked for me with no further steps needed.

Many thanks to Ionel, apparently the only place on the web to find this information! http://blog.ionelmc.ro/2014/12/21/compiling-python-extensions-on-windows/

What are .iml files in Android Studio?

They are project files, that hold the module information and meta data.

Just add *.iml to .gitignore.

In Android Studio: Press CTRL + F9 to rebuild your project. The missing *.iml files will be generated.

Swift alert view with OK and Cancel: which button tapped?

Updated for swift 3:

// function defination:

@IBAction func showAlertDialog(_ sender: UIButton) {
        // Declare Alert
        let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)

        // Create OK button with action handler
        let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
             print("Ok button click...")
             self.logoutFun()
        })

        // Create Cancel button with action handlder
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
            print("Cancel button click...")
        }

        //Add OK and Cancel button to dialog message
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancel)

        // Present dialog message to user
        self.present(dialogMessage, animated: true, completion: nil)
    }

// logoutFun() function definaiton :

func logoutFun()
{
    print("Logout Successfully...!")
}

How does Tomcat locate the webapps directory?

Change appBase in server.xml

If you want to keep both previous webapps and a new one, you can use another Host instance with another port defined in tomcat.

Ignore case in Python strings

For occasional or even repeated comparisons, a few extra string objects shouldn't matter as long as this won't happen in the innermost loop of your core code or you don't have enough data to actually notice the performance impact. See if you do: doing things in a "stupid" way is much less stupid if you also do it less.

If you seriously want to keep comparing lots and lots of text case-insensitively you could somehow keep the lowercase versions of the strings at hand to avoid finalization and re-creation, or normalize the whole data set into lowercase. This of course depends on the size of the data set. If there are a relatively few needles and a large haystack, replacing the needles with compiled regexp objects is one solution. If It's hard to say without seeing a concrete example.

Syntax error near unexpected token 'fi'

As well as having then on a new line, you also need a space before and after the [, which is a special symbol in BASH.

#!/bin/bash
echo "start\n"
for f in *.jpg
do
  fname=$(basename "$f")
  echo "fname is $fname\n"
  fname="${filename%.*}"
  echo "fname is $fname\n"
  if [ $((fname %  2)) -eq 1 ]
  then
    echo "removing $fname\n"
    rm "$f"
  fi
done

Android getting value from selected radiobutton

For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:

    for(int i = 0; i < myNames.length; i++) {
        rB = new RadioButton(getContext());
        rB.setText(myNames[i]);
        rB.setTag(i);
        myRadioGroup.addView(rB,i);
    }

Then in your listener:

    myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            int mySelectedIndex = (int) radioButton.getTag();
        }
    });

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

Access localhost from the internet

Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.

THen, send your ip + port to the person who will use it.

sample: http://200.200.200.200:8080/mySite/

How do I show the value of a #define at compile-time?

If you are using Visual C++, you can use #pragma message:

#include <boost/preprocessor/stringize.hpp>
#pragma message("BOOST_VERSION=" BOOST_PP_STRINGIZE(BOOST_VERSION))

Edit: Thanks to LB for link

Apparently, the GCC equivalent is (not tested):

#pragma message "BOOST_VERSION=" BOOST_PP_STRINGIZE(BOOST_VERSION)

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

ImportError in importing from sklearn: cannot import name check_build

no need to uninstall & then re-install sklearn

try this:

from sklearn.model_selection import train_test_split

PostgreSQL: Why psql can't connect to server?

I had the same problem. It seems that there is no socket when there is no cluster.

The default cluster creation failed during the installation because no default locale was set.

clearInterval() not working

The setInterval function returns an integer value, which is the id of the "timer instance" that you've created.

It is this integer value that you need to pass to clearInterval

e.g:

var timerID = setInterval(fontChange,500);

and later

clearInterval(timerID);

How to Set Active Tab in jQuery Ui

Inside your function for the click action use

$( "#tabs" ).tabs({ active: # });

Where # is replaced by the tab index you want to select.

Edit: change from selected to active, selected is deprecated

How to decode a Base64 string?

This page shows up when you google how to convert to base64, so for completeness:

$b  = [System.Text.Encoding]::UTF8.GetBytes("blahblah")
[System.Convert]::ToBase64String($b)

Ajax LARAVEL 419 POST error

Had the same problem, regenerating application key helped - php artisan key:generate

finding and replacing elements in a list

>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> item_to_replace = 1
>>> replacement_value = 6
>>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
>>> indices_to_replace
[0, 5, 10]
>>> for i in indices_to_replace:
...     a[i] = replacement_value
... 
>>> a
[6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
>>> 

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

From Django 2.0 on_delete is required:

user = models.OneToOneField(User, on_delete=models.CASCADE)

It will delete the child table data if the User is deleted. For more details check the Django documentation.

How can I send emails through SSL SMTP with the .NET Framework?

For gmail these settings worked for me, the ServicePointManager.SecurityProtocol line was necessary. Because I has setup 2 step verification I needed get a App Password from google app password generator.

SmtpClient mailer = new SmtpClient();
mailer.Host = "smtp.gmail.com";
mailer.Port = 587;
mailer.EnableSsl = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

Is it possible to have a default parameter for a mysql stored procedure?

Unfortunately, MySQL doesn't support DEFAULT parameter values, so:

CREATE PROCEDURE `blah`
(
  myDefaultParam int DEFAULT 0
)
BEGIN
  -- Do something here
END

returns the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use 
near 'DEFAULT 0) BEGIN END' at line 3

To work around this limitation, simply create additional procedures that assign default values to the original procedure:

DELIMITER //

DROP PROCEDURE IF EXISTS blah//
DROP PROCEDURE IF EXISTS blah2//
DROP PROCEDURE IF EXISTS blah1//
DROP PROCEDURE IF EXISTS blah0//

CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    SELECT param1, param2;
END;
//

CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    CALL blah(param1, param2);
END;
//

CREATE PROCEDURE blah1(param1 INT UNSIGNED)
BEGIN
    CALL blah2(param1, 3);
END;
//

CREATE PROCEDURE blah0()
BEGIN
    CALL blah1(4);
END;
//

Then, running this:

CALL blah(1, 1);
CALL blah2(2, 2);
CALL blah1(3);
CALL blah0();

will return:

+--------+--------+
| param1 | param2 |
+--------+--------+
|      1 |      1 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      2 |      2 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      3 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      4 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Then, if you make sure to only use the blah2(), blah1() and blah0() procedures, your code will not need to be immediately updated, when you add a third parameter to the blah() procedure.

close vs shutdown socket?

This is explained in Beej's networking guide. shutdown is a flexible way to block communication in one or both directions. When the second parameter is SHUT_RDWR, it will block both sending and receiving (like close). However, close is the way to actually destroy a socket.

With shutdown, you will still be able to receive pending data the peer already sent (thanks to Joey Adams for noting this).

How do I include the string header?

Sources telling you to use apstring.h are materials for the Advanced Placement course in computer science. It describes a string class that you'll use through the course, and some of the exam questions may refer to it and expect you to be moderately familiar with it. Unless you're enrolled in that class or studying to take that exam, ignore those sources.

Sources telling you to use string.h are either not really talking about C++, or are severely outdated. You should probably ignore them, too. That header is for the C functions for manipulating null-terminated arrays of characters, also known as C-style strings.

In C++, you should use the string header. Write #include <string> at the top of your file. When you declare a variable, the type is string, and it's in the std namespace, so its full name is std::string. You can avoid having to write the namespace portion of that name all the time by following the example of lots of introductory texts and saying using namespace std at the top of the C++ source files (but generally not at the top of any header files you might write).

delete vs delete[] operators in C++

The delete operator deallocates memory and calls the destructor for a single object created with new.

The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].

Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.

How to write loop in a Makefile?

Maybe you can use:

xxx:
    for i in `seq 1 4`; do ./a.out $$i; done;

How to remove leading zeros from alphanumeric text?

You could just do: String s = Integer.valueOf("0001007").toString();

Easy way of running the same junit test over and over?

I build a module that allows do this kind of tests. But it is focused not only in repeat. But in guarantee that some piece of code is Thread safe.

https://github.com/anderson-marques/concurrent-testing

Maven dependency:

<dependency>
    <groupId>org.lite</groupId>
    <artifactId>concurrent-testing</artifactId>
    <version>1.0.0</version>
</dependency>

Example of use:

package org.lite.concurrent.testing;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import ConcurrentTest;
import ConcurrentTestsRule;

/**
 * Concurrent tests examples
 */
public class ExampleTest {

    /**
     * Create a new TestRule that will be applied to all tests
     */
    @Rule
    public ConcurrentTestsRule ct = ConcurrentTestsRule.silentTests();

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 20, threads = 10)
    public void testConcurrentExecutionSuccess(){
        Assert.assertTrue(true);
    }

    /**
     * Tests using 10 threads and make 20 requests. This means until 10 simultaneous requests.
     */
    @Test
    @ConcurrentTest(requests = 200, threads = 10, timeoutMillis = 100)
    public void testConcurrentExecutionSuccessWaitOnly100Millissecond(){
    }

    @Test(expected = RuntimeException.class)
    @ConcurrentTest(requests = 3)
    public void testConcurrentExecutionFail(){
        throw new RuntimeException("Fail");
    }
}

This is a open source project. Feel free to improve.

How to return multiple values?

You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg

public class MyResult {
    int returnCode;
    String errorMessage;
    // etc
}

public MyResult someMethod() {
    // impl here
}

Gaussian fit for Python

sigma = sum(y*(x - mean)**2)

should be

sigma = np.sqrt(sum(y*(x - mean)**2))

Textarea to resize based on content length

A jquery solution has been implemented, and source code is available in github at: https://github.com/jackmoore/autosize .

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

According to the HTML standard, the content model of the HTML element is:

A head element followed by a body element.

You can either define the BODY element in the source code:

<html>
    <body>
        ... web-page ...
    </body>
</html>

or you can omit the BODY element:

<html>
    ... web-page ...
</html>

However, it is invalid to place the BODY element inside the web-page content (in-between other elements or text content), like so:

<html>
    ... content ...
    <body>
        ... content ...
    </body>
    ... content ...
</html>

Get table column names in MySQL?

I needed column names as a flat array, while the other answers returned associative arrays, so I used:

$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';

/**
* Get the column names for a mysql table
**/

function get_column_names($con, $table) {
  $sql = 'DESCRIBE '.$table;
  $result = mysqli_query($con, $sql);

  $rows = array();
  while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row['Field'];
  }

  return $rows;
}

$col_names = function get_column_names($con, $table);

$col_names now equals:

(
    [0] => name
    [1] => parent
    [2] => number
    [3] => chart_id
    [4] => type
    [5] => id
)

How to use ArrayAdapter<myClass>

Implement custom adapter for your class:

public class MyClassAdapter extends ArrayAdapter<MyClass> {

    private static class ViewHolder {
        private TextView itemView;
    }

    public MyClassAdapter(Context context, int textViewResourceId, ArrayList<MyClass> items) {
        super(context, textViewResourceId, items);
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(this.getContext())
            .inflate(R.layout.listview_association, parent, false);

            viewHolder = new ViewHolder();
            viewHolder.itemView = (TextView) convertView.findViewById(R.id.ItemView);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        MyClass item = getItem(position);
        if (item!= null) {
            // My layout has only one TextView
                // do whatever you want with your string and long
            viewHolder.itemView.setText(String.format("%s %d", item.reason, item.long_val));
        }

        return convertView;
    }
}

For those not very familiar with the Android framework, this is explained in better detail here: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.

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;
}

How do I access named capturing groups in a .NET Regex?

Use the group collection of the Match object, indexing it with the capturing group name, e.g.

foreach (Match m in mc){
    MessageBox.Show(m.Groups["link"].Value);
}

Grep and Python

Adapted from a grep in python.

Accepts a list of filenames via [2:], does no exception handling:

#!/usr/bin/env python
import re, sys, os

for f in filter(os.path.isfile, sys.argv[2:]):
    for line in open(f).readlines():
        if re.match(sys.argv[1], line):
            print line

sys.argv[1] resp sys.argv[2:] works, if you run it as an standalone executable, meaning

chmod +x

first

Change a Rails application to production

This would now be

rails server -e production

Or, more compact

rails s -e production

It works for rails 3+ projects.

How to center HTML5 Videos?

Do this:

<video style="display:block; margin: 0 auto;" controls>....</video>

Works perfect! :D

jQuery event for images loaded

As per this answer, you can use the jQuery load event on the window object instead of the document:

jQuery(window).load(function() {
    console.log("page finished loading now.");
});

This will be triggered after all content on the page has been loaded. This differs from jQuery(document).load(...) which is triggered after the DOM has finished loading.

Iterating over Numpy matrix rows to apply a function each?

Here's my take if you want to try using multiprocesses to process each row of numpy array,

from multiprocessing import Pool
import numpy as np

def my_function(x):
    pass     # do something and return something

if __name__ == '__main__':    
    X = np.arange(6).reshape((3,2))
    pool = Pool(processes = 4)
    results = pool.map(my_function, map(lambda x: x, X))
    pool.close()
    pool.join()

pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.

How to show "Done" button on iPhone number pad

Here is an adaptation for Luda's answer for Swift:

In the declaration of your UIViewController subclass put

let numberToolbar: UIToolbar = UIToolbar()

in ViewDidLoad put:

    numberToolbar.barStyle = UIBarStyle.BlackTranslucent
    numberToolbar.items=[
        UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Bordered, target: self, action: "hoopla"),
        UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil),
        UIBarButtonItem(title: "Apply", style: UIBarButtonItemStyle.Bordered, target: self, action: "boopla")
    ]

    numberToolbar.sizeToFit()

    textField.inputAccessoryView = numberToolbar //do it for every relevant textfield if there are more than one 

and the add the functions hoopla and hoopla (feel free to choose other names, just change the selector names in ViewDidLoad accordingly

func boopla () {
    textField.resignFirstResponder()
}

func hoopla () {
    textField.text=""
    textField.resignFirstResponder()
}

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

How to calculate probability in a normal distribution given mean & standard deviation?

There's one in scipy.stats:

>>> import scipy.stats
>>> scipy.stats.norm(0, 1)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(0, 1).pdf(0)
0.3989422804014327
>>> scipy.stats.norm(0, 1).cdf(0)
0.5
>>> scipy.stats.norm(100, 12)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(100, 12).pdf(98)
0.032786643008494994
>>> scipy.stats.norm(100, 12).cdf(98)
0.43381616738909634
>>> scipy.stats.norm(100, 12).cdf(100)
0.5

[One thing to beware of -- just a tip -- is that the parameter passing is a little broad. Because of the way the code is set up, if you accidentally write scipy.stats.norm(mean=100, std=12) instead of scipy.stats.norm(100, 12) or scipy.stats.norm(loc=100, scale=12), then it'll accept it, but silently discard those extra keyword arguments and give you the default (0,1).]

What happens if you don't commit a transaction to a database (say, SQL Server)?

In addition to the potential locking problems you might cause you will also find that your transaction logs begin to grow as they can not be truncated past the minimum LSN for an active transaction and if you are using snapshot isolation your version store in tempdb will grow for similar reasons.

You can use dbcc opentran to see details of the oldest open transaction.

R barplot Y-axis scale too short

I see you try to set ylim but you give bad values. This will change the scale of the plot (like a zoom). For example see this:

par(mfrow=c(2,1))
tN <- table(Ni <- stats::rpois(100, lambda = 5))
r <- barplot(tN, col = rainbow(20),ylim=c(0,50),main='long y-axis')
r <- barplot(tN, col = rainbow(20),main='short y axis')

enter image description here Another option is to plot without axes and set them manually using axis and usr:

require(grDevices) # for colours
par(mfrow=c(1,1))
r <- barplot(tN, col = rainbow(20),main='short y axis',ann=FALSE,axes=FALSE)
usr <- par("usr")
par(usr=c(usr[1:2], 0, 20))
axis(2,at=seq(0,20,5))

enter image description here

Fastest way to check if a value exists in a list

7 in a

Clearest and fastest way to do it.

You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)

Run command on the Ansible host

ansible your_server_name -i custom_inventory_file_name -m -a "uptime"

The default module is command module, hence command keyword is not required.

If you need to issue any command with elevated privileges use -b at the end of the same command.

ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b

Linux bash: Multiple variable assignment

Chapter 5 of the Bash Cookbook by O'Reilly, discusses (at some length) the reasons for the requirement in a variable assignment that there be no spaces around the '=' sign

MYVAR="something"

The explanation has something to do with distinguishing between the name of a command and a variable (where '=' may be a valid argument).

This all seems a little like justifying after the event, but in any case there is no mention of a method of assigning to a list of variables.

How does `scp` differ from `rsync`?

rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.

Use rsync -vP username@host:/path/to/file .

The -P option preserves partially downloaded files and also shows progress.

As usual check man rsync

Conditional replacement of values in a data.frame

Another option would be to use case_when

require(dplyr)

mutate(df, est = case_when(
    b == 0 ~ (a - 5)/2.53, 
    TRUE   ~ est 
))

This solution becomes even more handy if more than 2 cases need to be distinguished, as it allows to avoid nested if_else constructs.

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

I've seen this several times. Usually, it's due to having a signed release version on my phone, then trying to deploy the debug version on top. It gets stuck in an invalid state where it's not fully uninstalled.

The solution that works for me is to open a command prompt and type:

adb uninstall my.package.id

That usually completes the uninstall in order for me to continue development.

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

Append data to a POST NSURLRequest

The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest rather than NSURLRequest. In its current form, I couldn't get it to respond to the setHTTPMethod call. Changing the type fixed things right up.

Does C# support multiple inheritance?

You can't inherit multiple classes at a time. But there is an options to do that by the help of interface. See below code

interface IA
{
    void PrintIA();
}

class  A:IA
{
    public void PrintIA()
    {
        Console.WriteLine("PrintA method in Base Class A");
    }
}

interface IB
{
    void PrintIB();
}

class B : IB
{
    public void PrintIB()
    {
        Console.WriteLine("PrintB method in Base Class B");
    }
}

public class AB: IA, IB
{
    A a = new A();
    B b = new B();

    public void PrintIA()
    {
       a.PrintIA();
    }

    public void PrintIB()
    {
        b.PrintIB();
    }
}

you can call them as below

AB ab = new AB();
ab.PrintIA();
ab.PrintIB();

How to kill an application with all its activities?

When you use the finish() method, it does not close the process completely , it is STILL working in background.

Please use this code in Main Activity (Please don't use in every activities or sub Activities):

@Override
public void onBackPressed() {

    android.os.Process.killProcess(android.os.Process.myPid());
    // This above line close correctly
}

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Python 3 ImportError: No module named 'ConfigParser'

I was getting the same error on Mac OS 10, Python 3.7.6 & Django 2.2.7. I want to use this opportunity to share what worked for me after trying out numerous solutions.

Steps

  1. Installed Connector/Python 8.0.20 for Mac OS from link

  2. Copy current dependencies into requirements.txt file, deactivated the current virtual env, and deleted it using;

    create the file if not already created with; touch requirements.txt

    copy dependency to file; python -m pip3 freeze > requirements.txt

    deactivate and delete current virtual env; deactivate && rm -rf <virtual-env-name>

  3. Created another virtual env and activated it using; python -m venv <virtual-env-name> && source <virtual-env-name>/bin/activate

  4. Install previous dependencies using; python -m pip3 install -r requirements.txt

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

Sorting an IList in C#

Convert your IList into List<T> or some other generic collection and then you can easily query/sort it using System.Linq namespace (it will supply bunch of extension methods)

How do I add a user when I'm using Alpine as a base image?

The commands are adduser and addgroup.

Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker
ENV UID=12345
ENV GID=23456

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "$(pwd)" \
    --ingroup "$USER" \
    --no-create-home \
    --uid "$UID" \
    "$USER"

Note the following:

  • --disabled-password prevents prompt for a password
  • --gecos "" circumvents the prompt for "Full Name" etc. on Debian-based systems
  • --home "$(pwd)" sets the user's home to the WORKDIR. You may not want this.
  • --no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        --home DIR           Home directory
        --gecos GECOS        GECOS field
        --shell SHELL        Login shell
        --ingroup GRP        Group (by name)
        --system             Create a system user
        --disabled-password  Don't assign a password
        --no-create-home     Don't create home directory
        --uid UID            User id

One thing to note is that if --ingroup isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

        --gid GID  Group id
        --system   Create a system group

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

My entrypoint helper script can be found on GitHub.

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.

(At the time of writing I don't have documentation for my script. It's still on the todo list!!)

Stopping a CSS3 Animation on last frame

Nobody actualy brought it so, the way it was made to work is animation-play-state set to paused.

How to clear all data in a listBox?

this should work:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear( );
}

How to calculate time difference in java?

Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.

Ah, give the above poster (genesiss) his due credit, code's always handy ;) Though, you now have an explanation as well :)

How can I find and run the keytool

Android: where to run keytool command in android

Keytool command can be run at your dos command prompt, if JRE has been set in your classpath variable.

For example, if you want to get the MD5 Fingerprint of the SDK Debug Certificate for android,

just run the following command...

C:\Documents and Settings\user\.android>  keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android

where C:\Documents and Settings\user\.android> is the path which contains the debug.keystore that has to be certified.

For detailed information, please visit http://code.google.com/android/add-ons/google-apis/mapkey.html#getdebugfingerprint

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

For me it only worked when the certificate and both keys were in the Login keychain. I had created a Development keychain before, but the Xcode Organizer wouldn't find the keys in there. So I moved them back to Login, quit the keychain tool - and voila, the error in Xcode Organizer went away! This was on Snow Leopard 10.6.2 with the 3.1.3 SDK.

maven error: package org.junit does not exist

Ok, you've declared junit dependency for test classes only (those that are in src/test/java but you're trying to use it in main classes (those that are in src/main/java).

Either do not use it in main classes, or remove <scope>test</scope>.

Sorting by date & time in descending order?

SELECT * FROM (
               SELECT id, name, form_id, DATE(updated_at) as date
               FROM wp_frm_items
               WHERE user_id = 11 && form_id=9
               ORDER BY updated_at DESC
             ) AS TEMP
    ORDER BY DATE(updated_at) DESC, name DESC

Give it a try.

What is the difference between "::" "." and "->" in c++

1.-> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2.. for accessing object member variables and methods via object instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

How to see PL/SQL Stored Function body in Oracle

You can also use DBMS_METADATA:

select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY', 'PADCAMPAIGN') 
from dual

Phonegap + jQuery Mobile, real world sample or tutorial

These may not solve exactly your "real-world problems", but perhaps something useful ...

Our web site includes PhoneGap and jQuery Mobile tutorials for a media player, barcode scanner, google maps, and OAuth.

Also, my github page has code, but no tutorial, for two apps:

  • AppLaudApp - a run-control, debugging enabling, download complementary app to a cloud IDE
  • NameTrendz - an app developed in at Android Dev Camp to do a bunch of queries about popular name data. The PhoneGap and jQuery Mobile versions are from March 2011.

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

Table column sizing

Updated 2018

Make sure your table includes the table class. This is because Bootstrap 4 tables are "opt-in" so the table class must be intentionally added to the table.

http://codeply.com/go/zJLXypKZxL

Bootstrap 3.x also had some CSS to reset the table cells so that they don't float..

table td[class*=col-], table th[class*=col-] {
    position: static;
    display: table-cell;
    float: none;
}

I don't know why this isn't is Bootstrap 4 alpha, but it may be added back in the final release. Adding this CSS will help all columns to use the widths set in the thead..

Bootstrap 4 Alpha 2 Demo


UPDATE (as of Bootstrap 4.0.0)

Now that Bootstrap 4 is flexbox, the table cells will not assume the correct width when adding col-*. A workaround is to use the d-inline-block class on the table cells to prevent the default display:flex of columns.

Another option in BS4 is to use the sizing utils classes for width...

<thead>
     <tr>
           <th class="w-25">25</th>
           <th class="w-50">50</th>
           <th class="w-25">25</th>
     </tr>
</thead>

Bootstrap 4 Alpha 6 Demo

Lastly, you could use d-flex on the table rows (tr), and the col-* grid classes on the columns (th,td)...

<table class="table table-bordered">
        <thead>
            <tr class="d-flex">
                <th class="col-3">25%</th>
                <th class="col-3">25%</th>
                <th class="col-6">50%</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-sm-3">..</td>
                <td class="col-sm-3">..</td>
                <td class="col-sm-6">..</td>
            </tr>
        </tbody>
    </table>

Bootstrap 4.0.0 (stable) Demo

Note: Changing the TR to display:flex can alter the borders

Empty an array in Java / processing

If Array xco is not final then a simple reassignment would work:

i.e.

xco = new Float[xco .length];

This assumes you need the Array xco to remain the same size. If that's not necessary then create an empty array:

xco= new Float[0];

"Full screen" <iframe>

Use this code instead of it:

    <frameset rows="100%,*">
        <frame src="-------------------------URL-------------------------------">
        <noframes>
            <body>
                Your browser does not support frames. To wiew this page please use supporting browsers.
            </body>
        </noframes>
    </frameset>

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

What does "javax.naming.NoInitialContextException" mean?

It means that there is no initial context :)

But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".

An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.

UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.

Difference between "char" and "String" in Java

A char consists of a single character and should be specified in single quotes. It can contain an alphabetic, numerical or even special character. below are a few examples:

char a = '4';
char b = '$';
char c = 'B';

A String defines a line can be used which is specified in double quotes. Below are a few examples:

String a = "Hello World";
String b = "1234";
String c = "%%";

How to split a delimited string into an array in awk?

echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

should work.

How set maximum date in datepicker dialog in android?

Use setMaxDate().

For example, replace return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay) statement with something like this:

    DatePickerDialog dialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
    dialog.getDatePicker().setMaxDate(new Date().getTime());
    return dialog;

What is the "right" JSON date format?

In Sharepoint 2013, getting data in JSON there is no format to convert date into date only format, because in that date should be in ISO format

yourDate.substring(0,10)

This may be helpful for you

How can I submit form on button click when using preventDefault()?

Replace this :

$('#subscription_order_form').submit(function(e){
  e.preventDefault();
});

with this:

$('#subscription_order_form').on('keydown', function(e){
    if (e.which===13) e.preventDefault();
});

FIDDLE

That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.

Error: Could not find or load main class in intelliJ IDE

File > Project Structure > Modules > Mark "src" folder as sources. This should fix the problem. Also check latest language is selected so that you don't have to change code or do any config changes. enter image description here

CSS last-child selector: select last-element of specific class, not last child inside of parent?

If you are floating the elements you can reverse the order

i.e. float: right; instead of float: left;

And then use this method to select the first-child of a class.

/* 1: Apply style to ALL instances */
#header .some-class {
  padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
  padding-right: 20px;
}

This is actually applying the class to the LAST instance only because it's now in reversed order.

Here is a working example for you:

<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
  border: 1px solid red;
  padding-right: 0;
}
#header .some-class~.some-class {
  border: 0;
  padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
  <img src="some_image" title="Logo" class="lfloat no-border"/>
  <ul class="some-class rfloat">
    <li>List 1-1</li>
    <li>List 1-2</li>
    <li>List 1-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 2-1</li>
    <li>List 2-2</li>
    <li>List 2-3</li>
  </ul>
  <ul class="some-class rfloat">
    <li>List 3-1</li>
    <li>List 3-2</li>
    <li>List 3-3</li>
  </ul>
  <img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>

Unity 2d jumping script

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

Create a List of primitive int?

Java Collection should be collections of Object only.

List<Integer> integerList = new ArrayList<Integer>();

Integer is wrapper class of primitive data type int.

more from JAVA wrapper classes here!

U can directly save and get int to/from integerList as, integerList.add(intValue); int intValue = integerList.get(i)

Is it safe to expose Firebase apiKey to the public?

I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below

  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }
}

No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains. One can read more about it on Firebase Security rules

Saving timestamp in mysql table using php

Better is use datatype varchar(15).

Parse error: Syntax error, unexpected end of file in my PHP code

also, look for a comment // that breaks the closing curly brace

if (1==1) { //echo "it is true"; }

the closing curly brace will not properly close the conditional section and php won't properly process the remainder of code.

Just what is an IntPtr exactly?

What is a Pointer?

In all languages, a pointer is a type of variable that stores a memory address, and you can either ask them to tell you the address they are pointing at or the value at the address they are pointing at.

A pointer can be thought of as a sort-of book mark. Except, instead of being used to jump quickly to a page in a book, a pointer is used to keep track of or map blocks of memory.

Imagine your program's memory precisely like one big array of 65535 bytes.

Pointers point obediently

Pointers remember one memory address each, and therefore they each point to a single address in memory.

As a group, pointers remember and recall memory addresses, obeying your every command ad nauseum.

You are their king.

Pointers in C#

Specifically in C#, a pointer is an integer variable that stores a memory address between 0 and 65534.

Also specific to C#, pointers are of type int and therefore signed.

You can't use negatively numbered addresses though, neither can you access an address above 65534. Any attempt to do so will throw a System.AccessViolationException.

A pointer called MyPointer is declared like so:

int *MyPointer;

A pointer in C# is an int, but memory addresses in C# begin at 0 and extend as far as 65534.

Pointy things should be handled with extra special care

The word unsafe is intended to scare you, and for a very good reason: Pointers are pointy things, and pointy things e.g. swords, axes, pointers, etc. should be handled with extra special care.

Pointers give the programmer tight control of a system. Therefore mistakes made are likely to have more serious consequences.

In order to use pointers, unsafe code has to be enabled in your program's properties, and pointers have to be used exclusively in methods or blocks marked as unsafe.

Example of an unsafe block

unsafe
{
    // Place code carefully and responsibly here.

}

How to use Pointers

When variables or objects are declared or instantiated, they are stored in memory.

  • Declare a pointer by using the * symbol prefix.

int *MyPointer;

  • To get the address of a variable, you use the & symbol prefix.

MyPointer = &MyVariable;

Once an address is assigned to a pointer, the following applies:

  • Without * prefix to refer to the memory address being pointed to as an int.

MyPointer = &MyVariable; // Set MyPointer to point at MyVariable

  • With * prefix to get the value stored at the memory address being pointed to.

"MyPointer is pointing at " + *MyPointer;

Since a pointer is a variable that holds a memory address, this memory address can be stored in a pointer variable.

Example of pointers being used carefully and responsibly

    public unsafe void PointerTest()
    {
        int x = 100; // Create a variable named x

        int *MyPointer = &x; // Store the address of variable named x into the pointer named MyPointer

        textBox1.Text = ((int)MyPointer).ToString(); // Displays the memory address stored in pointer named MyPointer

        textBox2.Text = (*MyPointer).ToString(); // Displays the value of the variable named x via the pointer named MyPointer.

    }

Notice the type of the pointer is an int. This is because C# interprets memory addresses as integer numbers (int).

Why is it int instead of uint?

There is no good reason.

Why use pointers?

Pointers are a lot of fun. With so much of the computer being controlled by memory, pointers empower a programmer with more control of their program's memory.

Memory monitoring.

Use pointers to read blocks of memory and monitor how the values being pointed at change over time.

Change these values responsibly and keep track of how your changes affect your computer.

Which ORM should I use for Node.js and MySQL?

First off, please note that I haven't used either of them (but have used Node.js).

Both libraries are documented quite well and have a stable API. However, persistence.js seems to be used in more projects. I don't know if all of them still use it, though.

The developer of sequelize sometimes blogs about it at blog.depold.com. When you'd like to use primary keys as foreign keys, you'll need the patch that's described in this blog post. If you'd like help for persistence.js there is a google group devoted to it.

From the examples I gather that sequelize is a bit more JavaScript-like (more sugar) than persistance.js but has support for fewer datastores (only MySQL, while persistance.js can even use in-browser stores).

I think that sequelize might be the way to go for you, as you only need MySQL support. However, if you need some convenient features (for instance search) or want to use a different database later on you'd need to use persistence.js.

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

Convert output of MySQL query to utf8

SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table 

json call with C#

In your code you don't get the HttpResponse, so you won't see what the server side sends you back.

you need to get the Response similar to the way you get (make) the Request. So

public static bool SendAnSMSMessage(string message)
{
  var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
  httpWebRequest.ContentType = "text/json";
  httpWebRequest.Method = "POST";

  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
    string json = "{ \"method\": \"send\", " +
                      "  \"params\": [ " +
                      "             \"IPutAGuidHere\", " +
                      "             \"[email protected]\", " +
                      "             \"MyTenDigitNumberWasHere\", " +
                      "             \"" + message + "\" " +
                      "             ] " +
                      "}";

    streamWriter.Write(json);
  }
  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    var responseText = streamReader.ReadToEnd();
    //Now you have your response.
    //or false depending on information in the response
    return true;        
  }
}

I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

R: rJava package install failing

I was facing the same problem while using Windows 10. I have solved the problem using the following procedure

  1. Download Java from https://java.com/en/download/windows-64bit.jsp for 64-bit windows\Install it
  2. Download Java development kit from https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html for 64-bit windows\Install it
  3. Then right click on “This PC” icon in desktop\Properties\Advanced system settings\Advanced\Environment Variables\Under System variables select Path\Click Edit\Click on New\Copy and paste paths “C:\Program Files\Java\jdk1.8.0_201\bin” and “C:\Program Files\Java\jre1.8.0_201\bin” (without quote) \OK\OK\OK

Note: jdk1.8.0_201 and jre1.8.0_201 will be changed depending on the version of Java development kit and Java

  1. In Environment Variables window go to User variables for User\Click on New\Put Variable name as “JAVA_HOME” and Variable value as “C:\Program Files\Java\jdk1.8.0_201\bin”\Press OK

To check the installation, open CMD\Type javac\Press Enter and Type java\press enter It will show enter image description here

In RStudio run

Sys.setenv(JAVA_HOME="C:\\Program Files\\Java\\jdk1.8.0_201")

Note: jdk1.8.0_201 will be changed depending on the version of Java development kit

Now you can install and load rJava package without any problem.

Get Today's date in Java at midnight time

Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); //format it as per your requirement
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=>  " + dateNow);

How to test if JSON object is empty in Java

Try /*string with {}*/ string.trim().equalsIgnoreCase("{}")), maybe there is some extra spaces or something

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

How do you use "git --bare init" repository?

You can execute the following commands to initialize your local repository

mkdir newProject
cd newProject
touch .gitignore
git init
git add .
git commit -m "Initial Commit"
git remote add origin user@host:~/path_on_server/newProject.git
git push origin master

You should work on your project from your local repository and use the server as the central repository.

You can also follow this article which explains each and every aspect of creating and maintaining a Git repository. Git for Beginners

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

Java reverse an int value without using array

It is an outdated question, but as a reference for others First of all reversedNum must be initialized to 0;

input%10 is used to get the last digit from input

input/10 is used to get rid of the last digit from input, which you have added to the reversedNum

Let's say input was 135

135 % 10 is 5 Since reversed number was initialized to 0 now reversedNum will be 5

Then we get rid of 5 by dividing 135 by 10

Now input will be just 13

Your code loops through these steps until all digits are added to the reversed number or in other words untill input becomes 0.

How do I configure git to ignore some files locally?

Update: Consider using git update-index --skip-worktree [<file>...] instead, thanks @danShumway! See Borealid's explanation on the difference of the two options.


Old answer:

If you need to ignore local changes to tracked files (we have that with local modifications to config files), use git update-index --assume-unchanged [<file>...].

How to Import .bson file format on mongodb

You have to run this mongorestore command via cmd and not on Mongo Shell... Have a look at below command on...

Run this command on cmd (not on Mongo shell)

>path\to\mongorestore.exe -d dbname -c collection_name path\to\same\collection.bson

Here path\to\mongorestore.exe is path of mongorestore.exe inside bin folder of mongodb. dbname is name of databse. collection_name is name of collection.bson. path\to\same\collection.bson is the path up to that collection.

Now from mongo shell you can verify that database is created or not (If it does not exist, database with same name will be created with collection).

How can I make a time delay in Python?

You also can try this:

import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job

Now the shell will not crash or not react.

Material UI and Grid system

Below is made by purely MUI Grid system,

MUI - Grid Layout

With the code below,

// MuiGrid.js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
    backgroundColor: "#b5b5b5",
    margin: "10px"
  }
}));

export default function FullWidthGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container spacing={0}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>xs=12</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

↓ CodeSandbox ↓

Edit MUI-Grid system

Command to list all files in a folder as well as sub-folders in windows

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

How to replace specific values in a oracle database column?

Use REPLACE:

SELECT REPLACE(t.column, 'est1', 'rest1')
  FROM MY_TABLE t

If you want to update the values in the table, use:

UPDATE MY_TABLE t
   SET column = REPLACE(t.column, 'est1', 'rest1')

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

Get Path from another app (WhatsApp)

you can try to this , then you get a bitmap of selected image and then you can easily find it's native path from Device Default Gallery.

Bitmap roughBitmap= null;
    try {
    // Works with content://, file://, or android.resource:// URIs
    InputStream inputStream =
    getContentResolver().openInputStream(uri);
    roughBitmap= BitmapFactory.decodeStream(inputStream);

    // calc exact destination size
    Matrix m = new Matrix();
    RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
    RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
    m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
    float[] values = new float[9];
    m.GetValues(values);


    // resize bitmap if needed
    Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);

    string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
    var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
    Java.IO.File file = new Java.IO.File(sdCardPath);
    if (!file.Exists())
    {
        file.Mkdir();
    }
    var filePath = System.IO.Path.Combine(sdCardPath, name);
    } catch (FileNotFoundException e) {
    // Inform the user that things have gone horribly wrong
    }

Access a function variable outside the function without using "global"

The problem is you were calling print x.bye after you set x as a string. When you run x = hi() it runs hi() and sets the value of x to 5 (the value of bye; it does NOT set the value of x as a reference to the bye variable itself). EX: bye = 5; x = bye; bye = 4; print x; prints 5, not 4

Also, you don't have to run hi() twice, just run x = hi(), not hi();x=hi() (the way you had it it was running hi(), not doing anything with the resulting value of 5, and then rerunning the same hi() and saving the value of 5 to the x variable.

So full code should be

def hi():
    something
    something
    bye = 5
    return bye 
x = hi()
print x

If you wanted to return multiple variables, one option would be to use a list, or dictionary, depending on what you need.

ex:

def hi():
    something
    xyz = { 'bye': 7, 'foobar': 8}
    return xyz
x = hi()
print x['bye']

more on python dictionaries at http://docs.python.org/2/tutorial/datastructures.html#dictionaries

How to use "like" and "not like" in SQL MSAccess for the same field?

What I found out is that MS Access will reject --Not Like "BB*"-- if not enclosed in PARENTHESES, unlike --Like "BB*"-- which is ok without parentheses.

I tested these on MS Access 2010 and are all valid:

  1. Like "BB"

  2. (Like "BB")

  3. (Not Like "BB")

How to hide keyboard in swift on pressing return key?

The return true part of this only tells the text field whether or not it is allowed to return.
You have to manually tell the text field to dismiss the keyboard (or what ever its first responder is), and this is done with resignFirstResponder(), like so:

// Called on 'Return' pressed. Return false to ignore.

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    textField.resignFirstResponder()
    return true
}

JSON Parse File Path

My case of working code is:

var request = new XMLHttpRequest();
request.open("GET", "<path_to_file>", false);
request.overrideMimeType("application/json");
request.send(null);
var jsonData = JSON.parse(request.responseText);
console.log(jsonData);

PHP function overloading

It may be hackish to some, but I learned this way from how Cakephp does some functions and have adapted it because I like the flexibility it creates

The idea is you have different type of arguments, arrays, objects etc, then you detect what you were passed and go from there

function($arg1, $lastname) {
    if(is_array($arg1)){
        $lastname = $arg1['lastname'];
        $firstname = $arg1['firstname'];
    } else {
        $firstname = $arg1;
    }
    ...
}

Add carriage return to a string

Another option:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));

How to assign a NULL value to a pointer in python?

Normally you can use None, but you can also use objc.NULL, e.g.

import objc
val = objc.NULL

Especially useful when working with C code in Python.

Also see: Python objc.NULL Examples

Remove stubborn underline from link

You are not applying text-decoration: none; to an anchor (.boxhead a) but to a span element (.boxhead).

Try this:

.boxhead a {
    color: #FFFFFF;
    text-decoration: none;
}

How to specify credentials when connecting to boto3 S3?

You can get a client with new session directly like below.

 s3_client = boto3.client('s3', 
                      aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY, 
                      aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY, 
                      region_name=REGION_NAME
                      )

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Get user info via Google API

There are 3 steps that needs to be run.

  1. Register your app's client id from Google API console
  2. Ask your end user to give consent using this api https://developers.google.com/identity/protocols/OpenIDConnect#sendauthrequest
  3. Use google's oauth2 api as described at https://any-api.com/googleapis_com/oauth2/docs/userinfo/oauth2_userinfo_v2_me_get using the token obtained in step 2. (Though still I could not find how to fill "fields" parameter properly).

It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_emailparameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)

I find facebook's OAuth mechanics much much clearly described.

RegEx to match stuff between parentheses

Use this expression:

/\(([^()]+)\)/g

e.g:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
    alert(mts[0]);
    alert(mts[1]);
}

Docker: How to use bash with an Alpine based docker image?

RUN /bin/sh -c "apk add --no-cache bash"

worked for me.

What is the benefit of zerofill in MySQL?

When you select a column with type ZEROFILL it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL also implies UNSIGNED.

Using ZEROFILL and a display width has no effect on how the data is stored. It affects only how it is displayed.

Here is some example SQL that demonstrates the use of ZEROFILL:

CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);
INSERT INTO yourtable (x,y) VALUES
(1, 1),
(12, 12),
(123, 123),
(123456789, 123456789);
SELECT x, y FROM yourtable;

Result:

        x          y
 00000001          1
 00000012         12
 00000123        123
123456789  123456789

What's the difference between window.location and document.location in JavaScript?

Well yea, they are the same, but....!

window.location is not working on some Internet Explorer browsers.

jQuery Upload Progress and AJAX file upload

Here are some options for using AJAX to upload files:

UPDATE: Here is a JQuery plug-in for Multiple File Uploading.

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

I've made a category from @Abizern answer

@implementation NSString (Extensions)
- (NSDictionary *) json_StringToDictionary {
    NSError *error;
    NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error];
    return (!json ? nil : json);
}
@end

Use it like this,

NSString *jsonString = @"{\"2\":\"3\"}";
NSLog(@"%@",[jsonString json_StringToDictionary]);

Forcing anti-aliasing using css: Is this a myth?

Adding the following line of CSS works for Chrome, but not Internet Explorer or Firefox.

text-shadow: #fff 0px 1px 1px;

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

Call Python function from JavaScript code

Communicating through processes

Example:

Python: This python code block should return random temperatures.

# sensor.py

import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float
    temperatures.push(parseFloat(data));
    console.log(temperatures);
});

exception in thread 'main' java.lang.NoClassDefFoundError:

Try doing

javac Hello.java

and then, if it comes up with no compiler errors (which it should not do because I cannot see any bugs in your programme), then type

java Hello

Comparing strings by their alphabetical order

You can call either string's compareTo method (java.lang.String.compareTo). This feature is well documented on the java documentation site.

Here is a short program that demonstrates it:

class StringCompareExample {
    public static void main(String args[]){
        String s1 = "Project"; String s2 = "Sunject";
        verboseCompare(s1, s2);
        verboseCompare(s2, s1);
        verboseCompare(s1, s1);
    }

    public static void verboseCompare(String s1, String s2){
        System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");

        int comparisonResult = s1.compareTo(s2);
        System.out.println("The result of the comparison was " + comparisonResult);

        System.out.print("This means that \"" + s1 + "\" ");
        if(comparisonResult < 0){
            System.out.println("lexicographically precedes \"" + s2 + "\".");
        }else if(comparisonResult > 0){
            System.out.println("lexicographically follows \"" + s2 + "\".");
        }else{
            System.out.println("equals \"" + s2 + "\".");
        }
        System.out.println();
    }
}

Here is a live demonstration that shows it works: http://ideone.com/Drikp3

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

PHP Unset Session Variable

If you completely want to clear the session you can use this:

session_unset();
session_destroy();

Actually both are not neccessary but it does not hurt.

If you want to clear only a specific part I think you need this:

unset($_SESSION['Products']);
//or
$_SESSION['Products'] = "";

depending on what you need.

Visual Studio 2017 does not have Business Intelligence Integration Services/Projects

I havent tried this scenario yet - I was scared off by the (unanswered) comments below the GA announcement blog post:

https://blogs.msdn.microsoft.com/ssdt/2017/04/19/announcing-the-general-availability-ga-release-of-ssdt-17-0-april-2017/

I'll be staying on VS15 for a while ...

How to customize the background/border colors of a grouped table view cell?

I know the answers are relating to changing grouped table cells, but in case someone is wanting to also change the tableview's background color:

Not only do you need to set:

tableview.backgroundColor = color;

You also need to change or get rid of the background view:

tableview.backgroundView = nil;  

Insertion sort vs Bubble Sort Algorithms

Insertion sort can be resumed as "Look for the element which should be at first position(the minimum), make some space by shifting next elements, and put it at first position. Good. Now look at the element which should be at 2nd...." and so on...

Bubble sort operate differently which can be resumed as "As long as I find two adjacent elements which are in the wrong order, I swap them".

ImportError: No module named sqlalchemy

first install the library

pip install flask_sqlalchemy 

after that

from flask_sqlalchemy import SQLAlchemy

put this in app.py file to get the access of database through SQLAlchemy

C++ deprecated conversion from string constant to 'char*'

There are 3 solutions:

Solution 1:

const char *x = "foo bar";

Solution 2:

char *x = (char *)"foo bar";

Solution 3:

char* x = (char*) malloc(strlen("foo bar")+1); // +1 for the terminator
strcpy(x,"foo bar");

Arrays also can be used instead of pointers because an array is already a constant pointer.

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

require is not defined? Node.js

Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.

See browserify or webpack if you wish to serve browser-specific modules from Node.

No content to map due to end-of-input jackson parser

The problem for me was that I read the response twice as follows:

System.out.println(response.body().string());
getSucherResponse = objectMapper.readValue(response.body().string(), GetSucherResponse.class);

However, the response can only be read once as it is a stream.

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

How to implement history.back() in angular.js

There was a syntax error. Try this and it should work:

directives.directive('backButton', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function () {
                history.back();
                scope.$apply();
            });
        }
    }
});

Ubuntu: OpenJDK 8 - Unable to locate package

I was having the same issue and tried all of the solutions on this page but none of them did the trick.

What finally worked was adding the universe repo to my repo list. To do that run the following command

sudo add-apt-repository universe

After running the above command I was able to run

sudo apt install openjdk-8-jre

without an issue and the package was installed.

Hope this helps someone.

How do I import a .sql file in mysql database using PHP?

As we all know MySQL was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0 ref so I have converted accepted answer to mysqli.

<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';

$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));

// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
    continue;

// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
    // Perform the query
    mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
 echo "Tables imported successfully";
?>

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

I think the complication may also occur when trying to nest multiple Divs within the return statement. You may wish to do this to ensure your components render as block elements.

Here's an example of correctly rendering a couple of components, using multiple divs.

return (
  <div>
    <h1>Data Information</H1>
    <div>
      <Button type="primary">Create Data</Button>
    </div>
  </div>
)

Tensorflow import error: No module named 'tensorflow'

I think your tensorflow is not installed for local environment.The best way of installing tensorflow is to create virtualenv as describe in the tensorflow installation guide Tensorflow Installation .After installing you can activate the invironment and can run anypython script under that environment.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.

Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.

You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

Can't bind to 'ngModel' since it isn't a known property of 'input'

For me the issue was, I forgot to declare the component in the declarations array of the module.

@NgModule({
 declarations: [yourcomponentName]
})

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

window.open(url, '_blank'); not working on iMac/Safari

window.location.assign(url) this fixs the window.open(url) issue in ios devices

Loop through JSON object List

had same problem today, Your topic helped me so here goes solution ;)

 alert(result.d[0].EmployeeTitle);

Make anchor link go some pixels above where it's linked to

Using only css and having no problems with covered and unclickable content before (the point of this is the pointer-events:none):

CSS

.anchored::before {
    content: '';
    display: block;
    position: relative;
    width: 0;
    height: 100px;
    margin-top: -100px;
}

HTML

<a href="#anchor">Click me!</a>
<div style="pointer-events:none;">
<p id="anchor" class="anchored">I should be 100px below where I currently am!</p>
</div>

Twitter bootstrap 3 two columns full height

Ok, I've achieved the same thing using Bootstrap 3.0

Example with the latest bootstrap

http://jsfiddle.net/HDNQS/1/

The HTML:

<div class="header">
    whatever
</div>
<div class="container-fluid wrapper">
    <div class="row">
        <div class="col-md-3 navigation"></div>
        <div class="col-md-9 content"></div>
    </div>
</div>

The SCSS:

html, body, .wrapper {
    padding: 0;
    margin: 0;
    height: 100%;
}

$headerHeight: 43px;

.navigation, .content {
    display: table-cell;
    float: none;
    vertical-align: top;
}

.wrapper {
    display: table;
    width: 100%;
    margin-top: -$headerHeight;
    padding-top: $headerHeight;
}

.header {
    height: $headerHeight;
}

.row {
    height: 100%;
    margin: 0;
    display: table-row;
    &:before, &:after {
        content: none;
    }
}

.navigation {
    background: #4a4d4e;
    padding-left: 0;
    padding-right: 0;
}

C fopen vs open

open() is a system call and specific to Unix-based systems and it returns a file descriptor. You can write to a file descriptor using write() which is another system call.
fopen() is an ANSI C function call which returns a file pointer and it is portable to other OSes. We can write to a file pointer using fprintf.

In Unix:
You can get a file pointer from the file descriptor using:

fP = fdopen(fD, "a");

You can get a file descriptor from the file pointer using:

fD = fileno (fP);

maven "cannot find symbol" message unhelpful

update to 3.1 :

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
        <source>1.7</source>
        <target>1.7</target>
    </configuration>
</plugin>

What does {0} mean when found in a string in C#?

It's a placeholder in the string.

For example,

string b = "world.";

Console.WriteLine("Hello {0}", b);

would produce this output:

Hello world.

Also, you can have as many placeholders as you wish. This also works on String.Format:

string b = "world.";
string a = String.Format("Hello {0}", b);

Console.WriteLine(a);

And you would still get the very same output.

Android. WebView and loadData

As I understand it, loadData() simply generates a data: URL with the data provide it.

Read the javadocs for loadData():

If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):

String data = ...;  // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");

How do I hide an element on a click event anywhere outside of the element?

$('html').click(function() {
//Hide the menus if it is visible
});

$('#menu_container').click(function(event){
    event.stopPropagation();
});

but you need to keep in mind these things as well. http://css-tricks.com/dangers-stopping-event-propagation/

Calculating the distance between 2 points

You can use the below formula to find the distance between the 2 points:

distance*distance = ((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1))

android lollipop toolbar: how to hide/show the toolbar while scrolling?

Just add this property inside your toolbar and its done

app:layout_scrollFlags="scroll|enterAlways"

Isn't is awesome

How to download image from url

.net Framework allows PictureBox Control to Load Images from url

and Save image in Laod Complete Event

protected void LoadImage() {
 pictureBox1.ImageLocation = "PROXY_URL;}

void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e) {
   pictureBox1.Image.Save(destination); }

Chrome - ERR_CACHE_MISS

This is an issue distinct to Chrome, but there are two paths you can take to fix it.

I noticed the error once I added this specific header to my PHP script.

header('Content-Type: application/json');

The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).

Clear History and Reload Page on Login/Logout Using Ionic Framework

I was trying to do refresh page using angularjs when i saw websites i got confused but no code was working for the code then i got solution for reloading page using

$state.go('path',null,{reload:true});

use this in a function this will work.

How to getText on an input in protractor

You have to use Promise to print or store values of element.

 var ExpectedValue:string ="AllTestings.com";
          element(by.id("xyz")).getAttribute("value").then(function (Text) {

                        expect(Text.trim()).toEqual("ExpectedValue", "Wrong page navigated");//Assertion
        console.log("Text");//Print here in Console

                    });

PHP 5 disable strict standards error

The default value of error_reporting flag is E_ALL & ~E_NOTICE if not set in php.ini. But in some installation (particularly installations targeting development environments) has E_ALL | E_STRICT set as value of this flag (this is the recommended value during development). In some cases, specially when you'll want to run some open source projects, that was developed prior to PHP 5.3 era and not yet updated with best practices defined by PHP 5.3, in your development environment, you'll probably run into getting some messages like you are getting. The best way to cope up on this situation, is to set only E_ALL as the value of error_reporting flag, either in php.ini or in code (probably in a front-controller like index.php in web-root as follows:

if(defined('E_STRICT')){
    error_reporting(E_ALL);
}

MySQL DROP all tables, ignoring foreign keys

In a Linux shell like bash/zsh:

DATABASE_TO_EMPTY="your_db_name";
{ echo "SET FOREIGN_KEY_CHECKS = 0;" ; \
  mysql "$DATABASE_TO_EMPTY" --skip-column-names -e \
  "SELECT concat('DROP TABLE IF EXISTS ', table_name, ';') \
   FROM information_schema.tables WHERE table_schema = '$DATABASE_TO_EMPTY';";\
  } | mysql "$DATABASE_TO_EMPTY"

This will generate the commands, then immediately pipe them to a 2nd client instance which will delete the tables.

The clever bit is of course copied from other answers here - I just wanted a copy-and-pasteable one-liner (ish) to actually do the job the OP wanted.

Note of course you'll have to put your credentials in (twice) in these mysql commands, too, unless you have a very low security setup. (or you could alias your mysql command to include your creds.)

How to make the 'cut' command treat same sequental delimiters as one?

shortest/friendliest solution

After becoming frustrated with the too many limitations of cut, I wrote my own replacement, which I called cuts for "cut on steroids".

cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.

One example, out of many, addressing this particular question:

$ cat text.txt
0   1        2 3
0 1          2   3 4

$ cuts 2 text.txt
2
2

cuts supports:

  • auto-detection of most common field-delimiters in files (+ ability to override defaults)
  • multi-char, mixed-char, and regex matched delimiters
  • extracting columns from multiple files with mixed delimiters
  • offsets from end of line (using negative numbers) in addition to start of line
  • automatic side-by-side pasting of columns (no need to invoke paste separately)
  • support for field reordering
  • a config file where users can change their personal preferences
  • great emphasis on user friendliness & minimalist required typing

and much more. None of which is provided by standard cut.

See also: https://stackoverflow.com/a/24543231/1296044

Source and documentation (free software): http://arielf.github.io/cuts/

How to find out which package version is loaded in R?

Old question, but not among the answers is my favorite command to get a quick and short overview of all loaded packages:

(.packages())

To see which version is installed of all loaded packages, just use the above command to subset installed.packages().

installed.packages()[(.packages()),3]

By changing the column number (3 for package version) you can get any other information stored in installed.packages() in an easy-to-read matrix. Below is an example for version number and dependency:

installed.packages()[(.packages()),c(3,5)]

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

Change Screen Orientation programmatically using a Button

A working code:

private void changeScreenOrientation() {
    int orientation = yourActivityName.this.getResources().getConfiguration().orientation;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        showMediaDescription();
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        hideMediaDescription();
    }
    if (Settings.System.getInt(getContentResolver(),
            Settings.System.ACCELEROMETER_ROTATION, 0) == 1) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            }
        }, 4000);
    }
}

call this method in your button click

Insert all values of a table into another table in SQL

From here:

SELECT *
INTO new_table_name [IN externaldatabase] 
FROM old_tablename

Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation

Defining insertable=false, updatable=false is useful when you need to map a field more than once in an entity, typically:

This is IMO not a semantical thing, but definitely a technical one.

How make background image on newsletter in outlook?

you cannot add a background image to an html newsletter which is to be viewed in outlook. It just wont work, as they ignore the property.

You can only have block colours (background-color) behind text.

Outlook doesn't support the following CSS:

azimuth
background-attachment
background-image
background-position
background-repeat
border-spacing
bottom
caption-side
clear
clip
content
counter-increment
counter-reset
cue-before, cue-after, cue
cursor
display
elevation
empty-cells
float
font-size-adjust
font-stretch
left
line-break
list-style-image
list-style-position
marker-offset
max-height
max-width
min-height
min-width
orphans
outline
outline-color
outline-style
outline-width
overflow
overflow-x
overflow-y
pause-before, pause-after, pause
pitch
pitch-range
play-during
position
quotes
richness
right
speak
speak-header
speak-numeral
speak-punctuation
speech-rate
stress
table-layout
text-shadow
text-transform
top
unicode-bidi
visibility
voice-family
volume
widows
word-spacing
z-index

Source: http://msdn.microsoft.com/en-us/library/aa338201.aspx

UPDATE - July 2015

I thought it best to update this list as it gets the odd upvote every now and then - a great link to current email client support is available here: https://www.campaignmonitor.com/css/

How to return a dictionary | Python


def query(id):
    for line in file:
        table = line.split(";")
        if id == int(table[0]):
             yield table
    
    

id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
  print("ID: " + id_)
  print("Name: " + name)
  print("City: " + city)
file.close()

Using yield..