Programs & Examples On #Myisam

MyISAM is a non-transactional storage engine for MySQL. It provides high-speed storage and retrieval, as well as fulltext searching capabilities. Also, it is the default storage engine type for versions prior to 5.5.

Is there a REAL performance difference between INT and VARCHAR primary keys?

For short codes, there's probably no difference. This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).

For larger tables with a wider variation among the key, this can be dangerous. Think about using e-mail address/user name from a User table, for example. What happens when you have a few million users and some of those users have long names or e-mail addresses. Now any time you need to join this table using that key it becomes much more expensive.

How to properly create composite primary keys - MYSQL

I would use a composite (multi-column) key.

CREATE TABLE INFO (
    t1ID INT,
    t2ID INT,
    PRIMARY KEY (t1ID, t2ID)
) 

This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

MyISAM versus InnoDB

In short, InnoDB is good if you are working on something that needs a reliable database that can handles a lot of INSERT and UPDATE instructions.

and, MyISAM is good if you needs a database that will mostly be taking a lot of read (SELECT) instructions rather than write (INSERT and UPDATES), considering its drawback on the table-lock thing.

you may want to check out;
Pros and Cons of InnoDB
Pros and Cons of MyISAM

How to test an SQL Update statement before running it?

In these cases that you want to test, it's a good idea to focus on only current column values and soon-to-be-updated column values.

Please take a look at the following code that I've written to update WHMCS prices:

# UPDATE tblinvoiceitems AS ii

SELECT                        ###  JUST
    ii.amount AS old_value,   ###  FOR
    h.amount AS new_value     ###  TESTING
FROM tblinvoiceitems AS ii    ###  PURPOSES.

JOIN tblhosting AS h ON ii.relid = h.id
JOIN tblinvoices AS i ON ii.invoiceid = i.id

WHERE ii.amount <> h.amount   ### Show only updatable rows

# SET ii.amount = h.amount

This way we clearly compare already existing values versus new values.

How can I check MySQL engine type for a specific table?

SHOW CREATE TABLE <tablename>;

Less parseable but more readable than SHOW TABLE STATUS.

How to write :hover condition for a:before and a:after?

You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    span {
    font-size:12px;
    }
    a {
        color:green;
    }
    .test1>a:hover span {
        display:none;
    }
    .test1>a:hover:before {
        color:red;
        content:"Apple";
    }
  </style>
</head>

<body>
  <div class="test1">
    <a href="#"><span>Google</span></a>
  </div>
  <div class="test2">
    <a href="#"><span>Apple</span></a>
  </div>
</body>

</html>

Note: The hover:before switch works only on the .test1 class

Plotting a fast Fourier transform in Python

I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.

Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:

import matplotlib.pyplot as plt
import numpy as np
import warnings


def fftPlot(sig, dt=None, plot=True):
    # Here it's assumes analytic signal (real signal...) - so only half of the axis is required

    if dt is None:
        dt = 1
        t = np.arange(0, sig.shape[-1])
        xLabel = 'samples'
    else:
        t = np.arange(0, sig.shape[-1]) * dt
        xLabel = 'freq [Hz]'

    if sig.shape[0] % 2 != 0:
        warnings.warn("signal preferred to be even in size, autoFixing it...")
        t = t[0:-1]
        sig = sig[0:-1]

    sigFFT = np.fft.fft(sig) / t.shape[0]  # Divided by size t for coherent magnitude

    freq = np.fft.fftfreq(t.shape[0], d=dt)

    # Plot analytic signal - right half of frequence axis needed only...
    firstNegInd = np.argmax(freq < 0)
    freqAxisPos = freq[0:firstNegInd]
    sigFFTPos = 2 * sigFFT[0:firstNegInd]  # *2 because of magnitude of analytic signal

    if plot:
        plt.figure()
        plt.plot(freqAxisPos, np.abs(sigFFTPos))
        plt.xlabel(xLabel)
        plt.ylabel('mag')
        plt.title('Analytic FFT plot')
        plt.show()

    return sigFFTPos, freqAxisPos


if __name__ == "__main__":
    dt = 1 / 1000

    # Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
    f0 = 200  # [Hz]
    t = np.arange(0, 1 + dt, dt)
    sig = 1 * np.sin(2 * np.pi * f0 * t) + \
        10 * np.sin(2 * np.pi * f0 / 2 * t) + \
        3 * np.sin(2 * np.pi * f0 / 4 * t) +\
        7.5 * np.sin(2 * np.pi * f0 / 5 * t)

    # Result in frequencies
    fftPlot(sig, dt=dt)
    # Result in samples (if the frequencies axis is unknown)
    fftPlot(sig)

Analytic FFT plot result

How to install libusb in Ubuntu

you can creat symlink to your libusb after locate it in your system :

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so.0.1.0 

sudo ln -s /lib/x86_64-linux-gnu/libusb-1.0.so.0 /usr/lib/libusbx-1.0.so

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
... 
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

Add newly created specific folder to .gitignore in Git

For this there are two cases

Case 1: File already added to git repo.

Case 2: File newly created and its status still showing as untracked file when using

git status

If you have case 1:

STEP 1: Then run

git rm --cached filename 

to remove it from git repo cache

if it is a directory then use

git rm -r --cached  directory_name

STEP 2: If Case 1 is over then create new file named .gitignore in your git repo

STEP 3: Use following to tell git to ignore / assume file is unchanged

git update-index --assume-unchanged path/to/file.txt

STEP 4: Now, check status using git status open .gitignore in your editor nano, vim, geany etc... any one, add the path of the file / folder to ignore. If it is a folder then user folder_name/* to ignore all file.

If you still do not understand read the article git ignore file link.

How to check if the URL contains a given string?

Regular Expressions will be more optimal for a lot of people because of word boundaries \b or similar devices. Word boundaries occur when any of 0-9, a-z, A-Z, _ are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.

if (location.href.match(/(?:\b|_)franky(?:\b|_)))

If you use if(window.location.href.indexOf("sam"), you'll get matches for flotsam and same, among other words. tom would match tomato and tomorrow, without regex.

Making it case-sensitive is as simple as removing the i.

Further, adding other filters is as easy as

if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i))

Let's talk about (?:\b|_). RegEx typically defines _ as a word character so it doesn't cause a word boundary. We use this (?:\b|_) to deal with this. To see if it either finds \b or _ on either side of the string.

Other languages may need to use something like

if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i))
//where xxx is a character representation (range or literal) of your language's alphanumeric characters.

All of this is easier than saying

var x = location.href // just used to shorten the code
x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam")...
// and other comparisons to see if the url ends with it 
// more for other filters like frank and billy

Other languages' flavors of Regular Expressions support \p{L} but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p{L}](filters|in|any|alphabet)[^\p{L}]

What does "<>" mean in Oracle

Does not equal. The opposite of =, equivalent to !=.

Also, for everyone's info, this can return a non-zero number of rows. I see the OP has reformatted his question so it's a bit clearer, but as far as I can tell, this finds records where product ID is among those found in order #605, as is quantity, but it's not actually order #605. If order #605 contains 1 apple, 2 bananas and 3 crayons, #604 should match if it contains 2 apples (but not 3 dogs). It just won't match order #605. (And if ordid is unique, then it would find exact duplicates.)

Split string into strings by length?

I tried Alexanders answer but got this error in Python3:

TypeError: 'float' object cannot be interpreted as an integer

This is because the division operator in Python3 is returning a float. This works for me:

>>> x = "qwertyui"
>>> chunks, chunk_size = len(x), len(x)//4
>>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
['qw', 'er', 'ty', 'ui']

Notice the // at the end of line 2, to ensure truncation to an integer.

How to hide element label by element id in CSS?

Despite other answers here, you should not use display:none to hide the label element.

The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).

label[for="foo"] { 
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

How to load an ImageView by URL in Android?

public class LoadWebImg extends Activity {

String image_URL=
 "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);
    bmImage.setImageBitmap(bm);
   }

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
   {       
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
           in.close();
       } catch (IOException e1) {
       }
       return bitmap;               
   }

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

 try{
  HttpURLConnection httpConn = (HttpURLConnection)conn;
  httpConn.setRequestMethod("GET");
  httpConn.connect();

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
  }
 }
 catch (Exception ex)
 {
 }
 return inputStream;
}
}

cmake - find_library - custom library location

The simplest solution may be to add HINTS to each find_* request.

For example:

find_library(CURL_LIBRARY
    NAMES curl curllib libcurl_imp curllib_static
    HINTS "${CMAKE_PREFIX_PATH}/curl/lib"
)

For Boost I would strongly recommend using the FindBoost standard module and setting the BOOST_DIR variable to point to your Boost libraries.

Checking whether a String contains a number value in Java

Why don't you try to write a function based on Integer.parseInt(String obj) ? The function could accept as parameter your String object, and then tokenize the String and use Integer.parseInt(String obj) to extract the number from the "lucky" substring...

Javadoc of Integer.parseInt(String obj)

DBCC CHECKIDENT Sets Identity to 0

It seems ridiculous that you can't set/reset an identity column with a single command to cover both cases of whether or not the table has had records inserted. I couldn't understand the behavior I was experiencing until I stumbled across this question on SO!

My solution (ugly but works) is to explicitly check the sys.identity_columns.last_value table (which tells you whether or not the table has had records inserted) and call the appropriate DBCC CHECKIDENT command in each case. It is as follows:

DECLARE @last_value INT = CONVERT(INT, (SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MyTable'));
IF @last_value IS NULL
    BEGIN
        -- Table newly created and no rows inserted yet; start the IDs off from 1
        DBCC CHECKIDENT ('MyTable', RESEED, 1);
    END
ELSE
    BEGIN
        -- Table has rows; ensure the IDs continue from the last ID used
        DECLARE @lastValUsed INT = (SELECT ISNULL(MAX(ID),0) FROM MyTable);
        DBCC CHECKIDENT ('MyTable', RESEED, @lastValUsed);
    END

How to find out if a Python object is a string?

This evening I ran into a situation in which I thought I was going to have to check against the str type, but it turned out I did not.

My approach to solving the problem will probably work in many situations, so I offer it below in case others reading this question are interested (Python 3 only).

# NOTE: fields is an object that COULD be any number of things, including:
# - a single string-like object
# - a string-like object that needs to be converted to a sequence of 
# string-like objects at some separator, sep
# - a sequence of string-like objects
def getfields(*fields, sep=' ', validator=lambda f: True):
    '''Take a field sequence definition and yield from a validated
     field sequence. Accepts a string, a string with separators, 
     or a sequence of strings'''
    if fields:
        try:
            # single unpack in the case of a single argument
            fieldseq, = fields
            try:
                # convert to string sequence if string
                fieldseq = fieldseq.split(sep)
            except AttributeError:
                # not a string; assume other iterable
                pass
        except ValueError:
            # not a single argument and not a string
            fieldseq = fields
        invalid_fields = [field for field in fieldseq if not validator(field)]
        if invalid_fields:
            raise ValueError('One or more field names is invalid:\n'
                             '{!r}'.format(invalid_fields))
    else:
        raise ValueError('No fields were provided')
    try:
        yield from fieldseq
    except TypeError as e:
        raise ValueError('Single field argument must be a string'
                         'or an interable') from e

Some tests:

from . import getfields

def test_getfields_novalidation():
    result = ['a', 'b']
    assert list(getfields('a b')) == result
    assert list(getfields('a,b', sep=',')) == result
    assert list(getfields('a', 'b')) == result
    assert list(getfields(['a', 'b'])) == result

Restart android machine

You can reboot the device by sending the following broadcast:

$ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

How to display raw html code in PRE or something like it but without escaping it

@GitaarLAB and @Jukka elaborate that <xmp> tag is obsolete, but still the best. When I use it like this

<xmp>
<div>Lorem ipsum</div>
<p>Hello</p>
</xmp>

then the first EOL is inserted in the code, and it looks awful.

It can be solved by removing that EOL

<xmp><div>Lorem ipsum</div>
<p>Hello</p>
</xmp>

but then it looks bad in the source. I used to solve it with wrapping <div>, but recently I figured out a nice CSS3 rule, I hope it also helps somebody:

xmp { margin: 5px 0; padding: 0 5px 5px 5px; background: #CCC; }
xmp:before { content: ""; display: block; height: 1em; margin: 0 -5px -2em -5px; }

This looks better.

Docker command can't connect to Docker daemon

I had the same problem. Been struggling for two days to solve it.

It only worked when I did:

  1. According to Docker's Tutorial, you need to add the Docker key if not already added using:

    $ sudo wget -qO- https://get.docker.com/gpg | sudo apt-key add -

  2. Then make sure you grant docker privileges to yourself using:

    $ sudo usermod -aG docker $USER

Hope this helps you too.

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

How to add Certificate Authority file in CentOS 7

Complete instruction is as follow:

  1. Extract Private Key from PFX

openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes

  1. Extract Certificate from PFX

openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem

  1. install certificate

yum install -y ca-certificates,

cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem ,

update-ca-trust ,

update-ca-trust force-enable

Hope to be useful

How to solve "Fatal error: Class 'MySQLi' not found"?

<?php  /* If the error is due to calling mysqli in a class */

    class dbconnect extends mysqli{

        private $host = 'localhost';
        private $user = 'root';
        private $pass = '';
        private $db = 'test';

        public function __construct() {
            parent::__construct($this->host, $this->user, $this->pass, $this->db);

            if (mysqli_connect_error()) {
                die('Connect Error (' . mysqli_connect_errno() . ') ' .
                    mysqli_connect_error());
            }
        }
    }
?>

Change directory command in Docker?

To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.

RUN git clone XYZ 
WORKDIR "/XYZ"
RUN make

How to map a composite key with JPA and Hibernate?

Looks like you are doing this from scratch. Try using available reverse engineering tools like Netbeans Entities from Database to at least get the basics automated (like embedded ids). This can become a huge headache if you have many tables. I suggest avoid reinventing the wheel and use as many tools available as possible to reduce coding to the minimum and most important part, what you intent to do.

Failed to resolve: com.android.support:appcompat-v7:28.0

28.0.0 is the final version of support libraries. Android has migrated to AndroidX. To use the latest android libraries, Migrating to AndroidX


Edit: Versions 28.0.0-rc02 and 28.0.0 are now available.

I don't see any 28.0 version on Google Maven. Only 28.0.0-alpha1 and 28.0.0-alpha3. Just change it to either of those or how it was previously, i.e., with .+ which just means any version under 28 major release.

For an alpha appcompat release 28.+ makes more sense.

Calendar date to yyyy-MM-dd format in java

In order to parse a java.util.Date object you have to convert it to String first using your own format.

inActiveDate = format1.parse(  format1.format(date)  );

But I believe you are being redundant here.

Simple Java Client/Server Program

this is client code

first run the server program then on another cmd run client program

import java.io.*;
import java.net.*;

public class frmclient 
{
 public static void main(String args[])throws Exception
 {

   try
        {
          DataInputStream d=new DataInputStream(System.in);
          System.out.print("\n1.fact\n2.Sum of digit\nEnter ur choice:");

           int ch=Integer.parseInt(d.readLine());
           System.out.print("\nEnter number:");
           int num=Integer.parseInt(d.readLine());

           Socket s=new Socket("localhost",1024);

           PrintStream ps=new PrintStream(s.getOutputStream());
           ps.println(ch+"");
           ps.println(num+"");

          DataInputStream dis=new DataInputStream(s.getInputStream());
           String response=dis.readLine();
                 System.out.print("Answer:"+response);


                s.close();
        }
        catch(Exception ex)
        {

        }
 }


}

this is sever side code

import java.io.*;
import java.net.*;
public class frmserver {

  public static void main(String args[])throws Exception
  {

try
    {

    ServerSocket ss=new ServerSocket(1024);
       System.out.print("\nWaiting for client.....");
       Socket s=ss.accept();
       System.out.print("\nConnected");

       DataInputStream d=new DataInputStream(s.getInputStream());

        int ch=Integer.parseInt(d.readLine());
       int num=Integer.parseInt(d.readLine());
         int result=0;

        PrintStream ps=new PrintStream(s.getOutputStream());
        switch(ch)
        {
          case 1:result=fact(num);
                 ps.println(result);
                  break;
          case 2:result=sum(num);
                 ps.println(result);
                  break;
        }

          ss.close();
          s.close();
    }
catch(Exception ex)
{

}
  }

  public static int fact(int n)
  {
  int ans=1;
    for(int i=n;i>0;i--)
    {
      ans=ans*i;
    }
    return ans;
  }
  public static int sum(int n)
  {
   String str=n+"";
   int ans=0;
    for(int i=0;i<str.length();i++)
    {
      int tmp=Integer.parseInt(str.charAt(i)+"");
      ans=ans+tmp;
    }
    return ans;
  }
}

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

Use application/javascript as content type instead of text/javascript

text/javascript is mentioned obsolete. See reference docs.

http://www.iana.org/assignments/media-types/application

Also see this question on SO.

UPDATE:

I have tried executing the code you have given and the below didn't work.

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

This is what worked for me.

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

As robertklep has suggested, please refer to the node http docs, there is no response.send() there.

Convert Little Endian to Big Endian

OP's code is incorrect for the following reasons:

  • The swaps are being performed on a nibble (4-bit) boundary, instead of a byte (8-bit) boundary.
  • The shift-left << operations of the final four swaps are incorrect, they should be shift-right >> operations and their shift values would also need to be corrected.
  • The use of intermediary storage is unnecessary, and the code can therefore be rewritten to be more concise/recognizable. In doing so, some compilers will be able to better-optimize the code by recognizing the oft-used pattern.

Consider the following code, which efficiently converts an unsigned value:

// Swap endian (big to little) or (little to big)
uint32_t num = 0x12345678;
uint32_t res =
    ((num & 0x000000FF) << 24) |
    ((num & 0x0000FF00) << 8) |
    ((num & 0x00FF0000) >> 8) |
    ((num & 0xFF000000) >> 24);

printf("%0x\n", res);

The result is represented here in both binary and hex, notice how the bytes have swapped:

?0111 1000 0101 0110 0011 0100 0001 0010?

78563412

Optimizing

In terms of performance, leave it to the compiler to optimize your code when possible. You should avoid unnecessary data structures like arrays for simple algorithms like this, doing so will usually cause different instruction behavior such as accessing RAM instead of using CPU registers.

Open link in new tab or window

It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.

Using _blank will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).

How to uninstall downloaded Xcode simulator?

You can remove them from /Library/Developer/CoreSimulator/Profiles/Runtimes (Not ~/Library!):

screenshot

Why am I getting tree conflicts in Subversion?

I had a similar problem. The only thing that actually worked for me was to delete the conflicted subdirectories with:

svn delete --force ./SUB_DIR_NAME

Then copy them again from another root directory in the working copy that has them with:

svn copy ROOT_DIR_NAME/SUB_DIR_NAME

Then do

svn cleanup

and

svn add *

You might get warnings with the last one, but just ignore them and finally

svn ci .

I lose my data when the container exits

None of the answers address the point of this design choice. I think docker works this way to prevent these 2 errors:

  • Repeated restart
  • Partial error

How can I retrieve a table from stored procedure to a datatable?

string connString = "<your connection string>";
string sql = "name of your sp";

using(SqlConnection conn = new SqlConnection(connString)) 
{
    try 
    {
        using(SqlDataAdapter da = new SqlDataAdapter()) 
        {
            da.SelectCommand = new SqlCommand(sql, conn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            DataSet ds = new DataSet();   
            da.Fill(ds, "result_name");

            DataTable dt = ds.Tables["result_name"];

            foreach (DataRow row in dt.Rows) {
                //manipulate your data
            }
        }    
    } 
    catch(SQLException ex) 
    {
        Console.WriteLine("SQL Error: " + ex.Message);
    }
    catch(Exception e) 
    {
        Console.WriteLine("Error: " + e.Message);
    }
}

Modified from Java Schools Example

Build an iOS app without owning a mac?

Some cloud solutions exist, such as macincloud (not free)

bundle install fails with SSL certificate verification error

I was just recently faced with this issue and followed the steps outlined here. There might be a chance that you are not pointing to the right OpenSSL certificate. After running:

rvm osx-ssl-certs status all
rvm osx-ssl-certs update all

and

export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt

the bundle complete ran!

SQL query for extracting year from a date

How about this one?

SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

How do I create a comma-separated list using a SQL query?

I believe what you want is:

SELECT ItemName, GROUP_CONCAT(DepartmentId) FROM table_name GROUP BY ItemName

If you're using MySQL

Reference

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

How to resolve "Waiting for Debugger" message?

Closing the emulator and closing eclipse. Reopening Eclipse and starting the simulator worked for me.

The key thing to look for is in the Devices pane of Eclipse. If you start the emulator or device and it shows up in the device name list but says [null] and no running processes show beneath it, then it won't work correctly with loading your app into it.

If the name of the device comes up and is Online then things seem to work smoothly.

Don't know why it doesn't work out all the time though.

Convert row to column header for Pandas DataFrame,

You can specify the row index in the read_csv or read_html constructors via the header parameter which represents Row number(s) to use as the column names, and the start of the data. This has the advantage of automatically dropping all the preceding rows which supposedly are junk.

import pandas as pd
from io import StringIO

In[1]
    csv = '''junk1, junk2, junk3, junk4, junk5
    junk1, junk2, junk3, junk4, junk5
    pears, apples, lemons, plums, other
    40, 50, 61, 72, 85
    '''

    df = pd.read_csv(StringIO(csv), header=2)
    print(df)

Out[1]
       pears   apples   lemons   plums   other
    0     40       50       61      72      85

Confirm deletion in modal / dialog using Twitter Bootstrap?

I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:

    bootbox.confirm("Are you sure to want to delete , function(result) {

    //here result will be true
    // delete process code goes here

    });

Offical bootboxjs site

How to disable back swipe gesture in UINavigationController on iOS 7

This is the way on Swift 3

works for me

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

What is a stack trace, and how can I use it to debug my application errors?

To add on to what Rob has mentioned. Setting break points in your application allows for the step-by-step processing of the stack. This enables the developer to use the debugger to see at what exact point the method is doing something that was unanticipated.

Since Rob has used the NullPointerException (NPE) to illustrate something common, we can help to remove this issue in the following manner:

if we have a method that takes parameters such as: void (String firstName)

In our code we would want to evaluate that firstName contains a value, we would do this like so: if(firstName == null || firstName.equals("")) return;

The above prevents us from using firstName as an unsafe parameter. Therefore by doing null checks before processing we can help to ensure that our code will run properly. To expand on an example that utilizes an object with methods we can look here:

if(dog == null || dog.firstName == null) return;

The above is the proper order to check for nulls, we start with the base object, dog in this case, and then begin walking down the tree of possibilities to make sure everything is valid before processing. If the order were reversed a NPE could potentially be thrown and our program would crash.

Displaying a Table in Django from Database

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

How can I develop for iPhone using a Windows development machine?

You can use Sentenza for make applications for iPhone, on Windows. Tested with success. It's not a solution but a good alternative !

Better way to set distance between flexbox items

It won't work in every case but if you have flexible child widths (%) and know the number of items per row you can very cleanly specify the margins of the necessary elements by using nth-child selector/s.

It depends largely on what you mean by "better". This way doesn't require additional wrapper markup for child elements or negative elements - but those things both have their place.

_x000D_
_x000D_
section {_x000D_
  display: block_x000D_
  width: 100vw;_x000D_
}_x000D_
.container {_x000D_
  align-content: flex-start;_x000D_
  align-items: stretch;_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  justify-content: flex-start;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.child-item {_x000D_
  background-color: #c00;_x000D_
  margin-bottom: 2%;_x000D_
  min-height: 5em;_x000D_
  width: 32%;_x000D_
}_x000D_
_x000D_
.child-item:nth-child(3n-1) {_x000D_
  margin-left: 2%;_x000D_
  margin-right: 2%;_x000D_
}
_x000D_
<html>_x000D_
  <body>_x000D_
      <div class="container">_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
        <div class="child-item"></div>_x000D_
      </div>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

C programming in Visual Studio

Download visual studio c++ express version 2006,2010 etc. then goto create new project and create c++ project select cmd project check empty rename cc with c extension file name

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

Dynamically Dimensioning A VBA Array?

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. They have distinctly different meanings.

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

Downloading Java JDK on Linux via wget is shown license page instead

Try

wget --no-cookies --header "Cookie: s_nr=1359635827494; s_cc=true; gpw_e24=http%3A%2F%2Fwww.oracle.com%2Ftechnetwork%2Fjava%2Fjavase%2Fdownloads%2Fjdk6downloads-1902814.html; s_sq=%5B%5BB%5D%5D; gpv_p24=no%20value" http://download.oracle.com/otn-pub/java/jdk/6u45-b06/jdk-6u45-linux-x64-rpm.bin --no-check-certificate -O ./jdk-6u45-linux-x64-rpm.bin

if you are like me trying to get Oracle JDK 6.

source: Oracle JVM download using curl/wget

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

You never named your submit button, so as far as the form is concerned it's just an action.

Either:

  1. Name the submit button (<input type="submit" name="submit" ... />)
  2. Test if (!empty($_POST)) instead to detect when data has been posted.

Remember that keys in the $_POST superglobal only appear for named input elements. So, unless the element has the name attribute, it won't come through to $_POST (or $_GET/$_REQUEST)

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

When you sync this dependency to the android studio:

 implementation 'com.android.support:cardview-v7:26.0.1-alpha1'

Then, Sync the Gradle with Project Files. It will say, (Suppose if you are working on new ones like androidx) obviously, it will show error on the dependency.

For that you can go to the File menu and click on the invalidate/restart the code. It will resolve itself and the application will restart without any error.

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

missing FROM-clause entry for table

SELECT 
   AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
   BillLimit, Mode, PNotes, gtab82.memno 
FROM
   VCustomer AS v1
INNER JOIN   
   gtab82 ON gtab82.memacid = v1.AcId 
WHERE (AcGrCode = '204' OR CreDebt = 'True') 
AND Masked = 'false'
ORDER BY AcName

You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

How to check if a variable is set in Bash?

After skimming all the answers, this also works:

if [[ -z $SOME_VAR ]]; then read -p "Enter a value for SOME_VAR: " SOME_VAR; fi
echo "SOME_VAR=$SOME_VAR"

if you don't put SOME_VAR instead of what I have $SOME_VAR, it will set it to an empty value; $ is necessary for this to work.

Print text instead of value from C enum

Here's a cleaner way to do it with macros:

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

#define DOW(X, S)                                                         \
    X(Sunday) S X(Monday) S X(Tuesday) S X(Wednesday) S X(Thursday) S X(Friday) S X(Saturday)

#define COMMA ,

/* declare the enum */
#define DOW_ENUM(DOW) DOW
enum dow {
    DOW(DOW_ENUM, COMMA)
};

/* create an array of strings with the enum names... */
#define DOW_ARR(DOW ) [DOW] = #DOW
const char * const dow_str[] = {
    DOW(DOW_ARR, COMMA)
};

/* ...or create a switchy function. */
static const char * dowstr(int i)
{
#define DOW_CASE(D) case D: return #D

    switch(i) {
        DOW(DOW_CASE, ;);
    default: return NULL;
    }
}


int main(void)
{
    for(int i = 0; i < 7; i++)
        printf("[%d] = «%s»\n", i, dow_str[i]);
    printf("\n");
    for(int i = 0; i < 7; i++)
        printf("[%d] = «%s»\n", i, dowstr(i));
    return 0;
}

I'm not sure that this is totally portable b/w preprocessors, but it works with gcc.

This is c99 btw, so use c99 strict if you plug it into (the online compiler) ideone.

How to undo "git commit --amend" done instead of "git commit"

What you need to do is to create a new commit with the same details as the current HEAD commit, but with the parent as the previous version of HEAD. git reset --soft will move the branch pointer so that the next commit happens on top of a different commit from where the current branch head is now.

# Move the current head so that it's pointing at the old commit
# Leave the index intact for redoing the commit.
# HEAD@{1} gives you "the commit that HEAD pointed at before 
# it was moved to where it currently points at". Note that this is
# different from HEAD~1, which gives you "the commit that is the
# parent node of the commit that HEAD is currently pointing to."
git reset --soft HEAD@{1}

# commit the current tree using the commit details of the previous
# HEAD commit. (Note that HEAD@{1} is pointing somewhere different from the
# previous command. It's now pointing at the erroneously amended commit.)
git commit -C HEAD@{1}

Ascending and Descending Number Order in java

You can sort the array first, and then loop through it twice, once in both directions:

Arrays.sort(arr); 
System.out.print("Numbers in Ascending Order:" ); 
for(int i = 0; i < arr.length; i++){ 
  System.out.print( " " + arr[i]); 
} 
System.out.print("Numbers in Descending Order: " ); 
for(int i = arr.length - 1; i >= 0; i--){ 
  System.out.print( " " + arr[i]); 
} 

What is the difference between Linear search and Binary search?

Linear search also referred to as sequential search looks at each element in sequence from the start to see if the desired element is present in the data structure. When the amount of data is small, this search is fast.Its easy but work needed is in proportion to the amount of data to be searched.Doubling the number of elements will double the time to search if the desired element is not present.

Binary search is efficient for larger array. In this we check the middle element.If the value is bigger that what we are looking for, then look in the first half;otherwise,look in the second half. Repeat this until the desired item is found. The table must be sorted for binary search. It eliminates half the data at each iteration.Its logarithmic.

If we have 1000 elements to search, binary search takes about 10 steps, linear search 1000 steps.

Getting a list of values from a list of dicts

Here's another way to do it using map() and lambda functions:

>>> map(lambda d: d['value'], l)

where l is the list. I see this way "sexiest", but I would do it using the list comprehension.

Update: In case that 'value' might be missing as a key use:

>>> map(lambda d: d.get('value', 'default value'), l)

Update: I'm also not a big fan of lambdas, I prefer to name things... this is how I would do it with that in mind:

>>> import operator
>>> get_value = operator.itemgetter('value')
>>> map(get_value, l)

I would even go further and create a sole function that explicitly says what I want to achieve:

>>> import operator, functools
>>> get_value = operator.itemgetter('value')
>>> get_values = functools.partial(map, get_value)
>>> get_values(l)
... [<list of values>]

With Python 3, since map returns an iterator, use list to return a list, e.g. list(map(operator.itemgetter('value'), l)).

Android Layout Right Align

You can do all that by using just one RelativeLayout (which, btw, don't need android:orientation parameter). So, instead of having a LinearLayout, containing a bunch of stuff, you can do something like:

<RelativeLayout>
    <ImageButton
        android:layout_width="wrap_content"
        android:id="@+id/the_first_one"
        android:layout_alignParentLeft="true"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_toRightOf="@+id/the_first_one"/>
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

As you noticed, there are some XML parameters missing. I was just showing the basic parameters you had to put. You can complete the rest.

Access to the path is denied

My problem was that I had to ask for Read access only:

FileStream fs = new FileStream(name, FileMode.Open, FileAccess.Read);

What is Ruby's double-colon `::`?

Ruby on rails uses :: for namespace resolution.

class User < ActiveRecord::Base

  VIDEOS_COUNT = 10
  Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}

end

To use it :

User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"

Also, other usage is : When using nested routes

OmniauthCallbacksController is defined under users.

And routed as:

devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

end

Installing a dependency with Bower from URL and specify version

If you use bower.json file to specify your dependencies:

{
     "dependencies": {
         ...
         "photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",

#bower 1.4 (tested with that version) can read repositorios with uri format

         "photo-swipe": "git://github.com/dimsemenov/PhotoSwipe.git#v3.0.x",

     }
}

Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)

Update, as the question description also mention using only a URL and no mention of a github repository.

Another example is to execute this command using the desired url, like:

bower install gmap3MarkerWithLabel=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.0/src/markerwithlabel.js -S

that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute bower update gmap3MarkerWithLabel if needed.

Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a

bower ENOTFOUND Package gmapV3MarkerWithLabel not found

Best way to retrieve variable values from a text file?

The other solutions posted here didn't work for me, because:

  • i just needed parameters from a file for a normal script
  • import * didn't work for me, as i need a way to override them by choosing another file
  • Just a file with a dict wasn't fine, as I needed comments in it.

So I ended up using Configparser and globals().update()

Test file:

#File parametertest.cfg:
[Settings]
#Comments are no Problem
test= True
bla= False    #Here neither

#that neither

And that's my demo script:

import ConfigParser

cfg = ConfigParser.RawConfigParser()
cfg.read('parametertest.cfg')       # Read file

#print cfg.getboolean('Settings','bla') # Manual Way to acess them

par=dict(cfg.items("Settings"))
for p in par:
    par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments

globals().update(par)  #Make them availible globally

print bla

It's just for a file with one section now, but that will be easy to adopt.

Hope it will be helpful for someone :)

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

How to wait for 2 seconds?

As mentioned in other answers, all of the following will work for the standard string-based syntax.

WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds

There is also an alternative method of passing it a DATETIME value. You might think I'm confusing this with WAITFOR TIME, but it also works for WAITFOR DELAY.

Considerations for passing DATETIME:

  • It must be passed as a variable, so it isn't a nice one-liner anymore.
  • The delay is measured as the time since the Epoch ('1900-01-01').
  • For situations that require a variable amount of delay, it is much easier to manipulate a DATETIME than to properly format a VARCHAR.

How to wait for 2 seconds:

--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1

--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2

A note on waiting for TIME vs DELAY:

Have you ever noticed that if you accidentally pass WAITFOR TIME a date that already passed, even by just a second, it will never return? Check it out:

--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER

Unfortunately, WAITFOR DELAY will do the same thing if you pass it a negative DATETIME value (yes, that's a thing).

--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER

However, I would still recommend using WAITFOR DELAY over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR statement.

How to send a pdf file directly to the printer using JavaScript?

There are two steps you need to take.

First, you need to put the PDF in an iframe.

  <iframe id="pdf" name="pdf" src="document.pdf"></iframe>

To print the iframe you can look at the answers here:

Javascript Print iframe contents only

If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>:

  <iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>

the loader can look like this:

function isLoaded()
{
  var pdfFrame = window.frames["pdf"];
  pdfFrame.focus();
  pdfFrame.print();
}

This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).

I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.

Read input numbers separated by spaces

I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.

#include <string>
#include <vector>
...
  string rawInput;
  vector<String> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }

So say the input looks like this:

Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7

You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.

Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.

while(!numbers.empty())
{
  string temp = numbers.pop_back();//removes the last element from the string
  num = atoi( temp.c_str() ); //re-used your 'num' variable from your code

  ...//do stuff
}

Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:

#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  num = atoi( rawInput.c_str() );
  ...//do your stuff
}

There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)

Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/

Edit: I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].

#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  bool isNum = true;
  for(int i = 0; i < rawInput.length() && isNum; ++i)
  {
    isNum = isdigit( rawInput[i]);
  }

  if(isNum)
  {
    num = atoi( rawInput.c_str() );
    ...//do your stuff
  }
  else
    cout << rawInput << " is not a number!" << endl;
}

The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

How to set seekbar min and max value

You can set max value for your seekbar by using this code:

    sb1.setMax(100);

This will set the max value for your seekbar.

But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.

For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.

You can get more info via this link.

Splitting a string into chunks of a certain size

Personally I prefer my solution :-)

It handles:

  • String lengths that are a multiple of the chunk size.
  • String lengths that are NOT a multiple of the chunk size.
  • String lengths that are smaller than the chunk size.
  • NULL and empty strings (throws an exception).
  • Chunk sizes smaller than 1 (throws an exception).

It is implemented as a extension method, and it calculates the number of chunks is going to generate beforehand. It checks the last chunk because in case the text length is not a multiple it needs to be shorter. Clean, short, easy to understand... and works!

    public static string[] Split(this string value, int chunkSize)
    {
        if (string.IsNullOrEmpty(value)) throw new ArgumentException("The string cannot be null.");
        if (chunkSize < 1) throw new ArgumentException("The chunk size should be equal or greater than one.");

        int remainder;
        int divResult = Math.DivRem(value.Length, chunkSize, out remainder);

        int numberOfChunks = remainder > 0 ? divResult + 1 : divResult;
        var result = new string[numberOfChunks];

        int i = 0;
        while (i < numberOfChunks - 1)
        {
            result[i] = value.Substring(i * chunkSize, chunkSize);
            i++;
        }

        int lastChunkSize = remainder > 0 ? remainder : chunkSize;
        result[i] = value.Substring(i * chunkSize, lastChunkSize);

        return result;
    }

How do I select child elements of any depth using XPath?

You're almost there. Simply use:

//form[@id='myform']//input[@type='submit']

The // shortcut can also be used inside an expression.

Parallel foreach with asynchronous lambda

With SemaphoreSlim you can achieve parallelism control.

var bag = new ConcurrentBag<object>();
var maxParallel = 20;
var throttler = new SemaphoreSlim(initialCount: maxParallel);
var tasks = myCollection.Select(async item =>
{
  try
  {
     await throttler.WaitAsync();
     var response = await GetData(item);
     bag.Add(response);
  }
  finally
  {
     throttler.Release();
  }
});
await Task.WhenAll(tasks);
var count = bag.Count;

How can I find all of the distinct file extensions in a folder hierarchy?

I don't think this one was mentioned yet:

find . -type f -exec sh -c 'echo "${0##*.}"' {} \; | sort | uniq -c

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Declaring variables inside loops, good practice or bad practice?

It's a very good practice, as all above answer provide very good theoretical aspect of the question let me give a glimpse of code, i was trying to solve DFS over GEEKSFORGEEKS, i encounter the optimization problem...... If you try to solve the code declaring the integer outside the loop will give you Optimization Error..

stack<int> st;
st.push(s);
cout<<s<<" ";
vis[s]=1;
int flag=0;
int top=0;
while(!st.empty()){
    top = st.top();
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            st.push(g[top][i]);
            cout<<g[top][i]<<" ";
            vis[g[top][i]]=1;
            flag=1;
            break;
        }
    }
    if(!flag){
        st.pop();
    }
}

Now put integers inside the loop this will give you correct answer...

stack<int> st;
st.push(s);
cout<<s<<" ";
vis[s]=1;
// int flag=0;
// int top=0;
while(!st.empty()){
    int top = st.top();
    int flag = 0;
    for(int i=0;i<g[top].size();i++){
        if(vis[g[top][i]] != 1){
            st.push(g[top][i]);
            cout<<g[top][i]<<" ";
            vis[g[top][i]]=1;
            flag=1;
            break;
        }
    }
    if(!flag){
        st.pop();
    }
}

this completely reflect what sir @justin was saying in 2nd comment.... try this here https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1. just give it a shot.... you will get it.Hope this help.

For homebrew mysql installs, where's my.cnf?

I believe the answer is no. Installing one in ~/.my.cnf or /usr/local/etc seems to be the preferred solution.

jquery remove "selected" attribute of option?

This works:

$("#myselect").find('option').removeAttr("selected");

or

$("#myselect").find('option:selected').removeAttr("selected");

jsFiddle

Read all contacts' phone numbers in android

Here's how to use ContentsContract API to fetch your contacts in your Phone Book. You'll need to add these permissions in your AndroidManifest.xml

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

Then, you can run this method to loop through all your contacts.

Here's an example to query fields like Name and Phone Number, you can configure yourself to use CommonDataKinds, it query other fields in your Contact.

https://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds

private fun readContactsOnDevice() {
    val context = requireContext()
    if (ContextCompat.checkSelfPermission(
            context, Manifest.permission.WRITE_CONTACTS
        ) != PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(
            context, Manifest.permission.READ_CONTACTS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        requestPermissions(
            arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), 1
        )
        return
    }

    val contentResolver = context.contentResolver
    val contacts = contentResolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null, null, null, null
    )

    while (contacts?.moveToNext() == true) {
        val name = contacts.getString(
            contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
        )
        val phoneNumber = contacts.getString(
            contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
        )
        Timber.i("Name: $name, Phone Number: $phoneNumber")
    }
}

Get counts of all tables in a schema

You have to use execute immediate (dynamic sql).

DECLARE 
v_owner varchar2(40); 
v_table_name varchar2(40); 
cursor get_tables is 
select distinct table_name,user 
from user_tables 
where lower(user) = 'schema_name'; 
begin 
open get_tables; 
loop
    fetch get_tables into v_table_name,v_owner; 
    EXIT WHEN get_tables%NOTFOUND;
    execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED) 
    SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'')     FROM ' || v_table_name; 
end loop;
CLOSE get_tables; 
END; 

Can JavaScript connect with MySQL?

If you want to connect to a MySQL database using JavaScript, you can use Node.js and a library called mysql. You can create queries, and get results as an array of registers. If you want to try it, you can use my project generator to create a backend and choose MySQL as the database to connect. Then, just expose your new REST API or GraphQL endpoint to your front and start working with your MySQL database.


OLD ANSWER LEFT BY NOSTALGIA

THEN

As I understand the question and correct me if I am wrong, it refers to the classic server model with JavaScript only on the client-side. In this classic model, with LAMP servers (Linux, Apache, MySQL, PHP) the language in contact with the database was PHP, so to request data to the database you need to write PHP scripts and echo the returning data to the client. Basically, the distribution of the languages according to physical machines was:

  1. Server Side: PHP and MySQL.
  2. Client Side: HTML/CSS and JavaScript.

This answered to an MVC model (Model, View, Controller) where we had the following functionality:

  1. MODEL: The model is what deals with the data, in this case, the PHP scripts that manage variables or that access data stored, in this case in our MySQL database and send it as JSON data to the client.
  2. VIEW: The view is what we see and it should be completely independent of the model. It just needs to show the data contained in the model, but it shouldn't have relevant data on it. In this case, the view uses HTML and CSS. HTML to create the basic structure of the view, and CSS to give the shape to this basic structure.
  3. CONTROLLER: The controller is the interface between our model and our view. In this case, the language used is JavaScript and it takes the data the model send us as a JSON package and put it inside the containers that offer the HTML structure. The way the controller interacts with the model is by using AJAX. We use GET and POST methods to call PHP scripts on the server-side and to catch the returned data from the server.

For the controller, we have really interesting tools like jQuery, as "low-level" library to control the HTML structure (DOM), and then new, more high-level ones as Knockout.js that allow us to create observers that connect different DOM elements updating them when events occur. There is also Angular.js by Google that works in a similar way, but seems to be a complete environment. To help you to choose among them, here you have two excellent analyses of the two tools: Knockout vs. Angular.js and Knockout.js vs. Angular.js. I am still reading. Hope they help you.

NOW

In modern servers based in Node.js, we use JavaScript for everything. Node.js is a JavaScript environment with many libraries that work with Google V8, Chrome JavaScript engine. The way we work with these new servers is:

  1. Node.js and Express: The mainframe where the server is built. We can create a server with a few lines of code or even use libraries like Express to make even easier to create the server. With Node.js and Express, we will manage the petitions to the server from the clients and will answer them with the appropriate pages.
  2. Jade: To create the pages we use a templating language, in this case, Jade, that allow us to write web pages as we were writing HTML but with differences (it take a little time but is easy to learn). Then, in the code of the server to answer the client's petitions, we just need to render the Jade code into a "real" HTML code.
  3. Stylus: Similar to Jade but for CSS. In this case, we use a middleware function to convert the stylus file into a real CSS file for our page.

Then we have a lot of packages we can install using the NPM (Node.js package manager) and use them directly in our Node.js server just requiring it (for those of you that want to learn Node.js, try this beginner tutorial for an overview). And among these packages, you have some of them to access databases. Using this you can use JavaScript on the server-side to access My SQL databases.

But the best you can do if you are going to work with Node.js is to use the new NoSQL databases like MongoDB, based on JSON files. Instead of storing tables like MySQL, it stores the data in JSON structures, so you can put different data inside each structure like long numeric vectors instead of creating huge tables for the size of the biggest one.

I hope this brief explanation becomes useful to you, and if you want to learn more about this, here you have some resources you can use:

  • Egghead: This site is full of great short tutorials about JavaScript and its environment. It worths a try. And the make discounts from time to time.
  • Code School: With a free and very interesting course about Chrome Developer tools to help you to test the client-side.
  • Codecademy: With free courses about HTML, CSS, JavaScript, jQuery, and PHP that you can follow with online examples.
  • 10gen Education: With everything you need to know about MongoDB in tutorials for different languages.
  • W3Schools: This one has tutorials about all this and you can use it as a reference place because it has a lot of shortcode examples really useful.
  • Udacity: A place with free video courses about different subjects with a few interesting ones about web development and my preferred, an amazing WebGL course for 3D graphics with JavaScript.

I hope it helps you to start.

Have fun!

make an ID in a mysql table auto_increment (after the fact)

For example, here's a table that has a primary key but is not AUTO_INCREMENT:

mysql> CREATE TABLE foo (
  id INT NOT NULL,
  PRIMARY KEY (id)
);
mysql> INSERT INTO foo VALUES (1), (2), (5);

You can MODIFY the column to redefine it with the AUTO_INCREMENT option:

mysql> ALTER TABLE foo MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT;

Verify this has taken effect:

mysql> SHOW CREATE TABLE foo;

Outputs:

CREATE TABLE foo (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1

Note that you have modified the column definition in place, without requiring creating a second column and dropping the original column. The PRIMARY KEY constraint is unaffected, and you don't need to mention in in the ALTER TABLE statement.

Next you can test that an insert generates a new value:

mysql> INSERT INTO foo () VALUES (); -- yes this is legal syntax
mysql> SELECT * FROM foo;

Outputs:

+----+
| id |
+----+
|  1 | 
|  2 | 
|  5 | 
|  6 | 
+----+
4 rows in set (0.00 sec)

I tested this on MySQL 5.0.51 on Mac OS X.

I also tested with ENGINE=InnoDB and a dependent table. Modifying the id column definition does not interrupt referential integrity.


To respond to the error 150 you mentioned in your comment, it's probably a conflict with the foreign key constraints. My apologies, after I tested it I thought it would work. Here are a couple of links that may help to diagnose the problem:

How to generate serial version UID in Intellij

with in the code editor, Open the class you want to create the UID for , Right click -> Generate -> SerialVersionUID. You may need to have the GenerateSerialVersionUID plugin installed for this to work.

How to use ADB in Android Studio to view an SQLite DB

The issue you are having is common and not explained well in the documentation. Normal devices do not include the sqlite3 database binary which is why you are getting an error. the Android Emeulator, OSX, Linux (if installed) and Windows (after installed) have the binary so you can open a database locally on your machine.

The workaround is to copy the Database from your device to your local machine. This can be accomplished with ADB but requires a number of steps.

Before you start you will need some information:

  • path of the SDK (if not included in your OS environment)
  • your <package name>, for example, com.example.application
  • a <local path> to place your database, eg. ~/Desktop or %userprofile%\Desktop

Next you will need to understand what terminal each command gets written to the first character in the examples below does not get typed but lets you know what shell we are in:

  • > = you OS command prompt
  • $ = ADB shell command Prompt
  • ! = ADB shell as admin command prompt
  • %

Next enter the following commands from Terminal or Command (don't enter first character or text in ())

> adb shell
$ su
! cp /data/data/<package name>/Databases/<database name> /sdcard
! exit
$ exit
> adb pull /sdcard/<database name> <local path>
> sqlite3 <local db path>
% .dump
% .exit  (to exit sqldb)

This is a really round about way of copying the database to your local machine and locally reading the database. There are SO and other resources explaining how to install the sqlite3 binary onto your device from an emulator but for one time access this process works.

If you need to access the database interactively I would suggest running your app in an emulator (that already had sqlite3) or installing sqlite onto your devices /xbin path.

SSH to Vagrant box in Windows?

I use vagrant ssh command with git ssh on windows 7, 8.1 and Windows 10.

To install only download msysgit from msysgit project page.

And to run ssh.exe only include the bin folter to windows environment variables or install git from Git Download page and copy the msysgit bin folter to C:\Program Files\Git\bin.

About .bash_profile, .bashrc, and where should alias be written in?

.bash_profile is loaded for a "login shell". I am not sure what that would be on OS X, but on Linux that is either X11 or a virtual terminal.

.bashrc is loaded every time you run Bash. That is where you should put stuff you want loaded whenever you open a new Terminal.app window.

I personally put everything in .bashrc so that I don't have to restart the application for changes to take effect.

Convert date from String to Date format in Dataframes

dateID is int column contains date in Int format

spark.sql("SELECT from_unixtime(unix_timestamp(cast(dateid as varchar(10)), 'yyyymmdd'), 'yyyy-mm-dd') from XYZ").show(50, false)

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

Any tools to generate an XSD schema from an XML instance document?

the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.

edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that

How to deploy correctly when using Composer's develop / production switch?

I think is better automate the process:

Add the composer.lock file in your git repository, make sure you use composer.phar install --no-dev when you release, but in you dev machine you could use any composer command without concerns, this will no go to production, the production will base its dependencies in the lock file.

On the server you checkout this specific version or label, and run all the tests before replace the app, if the tests pass you continue the deployment.

If the test depend on dev dependencies, as composer do not have a test scope dependency, a not much elegant solution could be run the test with the dev dependencies (composer.phar install), remove the vendor library, run composer.phar install --no-dev again, this will use cached dependencies so is faster. But that is a hack if you know the concept of scopes in other build tools

Automate this and forget the rest, go drink a beer :-)

PS.: As in the @Sven comment bellow, is not a good idea not checkout the composer.lock file, because this will make composer install work as composer update.

You could do that automation with http://deployer.org/ it is a simple tool.

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

If all the other answers do not work for you check the config.inc.php for the following:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

…and add the port of MySQL set in your XAMPP as shown below:

$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';

Stop MySQL from XAMPP and restart MySQL.

Open a fresh page for http://localhost:8012/phpmyadmin/ and check.

Merge two rows in SQL

My case is I have a table like this

---------------------------------------------
|company_name|company_ID|CA        |   WA   |
---------------------------------------------
|Costco      |   1      |NULL      | 2      |
---------------------------------------------
|Costco      |   1      |3         |Null    |
---------------------------------------------

And I want it to be like below:

---------------------------------------------
|company_name|company_ID|CA        |   WA   |
---------------------------------------------
|Costco      |   1      |3         | 2      |
---------------------------------------------

Most code is almost the same:

SELECT
    FK,
    MAX(CA) AS CA,
    MAX(WA) AS WA
FROM
    table1
GROUP BY company_name,company_ID

The only difference is the group by, if you put two column names into it, you can group them in pairs.

What does "exited with code 9009" mean during this build?

I think in my case there were russian symbols in path (all projects were in user folder). When I put solution in another folder (directly on disk), everything became ok.

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

How can I check that two objects have the same set of property names?

2 Here a short ES6 variadic version:

function objectsHaveSameKeys(...objects) {
   const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
   const union = new Set(allKeys);
   return objects.every(object => union.size === Object.keys(object).length);
}

A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):

var x = {};
var y = {};

for (var i = 0; i < 5000000; ++i) {
    x[i] = i;
    y[i] = i;
}

Results:

objectsHaveSameKeys(x, y) // took  4996 milliseconds
compareKeys(x, y)               // took 14880 milliseconds
hasSameProps(x,y)               // after 10 minutes I stopped execution

How to change the URI (URL) for a remote Git repository?

Navigate to the project root of the local repository and check for existing remotes:

git remote -v

If your repository is using SSH you will see something like:

> origin  [email protected]:USERNAME/REPOSITORY.git (fetch)
> origin  [email protected]:USERNAME/REPOSITORY.git (push)

And if your repository is using HTTPS you will see something like:

> origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin  https://github.com/USERNAME/REPOSITORY.git (push)

Changing the URL is done with git remote set-url. Depending on the output of git remote -v, you can change the URL in the following manner:

In case of SSH, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin [email protected]:USERNAME/NEW_REPOSITORY.git

And in case of HTTPS, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin https://github.com/USERNAME/NEW_REPOSITORY.git

NOTE: If you've changed your GitHub username, you can follow the same process as above to update the change in the username associated with your repository. You would only have to update the USERNAME in the git remote set-url command.

Java - How to create a custom dialog box?

i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.

Sample Error Dialog from CUstomDialog API: CustomDialog Error Message

Get querystring from URL using jQuery

Have a look at this Stack Overflow answer.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

You can use the method to animate:

I.e.:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths

From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).

More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.

Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.

How to count the number of letters in a string without the spaces?

Simply solution using the sum function:

sum(c != ' ' for c in word)

It's a memory efficient solution because it uses a generator rather than creating a temporary list and then calculating the sum of it.

It's worth to mention that c != ' ' returns True or False, which is a value of type bool, but bool is a subtype of int, so you can sum up bool values (True corresponds to 1 and False corresponds to 0)

You can check for an inheretance using the mro method:

>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]

Here you see that bool is a subtype of int which is a subtype of object.

Adding an assets folder in Android Studio

According to new Gradle based build system. We have to put assets under main folder.

Or simply right click on your project and create it like

File > New > folder > assets Folder

Setting a minimum/maximum character count for any character using a regular expression

It's usually the metacharacter . when not inside a character class.

So use ^.{1,35}$. However, dot does not include newlines unless the dot-all modifier is applied against it.

You can use ^[\S\s]{1,35}$ without any modifiers, and this includes newlines as well.

How to set dialog to show in full screen?

The easiest way I found

Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
        dialog.setContentView(R.layout.frame_help);
        dialog.show();

CSS 3 slide-in from left transition

You can use CSS3 transitions or maybe CSS3 animations to slide in an element.

For browser support: http://caniuse.com/

I made two quick examples just to show you how I mean.

CSS transition (on hover)

Demo One

Relevant Code

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

In this case, Im just transitioning the position from left: -100px; to 0; with a 1s. duration. It's also possible to move the element using transform: translate();

CSS animation

Demo Two

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    -webkit-animation: slide 0.5s forwards;
    -webkit-animation-delay: 2s;
    animation: slide 0.5s forwards;
    animation-delay: 2s;
}

@-webkit-keyframes slide {
    100% { left: 0; }
}

@keyframes slide {
    100% { left: 0; }
}

Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode to forwards, which will persist the end state, keeping the div visible when the animation ends.

Like I said, two quick example to show you how it could be done.

EDIT: For details regarding CSS Animations and Transitions see:

Animations

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations

Transitions

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

Hope this helped.

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Write a file on iOS

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

Moving uncommitted changes to a new branch

Just create a new branch with git checkout -b ABC_1; your uncommitted changes will be kept, and you then commit them to that branch.

Array.sort() doesn't sort numbers correctly

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

array.sort([compareFunction])

Parameters

compareFunction

Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:

13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.

Eclipse reported "Failed to load JNI shared library"

JRE 7 is probably installed in Program Files\Java and NOT Program Files(x86)\Java.

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals

$('#modalOne').modal('toggle');
$('#modalTwo').modal('toggle');

Flask-SQLalchemy update a row's information

Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit().

For example:

admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()

user = User.query.get(5)
user.name = 'New Name'
db.session.commit()

Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.

Username and password in command for git push

For anyone having issues with passwords with special chars just omit the password and it will prompt you for it:

git push https://[email protected]/YOUR_GIT_USERNAME/yourGitFileName.git

Row names & column names in R

I think that using colnames and rownames makes the most sense; here's why.

Using names has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames whenever you use matrices. By calling colnames, you only have to remember one function. Finally, if you look at the code for colnames, you will see that it calls names in the case of a data frame anyway, so the output is identical.

rownames and row.names return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames will print "NULL" (as does colnames), but row.names returns it invisibly. Since there isn't much to choose between the two functions, rownames wins on the grounds of aesthetics, since it pairs more prettily withcolnames. (Also, for the lazy programmer, you save a character of typing.)

Display fullscreen mode on Tkinter

This creates a fullscreen window. Pressing Escape resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape toggles between the current geometry and the previous geometry.

import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()

Template not provided using create-react-app

"If you've previously installed create-react-app globally via npm install -g create-react-app, we recommend you uninstall the package using npm uninstall -g create-react-app to ensure that npx always uses the latest version"

This is reported at https://create-react-app.dev/docs/getting-started/. For me, this did not work. I had to re-install create-react-app globally instead.

My steps to fix this problem were to:

  1. npm uninstall -g create-react-app
  2. npm install -g create-react-app
  3. npx create-react-app my-app

Add an object to a python list

You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

mylist[:]

Example:

>>> first = [1,2,3]
>>> second = first[:]
>>> second.append(4)
>>> first
[1, 2, 3]
>>> second
[1, 2, 3, 4]

And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

>>> first = [1,2,3]
>>> second = first
>>> second.append(4)
>>> first
[1, 2, 3, 4]
>>> second
[1, 2, 3, 4]

Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.

Cross-browser bookmark/add to favorites JavaScript

I'm thinking no. Bookmarks/favorites should be under the control of the user, imagine if any site you visited could insert itself into your bookmarks with just some javascript.

What's the effect of adding 'return false' to a click event listener?

The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.

PHP check if date between two dates

You are comparing the dates as strings, which won't work because the comparison is lexicographical. It's the same issue as when sorting a text file, where a line 20 would appear after a line 100 because the contents are not treated as numbers but as sequences of ASCII codes. In addition, the dates created are all wrong because you are using a string format string where a timestamp is expected (second argument).

Instead of this you should be comparing timestamps of DateTime objects, for instance:

 $paymentDate = date_create();
 $contractDateBegin = date_create_from_format('d/m/Y', '01/01/2001');
 $contractDateEnd = date_create_from_format('d/m/Y', '01/01/2015');

Your existing conditions will then work correctly.

Create a remote branch on GitHub

It looks like github has a simple UI for creating branches. I opened the branch drop-down and it prompts me to "Find or create a branch ...". Type the name of your new branch, then click the "create" button that appears.

To retrieve your new branch from github, use the standard git fetch command.

create branch github ui

I'm not sure this will help your underlying problem, though, since the underlying data being pushed to the server (the commit objects) is the same no matter what branch it's being pushed to.

Set colspan dynamically with jquery

How about

$([your selector]).attr('colspan',3);

I would imagine that to work but have no way to test at the moment. Using .attr() would be the usual jQuery way of setting attributes of elements in the wrapped set.

As has been mentioned in another answer, in order to get this to work would require removing the td elements that have no text in them from the DOM. It may be easier to do this all server side

EDIT:

As was mentioned in the comments, there is a bug in attempting to set colspan using attr() in IE, but the following works in IE6 and FireFox 3.0.13.

Working Demo

notice the use of the attribute colSpan and not colspan - the former works in both IE and Firefox, but the latter does not work in IE. Looking at jQuery 1.3.2 source, it would appear that attr() attempts to set the attribute as a property of the element if

  1. it exists as a property on the element (colSpan exists as a property and defaults to 1 on <td> HTMLElements in IE and FireFox)
  2. the document is not xml and
  3. the attribute is none of href, src or style

using colSpan as opposed to colspan works with attr() because the former is a property defined on the element whereas the latter is not.

the fall-through for attr() is to attempt to use setAttribute() on the element in question, setting the value to a string, but this causes problems in IE (bug #1070 in jQuery)

// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value ); 

In the demo, for each row, the text in each cell is evaluated. If the text is a blank string, then the cell is removed and a counter incremented. The first cell in the row that does not have class="colTime" has a colspan attribute set to the value of the counter + 1 (for the span it occupies itself).

After this, for each row, the text in the cell with class="colspans" is set to the colspan attribute values of each cell in the row from left to right.

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
td { text-align: center; }
</style>
</head>
<body>
<table  class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
 <tbody>
        <tr>
            <th align="left">Time</th>
            <th align="left">Room 1</th>
            <th align="left">Room 2</th>
            <th align="left">Room 3</th> 
            <th align="left">Colspans (L -> R)</th>
        </tr>
        <tr valign="top">
            <td class="colTime">09:00 – 10:00</td>
            <td class="col1"></td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>
        </tr>

        <tr valign="top">
            <td class="colTime">10:00 – 10:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>    
             <td class="colspans">holder</td> 
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>
            <td class="colspans">holder</td>     
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>     
        </tr>
</tbody>
</table>

</body>
</html>

jQuery code

$(function() {

  $('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;

    $('td', tr).each(function(index, value) {
      var td = $(this);

      if (td.text() == "") {
        counter++;
        td.remove();
      }
    });

    if (counter !== 0) {
      $('td:not(.colTime):first', tr)
        .attr('colSpan', '' + parseInt(counter + 1,10) + '');
    }
  });

  $('td.colspans').each(function(){
    var td = $(this);
    var colspans = [];

    td.siblings().each(function() {
      colspans.push(($(this).attr('colSpan')) == null ? 1 : $(this).attr('colSpan'));
    });

    td.text(colspans.join(','));
  });

});

This is just a demonstration to show that attr() can be used, but to be aware of it's implementation and the cross-browser quirks that come with it. I've also made some assumptions about your table layout in the demo (i.e. apply the colspan to the first "non-Time" cell in each row), but hopefully you get the idea.

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Checking if output of a command contains a certain string in a shell script

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then
   echo "matched"
fi

and also:

./somecommand | grep -q 'string' && echo 'matched'

javascript get child by id

If the child is always going to be a specific tag then you could do it like this

function test(el)
{
 var children = el.getElementsByTagName('div');// any tag could be used here..

  for(var i = 0; i< children.length;i++)
  {
    if (children[i].getAttribute('id') == 'child') // any attribute could be used here
    {
     // do what ever you want with the element..  
     // children[i] holds the element at the moment..

    }
  }
}

Difference between static, auto, global and local variable in the context of c and c++

Difference is static variables are those variables: which allows a value to be retained from one call of the function to another. But in case of local variables the scope is till the block/ function lifetime.

For Example:

#include <stdio.h>

void func() {
    static int x = 0; // x is initialized only once across three calls of func()
    printf("%d\n", x); // outputs the value of x
    x = x + 1;
}

int main(int argc, char * const argv[]) {
    func(); // prints 0
    func(); // prints 1
    func(); // prints 2
    return 0;
}

SQL Server: UPDATE a table by using ORDER BY

I had a similar problem and solved it using ROW_NUMBER() in combination with the OVER keyword. The task was to retrospectively populate a new TicketNo (integer) field in a simple table based on the original CreatedDate, and grouped by ModuleId - so that ticket numbers started at 1 within each Module group and incremented by date. The table already had a TicketID primary key (a GUID).

Here's the SQL:

UPDATE Tickets SET TicketNo=T2.RowNo
FROM Tickets
INNER JOIN 
  (select TicketID, TicketNo, 
     ROW_NUMBER() OVER (PARTITION BY ModuleId ORDER BY DateCreated) AS RowNo from Tickets) 
  AS T2 ON T2.TicketID = Tickets.TicketID

Worked a treat!

SELECT data from another schema in oracle

Does the user that you are using to connect to the database (user A in this example) have SELECT access on the objects in the PCT schema? Assuming that A does not have this access, you would get the "table or view does not exist" error.

Most likely, you need your DBA to grant user A access to whatever tables in the PCT schema that you need. Something like

GRANT SELECT ON pct.pi_int
   TO a;

Once that is done, you should be able to refer to the objects in the PCT schema using the syntax pct.pi_int as you demonstrated initially in your question. The bracket syntax approach will not work.

AngularJS Folder Structure

I like this entry about angularjs structure

It's written by one of the angularjs developers, so should give you a good insight

Here's an excerpt:

root-app-folder
+-- index.html
+-- scripts
¦   +-- controllers
¦   ¦   +-- main.js
¦   ¦   +-- ...
¦   +-- directives
¦   ¦   +-- myDirective.js
¦   ¦   +-- ...
¦   +-- filters
¦   ¦   +-- myFilter.js
¦   ¦   +-- ...
¦   +-- services
¦   ¦   +-- myService.js
¦   ¦   +-- ...
¦   +-- vendor
¦   ¦   +-- angular.js
¦   ¦   +-- angular.min.js
¦   ¦   +-- es5-shim.min.js
¦   ¦   +-- json3.min.js
¦   +-- app.js
+-- styles
¦   +-- ...
+-- views
    +-- main.html
    +-- ...

How to fully clean bin and obj folders within Visual Studio?

This site: https://sachabarbs.wordpress.com/2014/10/24/powershell-to-clean-visual-studio-binobj-folders/ uses William Kempf's powershell commands to remove any bin and obj folders from the current directory and sub directories. It should be possible to run it from the root of the drive.

Here is William's version

 gci -inc bin,obj -rec | rm -rec -force

In William's own words:

That wipes out all of the “bin” and “obj” directories in the current directory and every subdirectory. Super useful to run in your workspace directory to get to a “clean” state, especially when someone messes up and there’s something that a Clean or Rebuild inside the IDE doesn’t catch.

For those of you reading that may not know, PowerShell supports command aliases, here it is rewritten again not using the aliases

Get-ChildItem -inc bin,obj -rec | Remove-Item -rec -force

NOTE : You should have this stored in a PowerShell file and place that file at the root of your solution (where the .sln file resides), and then run it when you want a proper clean (not the micky mouse one that VisualStudio does, and reports success too).

Angular 4/5/6 Global Variables

You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.

How can I tell if a DOM element is visible in the current viewport?

I use this function (it only checks if the y is inscreen since most of the time the x is not needed)

function elementInViewport(el) {
    var elinfo = {
        "top":el.offsetTop,
        "height":el.offsetHeight,
    };

    if (elinfo.top + elinfo.height < window.pageYOffset || elinfo.top > window.pageYOffset + window.innerHeight) {
        return false;
    } else {
        return true;
    }

}

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()

Java : Accessing a class within a package, which is the better way?

There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here

Deciding between HttpClient and WebClient

Firstly, I am not an authority on WebClient vs. HttpClient, specifically. Secondly, from your comments above, it seems to suggest that WebClient is Sync ONLY whereas HttpClient is both.

I did a quick performance test to find how WebClient (Sync calls), HttpClient (Sync and Async) perform. and here are the results.

I see that as a huge difference when thinking for future, i.e. long running processes, responsive GUI, etc. (add to the benefit you suggest by framework 4.5 - which in my actual experience is hugely faster on IIS)

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

Converting between datetime, Timestamp and datetime64

I've come back to this answer more times than I can count, so I decided to throw together a quick little class, which converts a Numpy datetime64 value to Python datetime value. I hope it helps others out there.

from datetime import datetime
import pandas as pd

class NumpyConverter(object):
    @classmethod
    def to_datetime(cls, dt64, tzinfo=None):
        """
        Converts a Numpy datetime64 to a Python datetime.
        :param dt64: A Numpy datetime64 variable
        :type dt64: numpy.datetime64
        :param tzinfo: The timezone the date / time value is in
        :type tzinfo: pytz.timezone
        :return: A Python datetime variable
        :rtype: datetime
        """
        ts = pd.to_datetime(dt64)
        if tzinfo is not None:
            return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, tzinfo=tzinfo)
        return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)

I'm gonna keep this in my tool bag, something tells me I'll need it again.

How do I base64 encode a string efficiently using Excel VBA?

You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)      

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument 
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.Text 

  Set objNode = Nothing
  Set objXML = Nothing
End Function

How to export a CSV to Excel using Powershell

Why would you bother? Load your CSV into Excel like this:

$csv = Join-Path $env:TEMP "process.csv"
$xls = Join-Path $env:TEMP "process.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.OpenText($csv)

$wb.SaveAs($xls, 51)

You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter if need be.


Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

$i = 1
Import-Csv $csv | ForEach-Object {
  $j = 1
  foreach ($prop in $_.PSObject.Properties) {
    if ($i -eq 1) {
      $ws.Cells.Item($i, $j++).Value = $prop.Name
    } else {
      $ws.Cells.Item($i, $j++).Value = $prop.Value
    }
  }
  $i++
}

$wb.SaveAs($xls, 51)
$wb.Close()

$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Obviously this second approach won't perform too well, because it's processing each cell individually.

How can I add a custom HTTP header to ajax request with js or jQuery?

Assuming JQuery ajax, you can add custom headers like -

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

Css height in percent not working

You need to set a 100% height on all your parent elements, in this case your body and html. This fiddle shows it working.

_x000D_
_x000D_
html, body { height: 100%; width: 100%; margin: 0; }_x000D_
div { height: 100%; width: 100%; background: #F52887; }
_x000D_
<html><body><div></div></body></html>
_x000D_
_x000D_
_x000D_

How to find out which JavaScript events fired?

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.

  • Enter monitorEvents(window);

  • View the console flooded with events

     ...
     mousemove MouseEvent {dataTransfer: ...}
     mouseout MouseEvent {dataTransfer: ...}
     mouseover MouseEvent {dataTransfer: ...}
     change Event {clipboardData: ...}
     ...
    

There are other examples in the documentation. I'm guessing this feature was added after the previous answer.

pip install mysql-python fails with EnvironmentError: mysql_config not found

OSX Mavericks

Due to changes within osx mavericks & xcode development tools you may get the error on installation

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

therefore use :

sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install mysql-python

Get UTC time and local time from NSDate object

NSDate is a specific point in time without a time zone. Think of it as the number of seconds that have passed since a reference date. How many seconds have passed in one time zone vs. another since a particular reference date? The answer is the same.

Depending on how you output that date (including looking at the debugger), you may get an answer in a different time zone.

If they ran at the same moment, the values of these are the same. They're both the number of seconds since the reference date, which may be formatted on output to UTC or local time. Within the date variable, they're both UTC.

Objective-C:

NSDate *UTCDate = [NSDate date]

Swift:

let UTCDate = NSDate.date()

To explain this, we can use a NSDateFormatter in a playground:

import UIKit

let date = NSDate.date()
    // "Jul 23, 2014, 11:01 AM" <-- looks local without seconds. But:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let defaultTimeZoneStr = formatter.stringFromDate(date)
    // "2014-07-23 11:01:35 -0700" <-- same date, local, but with seconds
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
let utcTimeZoneStr = formatter.stringFromDate(date)
    // "2014-07-23 18:01:41 +0000" <-- same date, now in UTC

The date output varies, but the date is constant. This is exactly what you're saying. There's no such thing as a local NSDate.

As for how to get microseconds out, you can use this (put it at the bottom of the same playground):

let seconds = date.timeIntervalSince1970
let microseconds = Int(seconds * 1000) % 1000 // chops off seconds

To compare two dates, you can use date.compare(otherDate).

How to get Database Name from Connection String using SqlConnectionStringBuilder

string connectString = "Data Source=(local);" + "Integrated Security=true";

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);

Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);

How to calculate the sum of the datatable column in asp.net?

Compute Sum of Column in Datatable , Works 100%

lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();

if you want to have any conditions, use it like this

   lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();

How should I remove all the leading spaces from a string? - swift

For swift 3.0

import Foundation

var str = " Hear me calling"

extension String {
    var stringByRemovingWhitespaces: String {
        return components(separatedBy: .whitespaces).joined()
    }
}

str.stringByRemovingWhitespaces  // Hearmecalling

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

Choosing a file in Python with simple Dialog

How about using tkinter?

from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

Done!

show/hide a div on hover and hover out

I found using css opacity is better for a simple show/hide hover, and you can add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.

JS fiddle Demo

CSS

#stuff {
    opacity: 0.0;
    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
}
#hover {
    width:80px;
    height:20px;
    background-color:green;
    margin-bottom:15px;
}
#hover:hover + #stuff {
    opacity: 1.0;
}

HTML

<div id="hover">Hover</div>
<div id="stuff">stuff</div>

Adding multiple class using ng-class

For the ternary operator notation:

<div ng-class="expression1? 'class1 class2' : 'class3 class4'">

Sorting Values of Set

Use a SortedSet (TreeSet is the default one):

SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);

No extra sorting code needed.

Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:

new TreeSet<String>(Comparator.comparing(Integer::valueOf));

Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)

Reference:

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

Getting all types in a namespace via reflection

Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:

// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);

Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here

// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
    return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}

That should help with loading types defined in other assemblies.

Hope that helps!

Remove all child elements of a DOM node in JavaScript

Why aren't we following the simplest method here "remove" looped inside while.

const foo = document.querySelector(".foo");
while (foo.firstChild) {
  foo.firstChild.remove();     
}
  • Selecting the parent div
  • Using "remove" Method inside a While loop for eliminating First child element , until there is none left.

how to set active class to nav menu from twitter bootstrap

<div class="nav-collapse">
                <ul class="nav">
                    <li class="home"><a href="~/Home/Index">Home</a></li>
                    <li class="Project"><a href="#">Project</a></li>
                    <li class="Customer"><a href="#">Customer</a></li>
                    <li class="Staff"><a href="#">Staff</a></li>
                    <li class="Broker"><a href="~/Home/Broker">Broker</a></li>
                    <li class="Sale"><a href="#">Sale</a></li>
                </ul>
</div>

then for each page you add this:

//home

 $(document).ready(function () {
        $('.home').addClass('active');
    });

//Project page

$(document).ready(function () {
            $('.Project').addClass('active');
        });

//Customer page

 $(document).ready(function () {
                $('.Customer').addClass('active');
            });

//staff page

 $(document).ready(function () {
                $('.Staff').addClass('active');
            });

Use child_process.execSync but keep output in console

Unless you redirect stdout and stderr as the accepted answer suggests, this is not possible with execSync or spawnSync. Without redirecting stdout and stderr those commands only return stdout and stderr when the command is completed.

To do this without redirecting stdout and stderr, you are going to need to use spawn to do this but it's pretty straight forward:

var spawn = require('child_process').spawn;

//kick off process of listing files
var child = spawn('ls', ['-l', '/']);

//spit stdout to screen
child.stdout.on('data', function (data) {   process.stdout.write(data.toString());  });

//spit stderr to screen
child.stderr.on('data', function (data) {   process.stdout.write(data.toString());  });

child.on('close', function (code) { 
    console.log("Finished with code " + code);
});

I used an ls command that recursively lists files so that you can test it quickly. Spawn takes as first argument the executable name you are trying to run and as it's second argument it takes an array of strings representing each parameter you want to pass to that executable.

However, if you are set on using execSync and can't redirect stdout or stderr for some reason, you can open up another terminal like xterm and pass it a command like so:

var execSync = require('child_process').execSync;

execSync("xterm -title RecursiveFileListing -e ls -latkR /");

This will allow you to see what your command is doing in the new terminal but still have the synchronous call.

Logcat not displaying my log calls

I figured out I was automatically importing com.sileria.Log (from some library project) instead of android.util.Log, where the latter was the correct one. Check your imports as well.

C++ wait for user input

a do while loop would be a nice way to wait for the user input. Like this:

int main() 
{

 do 
 {
   cout << '\n' << "Press a key to continue...";
 } while (cin.get() != '\n');

 return 0;
}

You can also use the function system('PAUSE') but I think this is a bit slower and platform dependent

How to increase the gap between text and underlining in CSS

No, but you could go with something like border-bottom: 1px solid #000 and padding-bottom: 3px.

If you want the same color of the "underline" (which in my example is a border), you just leave out the color declaration, i.e. border-bottom-width: 1px and border-bottom-style: solid.

For multiline, you can wrap you multiline texts in a span inside the element. E.g. <a href="#"><span>insert multiline texts here</span></a> then just add border-bottom and padding on the <span> - Demo

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

Subprocess changing directory

To run your_command as a subprocess in a different directory, pass cwd parameter, as suggested in @wim's answer:

import subprocess

subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)

A child process can't change its parent's working directory (normally). Running cd .. in a child shell process using subprocess won't change your parent Python script's working directory i.e., the code example in @glglgl's answer is wrong. cd is a shell builtin (not a separate executable), it can change the directory only in the same process.

SQL-Server: The backup set holds a backup of a database other than the existing

I had ran into similar problem today. Tried all the above solutions but didn't worked. So posting my solution here.

Don't forget to uncheck Tail-long Backup before restore

Don't forget to uncheck Tail-long Backup before restore

Hope it help others too!

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

I just encountered this and whilst we already had .NET 4.0 installed on the server it turns out we only had the "Client Profile" version and not the "Full" version. Installing the latter fixed the problem.

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

Remove duplicate rows in MySQL

If you don't want to alter the column properties, then you can use the query below.

Since you have a column which has unique IDs (e.g., auto_increment columns), you can use it to remove the duplicates:

DELETE `a`
FROM
    `jobs` AS `a`,
    `jobs` AS `b`
WHERE
    -- IMPORTANT: Ensures one version remains
    -- Change "ID" to your unique column's name
    `a`.`ID` < `b`.`ID`

    -- Any duplicates you want to check for
    AND (`a`.`title` = `b`.`title` OR `a`.`title` IS NULL AND `b`.`title` IS NULL)
    AND (`a`.`company` = `b`.`company` OR `a`.`company` IS NULL AND `b`.`company` IS NULL)
    AND (`a`.`site_id` = `b`.`site_id` OR `a`.`site_id` IS NULL AND `b`.`site_id` IS NULL);

In MySQL, you can simplify it even more with the NULL-safe equal operator (aka "spaceship operator"):

DELETE `a`
FROM
    `jobs` AS `a`,
    `jobs` AS `b`
WHERE
    -- IMPORTANT: Ensures one version remains
    -- Change "ID" to your unique column's name
    `a`.`ID` < `b`.`ID`

    -- Any duplicates you want to check for
    AND `a`.`title` <=> `b`.`title`
    AND `a`.`company` <=> `b`.`company`
    AND `a`.`site_id` <=> `b`.`site_id`;

Create an ArrayList of unique values

HashSet hs = new HashSet();
                hs.addAll(arrayList);
                arrayList.clear();
                arrayList.addAll(hs);

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

JQuery get all elements by class name

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
    console.log($(this).html());
    mvar += $(this).html();
});
console.log(mvar);

jQuery AJAX submit form

There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.

examples

Using os.walk() to recursively traverse directories in Python

#!/usr/bin/python

import os 

def tracing(a):
    global i>
    for item in os.listdir(a):
        if os.path.isfile(item):
            print i + item 
        else:
            print i + item 
            i+=i
            tracing(item)

i = "---"
tracing(".")

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

How do I parse a string to a float or int?

float("545.2222") and int(float("545.2222"))

Xcode error "Could not find Developer Disk Image"

This message appears when your version of Xcode is too old for the device's version of iOS. Upgrade Xcode to the latest.

If the App Store doesn't offer an update for Xcode, upgrade to the latest Mac OS. In the past, Apple has been rather aggressive about dropping support for past versions of Mac OS X in the latest Xcode.

EDIT: yes, this error started popping up all over again. :) Xcode 7.3.1, which is the latest one that's available for MacOS 10.11 (El Capitan), doesn't support iOS 10. You need MacOS Sierra (and possibly a new Mac).

What is the purpose of Order By 1 in SQL select statement?

This:

ORDER BY 1

...is known as an "Ordinal" - the number stands for the column based on the number of columns defined in the SELECT clause. In the query you provided, it means:

ORDER BY A.PAYMENT_DATE

It's not a recommended practice, because:

  1. It's not obvious/explicit
  2. If the column order changes, the query is still valid so you risk ordering by something you didn't intend

How can I install Python's pip3 on my Mac?

I also encountered the same problem but brew install python3 does not work properly to install pip3.

brre will throw the warning The post-install step did not complete successfully.

It has to do with homebrew does not have permission to /usr/local

Create the directory if not exist

sudo mkdir lib 
sudo mkdir Frameworks

Give the permissions inside /usr/local to homebrew so it can access them:

sudo chown -R $(whoami) $(brew --prefix)/*

Now ostinstall python3

brew postinstall python3

This will give you a successful installation

This version of the application is not configured for billing through Google Play

In the old developer console:

Settings -> Account details -> License Testing -> Gmail accounts with testing access and type here your accounts

In new developer console:

Settings -> License Testing -> Type your Gmail account, hit 'Enter' and click 'Save'.

Redirecting to a relative URL in JavaScript

try following js code

_x000D_
_x000D_
location = '..'
_x000D_
_x000D_
_x000D_

How to display both icon and title of action inside ActionBar?

Follow these steps:

  1. Add the Action Bar instance in the Java Code final ActionBar actionBar = getActionBar();
  2. Enable the Home Display Option actionBar.setDisplayShowHomeEnabled(false);
  3. Add the following code in the respective activity's manifest file android:logo=@drawable/logo and android:label="@string/actionbar_text"

I think this will help you

How to get the width of a react element

A simple and up to date solution is to use the React React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.

import React, {useState, useEffect, useRef} from 'react';

export default App = () => {
  const [width, setWidth] = useState(0);
  const elementRef = useRef(null);

  useEffect(() => {
    setWidth(elementRef.current.getBoundingClientRect().width);
  }, []); //empty dependency array so it only runs once at render

  return (
    <div ref={elementRef}>
      {width}
    </div>
  )
}

Using grep to search for hex strings in a file

There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):

$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL     HEX         DESCRIPTION
--------------------------------------------------------------------------
377654      0x5C336     Raw string signature

'python' is not recognized as an internal or external command

You need to add that folder to your Windows Path:

https://docs.python.org/2/using/windows.html Taken from this question.

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.

How to rollback just one step using rake db:migrate

Roll back the most recent migration:

rake db:rollback

Roll back the n most recent migrations:

rake db:rollback STEP=n

You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.


Here's some more:

  • rake db:migrate - Run all migrations that haven't been run already
  • rake db:migrate VERSION=20080906120000 - Run all necessary migrations (up or down) to get to the given version
  • rake db:migrate RAILS_ENV=test - Run migrations in the given environment
  • rake db:migrate:redo - Roll back one migration and run it again
  • rake db:migrate:redo STEP=n - Roll back the last n migrations and run them again
  • rake db:migrate:up VERSION=20080906120000 - Run the up method for the given migration
  • rake db:migrate:down VERSION=20080906120000 - Run the down method for the given migration

And to answer your question about where you get a migration's version number from:

The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run

$ rake db:migrate VERSION=20080906120000

(From Running Migrations in the Rails Guides)

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

capture div into image using html2canvas

window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

_x000D_
_x000D_
$("#btn_screenshot").click(function(){_x000D_
     element_to_png("container", "testhtmltocanvasimg");_x000D_
});_x000D_
_x000D_
_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
    console.log("element_to_png called for element id " + srcElementID);_x000D_
    html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
        var myImage = canvas.toDataURL("image/png");_x000D_
        $("#"+targetIMGid).attr("src", myImage);_x000D_
  console.log("html2canvas completed.  png rendered to " + targetIMGid);_x000D_
    });_x000D_
}
_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
   <img src="" id="testhtmltocanvasimg">_x000D_
</div>
_x000D_
_x000D_
_x000D_

I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!