Programs & Examples On #Nsaffinetransform

How to get the difference between two arrays in JavaScript?

You could use a Set in this case. It is optimized for this kind of operation (union, intersection, difference).

Make sure it applies to your case, once it allows no duplicates.

var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);

a.difference(b)
// -> Set{1,3,5,7,9}

How to get param from url in angular 4?

Check parameters from URL string or as :param in your routeConfig

downstream.component.ts

...
import {Router,ActivatedRoute} from '@angular/router';
...    
export class DownstreamComponent  {
    constructor(
    private route: ActivatedRoute,
    private router: Router
) {
    if(this.route.snapshot.queryParams) 
      console.log(this.route.snapshot.params); // e.g. :param1 in routeConfig
    if(this.route.snapshot.queryParamMap.get('param1'))
      console.log(this.route.snapshot.queryParamMap.get('param1')); // e.g. in URI ?param1=blah
}

}

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

In my case, I solved adding return in the onClientClick:

Code Behind

function verify(){
  if (document.getElementById("idName").checked == "") {
    alert("Fill the field");
    return false;
  }
}

Design Surface

<asp:Button runat="server" ID="send" Text="Send" onClientClick="return verify()" />

git: 'credential-cache' is not a git command

Looks like git now comes with wincred out-of-the-box on Windows (msysgit):

git config --global credential.helper wincred

Reference: https://github.com/msysgit/git/commit/e2770979fec968a25ac21e34f9082bc17a71a780

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

How to remove/delete a large file from commit history in Git repository?

100 times faster than git filter-branch and simpler

There are very good answers in this thread, but meanwhile many of them are outdated. Using git-filter-branch is no longer recommended, because it is difficult to use and awfully slow on big repositories.

git-filter-repo is much faster and simpler to use.

git-filter-repo is a Python script, available at github: https://github.com/newren/git-filter-repo . When installed it looks like a regular git command and can be called by git filter-repo.

You need only one file: the Python3 script git-filter-repo. Copy it to a path that is included in the PATH variable. On Windows you may have to change the first line of the script (refer INSTALL.md). You need Python3 installed installed on your system, but this is not a big deal.

First you can run

git filter-repo --analyze

This helps you to determine what to do next.

You can delete your DVD-rip file everywhere:

git filter-repo --invert-paths --path-match DVD-rip
 

Filter-repo is really fast. A task that took around 9 hours on my computer by filter-branch, was completed in 4 minutes by filter-repo. You can do many more nice things with filter-repo. Refer to the documentation for that.

Warning: Do this on a copy of your repository. Many actions of filter-repo cannot be undone. filter-repo will change the commit hashes of all modified commits (of course) and all their descendants down to the last commits!

Move branch pointer to different commit without checkout

Honestly, I'm surprised how nobody thought about the git push command:

git push -f . <destination>:<branch>

The dot ( . ) refers the local repository, and you may need the -f option because the destination could be "behind its remote counterpart".

Although this command is used to save your changes in your server, the result is exactly the same as if moving the remote branch (<branch>) to the same commit as the local branch (<destination>)

How do I line up 3 divs on the same row?

Just add float left property on all the divs you want to make appear in a row other than last one. here is example

<div>
  <div style="float: left;">A</div>
  <div style="float: left;">B</div>
  <div>C</div>
</div>

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

How do I find a default constraint using INFORMATION_SCHEMA?

How about using a combination of CHECK_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE:

    select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name
          from information_schema.columns columns
             inner join information_schema.constraint_column_usage usage on 
                  columns.column_name = usage.column_name and columns.table_name = usage.table_name
             inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name
    where columns.column_default is not null

Displaying the build date

I am just C# newbie so maybe my answer sound silly - I display the build date from the date the executable file was last written to:

string w_file = "MyProgram.exe"; 
string w_directory = Directory.GetCurrentDirectory();

DateTime c3 =  File.GetLastWriteTime(System.IO.Path.Combine(w_directory, w_file));
RTB_info.AppendText("Program created at: " + c3.ToString());

I tried to use File.GetCreationTime method but got weird results: the date from the command was 2012-05-29, but the date from the Window Explorer showed 2012-05-23. After searching for this discrepancy I found that the file was probably created on 2012-05-23 (as shown by Windows Explorer), but copied to the current folder on 2012-05-29 (as shown by File.GetCreationTime command) - so to be on the safe side I am using File.GetLastWriteTime command.

Zalek

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

How to check if the key pressed was an arrow key in Java KeyListener?

If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());

How do I convert Word files to PDF programmatically?

PDFCreator has a COM component, callable from .NET or VBScript (samples included in the download).

But, it seems to me that a printer is just what you need - just mix that with Word's automation, and you should be good to go.

Truncating long strings with CSS: feasible yet?

2014 March: Truncating long strings with CSS: a new answer with focus on browser support

Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.

Successfully tested (on Browserstack.com) on Windows OS, for web browsers:

  • IE6 to IE11
  • Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
  • Chrome 14, Chrome 20, Chrome 25
  • Safari 4.0, Safari 5.0, Safari 5.1
  • Firefox 7.0, Firefox 15

Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).

I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).

Some further testing on a Mac OS web browsers would be needed.

Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated

Resources:

Open Sublime Text from Terminal in macOS

This is to get it working as an ALIAS, not a Symbolic link!

This will allow you to run additional commands in the terminal without interrupting the subl session. Using many of the symbolic link answers here (ln -s), cause the terminal process to endure while using Sublime text. If you want the separation, create an alias in the Bash profile like so:

  1. Test subl from your ST installation:

    First, navigate to a folder in Terminal that you want ST to open and enter the following command:

    /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl .
    

    NOTE: You may need to replace Sublime\ Text.app in the command above to Sublime\ Text\ 3.app or Sublime\ Text\ 2.app depending upon where the application is stored in your Applications directory. The . at the end of the above command opens the current working directory you are located in (again make sure you're in a directory that only contains a few files!).

    If you DO NOT get Sublime Text opening your current working directory then the next set of steps will NOT work. If nothing happens or you get an error from Terminal it will be because it couldn't find the Sublime Text application. This would mean that you would have to check what you've typed (spelling, etc.) OR that Sublime Text isn't installed!

  2. Check and update ".bash_profile":

    Now add the alias in your Bash Profile. Open it via vim ~/.bash_profile. These are the following lines that pertain to having subl work on the command line for Sublime Text:

    ## For Sublime Text 3 alias
    alias subl='/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl'
    ## For Sublime Text global editor preference **Optional
    export EDITOR='subl -w'
    

    I suggest always commenting your code in here with ##. The second line is OPTIONAL and just sets Sublime Text as the default editor. The flag -w has been added and you can find out more about flags by going to the Sublime Text docs: ST3 subl or ST2 subl

    If you do make any edits to this file once you have closed it, you need to source this file in your current session or close the terminal (tab) and open a new one. You can source this file by running the command source ~/.bash_profile Resolve any errors before moving to the final step.

Read all contacts' phone numbers in android

Load contacts in background using CursorLoader:

  CursorLoader cursor = new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            Cursor managedCursor = cursor.loadInBackground();

            int number = managedCursor.getColumnIndex(ContactsContract.Contacts.Data.DATA1);
            int name = managedCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            int index = 0;
            while (managedCursor.moveToNext()) {
                String phNumber = managedCursor.getString(number);
                String phName = managedCursor.getString(name);
            }

How to download fetch response in react as file

This worked for me.

const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};

fetch(`${url}`, requestOptions)
.then((res) => {
    return res.blob();
})
.then((blob) => {
    const href = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'config.json'); //or any other extension
    document.body.appendChild(link);
    link.click();
})
.catch((err) => {
    return Promise.reject({ Error: 'Something Went Wrong', err });
})

Windows- Pyinstaller Error "failed to execute script " When App Clicked

In my case i have a main.py that have dependencies with other files. After I build that app with py installer using this command:

pyinstaller --onefile --windowed main.py

I got the main.exe inside dist folder. I double clicked on this file, and I raised the error mentioned above. To fix this, I just copy the main.exe from dist directory to previous directory, which is the root directory of my main.py and the dependency files, and I got no error after run the main.exe.

E: Unable to locate package npm

From the official Node.js documentation:

A Node.js package is also available in the official repo for Debian Sid (unstable), Jessie (testing) and Wheezy (wheezy-backports) as "nodejs". It only installs a nodejs binary.

So, if you only type sudo apt-get install nodejs , it does not install other goodies such as npm.

You need to type:

curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install -y nodejs

Optional: install build tools

To compile and install native add-ons from npm you may also need to install build tools:

sudo apt-get install -y build-essential

More info: Docs

Eliminate extra separators below UITableView

I was using a table view to show a fixed number of fixed height rows, so I simply resized it and made it non-scrollable.

Calculating the distance between 2 points

Given points (X1,Y1) and (X2,Y2) then:

dX = X1 - X2;
dY = Y1 - Y2;

if (dX*dX + dY*dY > (5*5))
{
    //your code
}

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

Google's Android Documentation Says that :

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask's generic types :

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html

Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

Well The structure of a typical AsyncTask class goes like :

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){

    }

This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

    protected Z doInBackground(X...x){

    }

The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.

   protected void onProgressUpdate(Y y){

   }

This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

  protected void onPostExecute(Z z){

  }

This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

What about the X, Y and Z types?

As you can deduce from the above structure:

 X – The type of the input variables value you want to set to the background process. This can be an array of objects.

 Y – The type of the objects you are going to enter in the onProgressUpdate method.

 Z – The type of the result from the operations you have done in the background process.

How do we call this task from an outside class? Just with the following two lines:

MyTask myTask = new MyTask();

myTask.execute(x);

Where x is the input parameter of the type X.

Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.

 myTask.getStatus();

and we can receive the following status:

RUNNING - Indicates that the task is running.

PENDING - Indicates that the task has not been executed yet.

FINISHED - Indicates that onPostExecute(Z) has finished.

Hints about using AsyncTask

  1. Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

  2. You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

  3. The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

  4. The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

Unable to convert MySQL date/time value to System.DateTime

I also faced the same problem, and get the columns name and its types. Then cast(col_Name as Char) from table name. From this way i get the problem as '0000-00-00 00:00:00' then I Update as valid date and time the error gets away for my case.

Create request with POST, which response codes 200 or 201 and content

Another answer I would have for this would be to take a pragmatic approach and keep your REST API contract simple. In my case I had refactored my REST API to make things more testable without resorting to JavaScript or XHR, just simple HTML forms and links.

So to be more specific on your question above, I'd just use return code 200 and have the returned message contain a JSON message that your application can understand. Depending on your needs it may require the ID of the object that is newly created so the web application can get the data in another call.

One note, in my refactored API contract, POST responses should not contain any cacheable data as POSTs are not really cachable, so limit it to IDs that can be requested and cached using a GET request.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

File Upload using AngularJS

Use the onchange event to pass the input file element to your function.

<input type="file" onchange="angular.element(this).scope().fileSelected(this)" />

So when a user selects a file, you have a reference to it without the user needing to click an "Add" or "Upload" button.

$scope.fileSelected = function (element) {
    var myFileSelected = element.files[0];
};

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

Convert string to decimal number with 2 decimal places in Java

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);

You print Float here, that has no format at all.

To print formatted float, just use

String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);

How to center the text in PHPExcel merged cell

When using merged columns, I got it centered by using PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS instead of PHPExcel_Style_Alignment::HORIZONTAL_CENTER

Getting the class name from a static method in Java

If you are using reflection, you can get the Method object and then:

method.getDeclaringClass().getName()

To get the Method itself, you can probably use:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)

How to open a local disk file with JavaScript?

Consider reformatting your file into javascript. Then you can simply load it using good old...

<script src="thefileIwantToLoad.js" defer></script>

Disabling Chrome cache for website development

If you're using ServiceWorkers (e.g.: for Progressive web apps), you'll likely need to check "Update on reload" under Application > Service Workers in dev tools too.

enter image description here

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

Tesseract OCR simple example

Try updating the line to:

ocr.Init(@"C:\", "eng", false); // the path here should be the parent folder of tessdata

Good Free Alternative To MS Access

Are you aware that the Access 2007 runtime can be downloaded for free?

Links for newer versions:

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

How to get AM/PM from a datetime in PHP

For (PHP >= 5.2.0):

You can use DateTime class. However you might need to change your date format. Didn't try yours. The following date format will work for sure: YYYY-MM-DD HH-MM-SS

$date = new DateTime("2010-04-08 22:15:00");
echo $date->format("g"). '.' .$date->format("i"). ' ' .$date->format("A");

//output
//10.15 PM

However, in my opinion, using . as a separator for 10.15 is not recommended because your users might be confused either this is a decimal number or time format. The most common way is to use 10:15 PM

Create a symbolic link of directory in Ubuntu

In script is usefull something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

Passing HTML input value as a JavaScript Function Parameter

One way is by using document.getElementByID, as below -

_x000D_
_x000D_
<body>
  <h1>Adding 'a' and 'b'</h1>

  a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br>
  <button onclick="add(document.getElementById('a').value,document.getElementById('b').value)">Add</button>

  <script>
    function add(a, b) {
      var sum = parseInt(a, 10) + parseInt(b, 10);
      alert(sum);
    }
  </script>
</body>
_x000D_
_x000D_
_x000D_

"detached entity passed to persist error" with JPA/EJB code

The error occurs because the object's ID is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects. If persist concludes the object is detached (which it will because the ID is set), it will return the "detached object passed to persist" error. You can find more details here and here.

However, this only applies if you have specified the primary key to be auto-generated: if the field is configured to always be set manually, then your code works.

Solutions for INSERT OR UPDATE on SQL Server

IF EXISTS (SELECT * FROM [Table] WHERE ID = rowID)
UPDATE [Table] SET propertyOne = propOne, property2 . . .
ELSE
INSERT INTO [Table] (propOne, propTwo . . .)

Edit:

Alas, even to my own detriment, I must admit the solutions that do this without a select seem to be better since they accomplish the task with one less step.

Remove characters from a string

I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:

var str = theText.split('A').join('')

will remove all occurrences of 'A' from the string, obviously it's not case sensitive

Removing viewcontrollers from navigation stack

This solution worked for me in swift 4:

let VCCount = self.navigationController!.viewControllers.count
self.navigationController?.viewControllers.removeSubrange(Range(VCCount-3..<VCCount - 1))

your current view controller index in stack is:

self.navigationController!.viewControllers.count - 1

How do I determine the size of an object in Python?

I use this trick... May won't be accurate on small objects, but I think it's much more accurate for a complex object (like pygame surface) rather than sys.getsizeof()

import pygame as pg
import os
import psutil
import time


process = psutil.Process(os.getpid())
pg.init()    
vocab = ['hello', 'me', 'you', 'she', 'he', 'they', 'we',
         'should', 'why?', 'necessarily', 'do', 'that']

font = pg.font.SysFont("monospace", 100, True)

dct = {}

newMem = process.memory_info().rss  # don't mind this line
Str = f'store ' + f'Nothing \tsurface use about '.expandtabs(15) + \
      f'0\t bytes'.expandtabs(9)  # don't mind this assignment too

usedMem = process.memory_info().rss

for word in vocab:
    dct[word] = font.render(word, True, pg.Color("#000000"))

    time.sleep(0.1)  # wait a moment

    # get total used memory of this script:
    newMem = process.memory_info().rss
    Str = f'store ' + f'{word}\tsurface use about '.expandtabs(15) + \
          f'{newMem - usedMem}\t bytes'.expandtabs(9)

    print(Str)
    usedMem = newMem

On my windows 10, python 3.7.3, the output is:

store hello          surface use about 225280    bytes
store me             surface use about 61440     bytes
store you            surface use about 94208     bytes
store she            surface use about 81920     bytes
store he             surface use about 53248     bytes
store they           surface use about 114688    bytes
store we             surface use about 57344     bytes
store should         surface use about 172032    bytes
store why?           surface use about 110592    bytes
store necessarily    surface use about 311296    bytes
store do             surface use about 57344     bytes
store that           surface use about 110592    bytes

HTTP Get with 204 No Content: Is that normal

I use GET/204 with a RESTful collection that is a positional array of known fixed length but with holes.

GET /items
    200: ["a", "b", null]

GET /items/0
    200: "a"

GET /items/1
    200: "b"

GET /items/2
    204:

GET /items/3
    404: Not Found

How can I get the active screen dimensions?

Screen.FromControl, Screen.FromPoint and Screen.FromRectangle should help you with this. For example in WinForms it would be:

class MyForm : Form
{
  public Rectangle GetScreen()
  {
    return Screen.FromControl(this).Bounds;
  }
}

I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method.

static class ExtensionsForWPF
{
  public static System.Windows.Forms.Screen GetScreen(this Window window)
  {
    return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
  }
}

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

keyword not supported data source

This problem can occur when you reference your web.config (or app.config) connection strings by index...

var con = ConfigurationManager.ConnectionStrings[0].ConnectionString;

The zero based connection string is not always the one in your config file as it inherits others by default from further up the stack.

The recommended approaches are to access your connection by name...

var con = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

or to clear the connnectionStrings element in your config file first...

<connectionStrings>
    <clear/>
    <add name="MyConnection" connectionString="...

Pass connection string to code-first DbContext

For anyone who came here trying find out how to set connection string dinamicaly, and got trouble with the solutions above (like "Format of the initialization string does not conform to specification starting at index 0.") when setting up the connection string in the constructor. This is how to fix it:

public static string ConnectionString
{
    get {
        if (ConfigurationManager.AppSettings["DevelopmentEnvironment"] == "true")
            return ConfigurationManager.ConnectionStrings["LocalDb"].ConnectionString;
        else
            return ConfigurationManager.ConnectionStrings["ExternalDb"].ConnectionString;
    }
}

public ApplicationDbContext() : base(ConnectionString)
{
}

Prevent text selection after double click

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me. Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

How to discard local changes and pull latest from GitHub repository

Run the below commands

git log

From this you will get your last push commit hash key

git reset --hard <your commit hash key>

Select all text inside EditText when it gets focus

You can also add an OnClick Method to the editText after

_editText.setSelectAllOnFocus(true);

and in that:

_editText.clearFocus();
_editText.requestFocus();

As soon as you click the editText the whole text is selected.

Change New Google Recaptcha (v2) Width

Here is a work around but not always a great one, depending on how much you scale it. Explanation can be found here: https://www.geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/

.g-recaptcha {
    transform:scale(0.77);
    transform-origin:0 0;
}

UPDATE: Google has added support for a smaller size via a parameter. Have a look at the docs - https://developers.google.com/recaptcha/docs/display#render_param

What is exactly the base pointer and stack pointer? To what do they point?

Long time since I've done Assembly programming, but this link might be useful...

The processor has a collection of registers which are used to store data. Some of these are direct values while others are pointing to an area within RAM. Registers do tend to be used for certain specific actions and every operand in assembly will require a certain amount of data in specific registers.

The stack pointer is mostly used when you're calling other procedures. With modern compilers, a bunch of data will be dumped first on the stack, followed by the return address so the system will know where to return once it's told to return. The stack pointer will point at the next location where new data can be pushed to the stack, where it will stay until it's popped back again.

Base registers or segment registers just point to the address space of a large amount of data. Combined with a second regiser, the Base pointer will divide the memory in huge blocks while the second register will point at an item within this block. Base pointers therefor point to the base of blocks of data.

Do keep in mind that Assembly is very CPU specific. The page I've linked to provides information about different types of CPU's.

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

<dependency> 
            <groupId> org.springframework.boot </groupId> 
            <artifactId> spring-boot-starter-web </artifactId> 
            <version> 1.2.0.RELEASE </version> 
</dependency>

How can I print a quotation mark in C?

Try this:

#include <stdio.h>

int main()
{
  printf("Printing quotation mark \" ");
}

Truncate string in Laravel blade templates

In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.

While in Laravel 7 up, you can use the Str::limit helper.

//For Laravel  to Laravel 7

{{ Illuminate\Support\Str::limit($post->title, 20, $end='...') }}

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same error message while trying to deploy the application. In Spring, the security configuration xml can be a different one from applicationContext.xml, usually applicationContext-security.xml inside WEB-INF folder. The changes to be applied are for web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/applicationContext.xml
        /WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

And the applicationContext.xml would look like:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http auto-config='true'>
        <intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern="/**" access="ROLE_USER" />
        <form-login login-page='login.jsp'/>
    </http>

</beans:beans>

Even after you make these changes, the namespace error will exist. To get rid of this, add the following jar files to the WEB-INF/lib and then to the library:

  • spring-security-acl-3.1.0.M2.jar
  • spring-security-config-3.1.0.M2.jar
  • spring-security-core-3.1.0.M2.jar
  • spring-security-taglibs-3.1.0.M2.jar
  • spring-security-web-3.1.0.M2.jar

Can you use CSS to mirror/flip text?

Just adding a working demo for horizontal and vertical mirror flip.

_x000D_
_x000D_
.horizontal-flip {_x000D_
  -moz-transform: scale(-1, 1);_x000D_
  -webkit-transform: scale(-1, 1);_x000D_
  -o-transform: scale(-1, 1);_x000D_
  -ms-transform: scale(-1, 1);_x000D_
  transform: scale(-1, 1);_x000D_
}_x000D_
_x000D_
.vertical-flip {_x000D_
  -moz-transform: scale(1, -1);_x000D_
  -webkit-transform: scale(1, -1);_x000D_
  -o-transform: scale(1, -1);_x000D_
  -ms-transform: scale(1, -1);_x000D_
  transform: scale(1, -1);_x000D_
}
_x000D_
<div class="horizontal-flip">_x000D_
  Hello, World_x000D_
  <input type="text">_x000D_
</div>_x000D_
<hr>_x000D_
<div class="vertical-flip">_x000D_
  Hello, World_x000D_
  <input type="text">_x000D_
</div>
_x000D_
_x000D_
_x000D_

What would be the Unicode character for big bullet in the middle of the character?

If you are on Windows (Any Version)

Go to start -> then search character map

that's where you will find 1000s of characters with their Unicode in the advance view you can get more options that you can use for different encoding symbols.

Turn off textarea resizing

It can done easy by just using html draggable attribute

<textarea name="mytextarea" draggable="false"></textarea>

Default value is true.

How to redirect to another page using PHP

You could use a function similar to:

function redirect($url) {
    ob_start();
    header('Location: '.$url);
    ob_end_flush();
    die();
}

Worth noting, you should always use either ob_flush() or ob_start() at the beginning of your header('location: ...'); functions, and you should always follow them with a die() or exit() function to prevent further code execution.

Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/

This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.

How can I make a ComboBox non-editable in .NET?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this:

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Link to the documentation for the ComboBox DropDownStyle property on MSDN.

Why doesn't importing java.util.* include Arrays and Lists?

Case 1 should have worked. I don't see anything wrong. There may be some other problems. I would suggest a clean build.

How to enable Ad Hoc Distributed Queries

If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

How to change the DataTable Column Name?

Use this

dataTable.Columns["OldColumnName"].ColumnName = "NewColumnName";

unable to start mongodb local server

(If your're using linux,) if

mongod --shutdown --config=path/to/your/configFile.conf 

or

mongod --repair --config=path/to/your/configFile.conf 

didn't fix the issue, logout and re-login. That solved my problem.

Or you can kill the process manually from terminal, I guess.

Convert number to varchar in SQL with formatting

You can try this

DECLARE @Table TABLE(
        Val INT
)

INSERT INTO @Table SELECT 3
INSERT INTO @Table SELECT 30

DECLARE @NumberPrefix INT
SET @NumberPrefix = 2
SELECT  REPLICATE('0', @NumberPrefix - LEN(Val)) + CAST(Val AS VARCHAR(10))
FROM    @Table

How to add link to flash banner

@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.

movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
  var url:String = "http://site";
  var request:URLRequest = new URLRequest(url);
  try {
    navigateToURL(request, '_blank');
  } catch (e:Error) {
    trace("Error occurred!");
  }
}

source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

C#: Dynamic runtime cast

I think you're confusing the issues of casting and converting here.

  • Casting: The act of changing the type of a reference which points to an object. Either moving up or down the object hierarchy or to an implemented interface
  • Converting: Creating a new object from the original source object of a different type and accessing it through a reference to that type.

It's often hard to know the difference between the 2 in C# because both of them use the same C# operator: the cast.

In this situation you are almost certainly not looking for a cast operation. Casting a dynamic to another dynamic is essentially an identity conversion. It provides no value because you're just getting a dynamic reference back to the same underlying object. The resulting lookup would be no different.

Instead what you appear to want in this scenario is a conversion. That is morphing the underlying object to a different type and accessing the resulting object in a dynamic fashion. The best API for this is Convert.ChangeType.

public static dynamic Convert(dynamic source, Type dest) {
  return Convert.ChangeType(source, dest);
}

EDIT

The updated question has the following line:

obj definitely implements castTo

If this is the case then the Cast method doesn't need to exist. The source object can simply be assigned to a dynamic reference.

dynamic d = source;

It sounds like what you're trying to accomplish is to see a particular interface or type in the hierarchy of source through a dynamic reference. That is simply not possible. The resulting dynamic reference will see the implementation object directly. It doesn't look through any particular type in the hierarchy of source. So the idea of casting to a different type in the hierarchy and then back to dynamic is exactly identical to just assigning to dynamic in the first place. It will still point to the same underlying object.

How do you allow spaces to be entered using scanf?

You can use this

char name[20];
scanf("%20[^\n]", name);

Or this

void getText(char *message, char *variable, int size){
    printf("\n %s: ", message);
    fgets(variable, sizeof(char) * size, stdin);
    sscanf(variable, "%[^\n]", variable);
}

char name[20];
getText("Your name", name, 20);

DEMO

How to set focus on input field?

  1. When a Modal is opened, set focus on a predefined <input> inside this Modal.

Define a directive and have it $watch a property/trigger so it knows when to focus the element:

Name: <input type="text" focus-me="shouldBeOpen">

app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) {
    return {
        //scope: true,   // optionally create a child scope
        link: function (scope, element, attrs) {
            var model = $parse(attrs.focusMe);
            scope.$watch(model, function (value) {
                console.log('value=', value);
                if (value === true) {
                    $timeout(function () {
                        element[0].focus();
                    });
                }
            });
            // to address @blesh's comment, set attribute value to 'false'
            // on blur event:
            element.bind('blur', function () {
                console.log('blur');
                scope.$apply(model.assign(scope, false));
            });
        }
    };
}]);

Plunker

The $timeout seems to be needed to give the modal time to render.

'2.' Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

Create a directive essentially like the one above. Watch some scope property, and when it becomes true (set it in your ng-click handler), execute element[0].focus(). Depending on your use case, you may or may not need a $timeout for this one:

<button class="btn" ng-click="showForm=true; focusInput=true">show form and
 focus input</button>
<div ng-show="showForm">
  <input type="text" ng-model="myInput" focus-me="focusInput"> {{ myInput }}
  <button class="btn" ng-click="showForm=false">hide form</button>
</div>

app.directive('focusMe', function($timeout) {
  return {
    link: function(scope, element, attrs) {
      scope.$watch(attrs.focusMe, function(value) {
        if(value === true) { 
          console.log('value=',value);
          //$timeout(function() {
            element[0].focus();
            scope[attrs.focusMe] = false;
          //});
        }
      });
    }
  };
});

Plunker


Update 7/2013: I've seen a few people use my original isolate scope directives and then have problems with embedded input fields (i.e., an input field in the modal). A directive with no new scope (or possibly a new child scope) should alleviate some of the pain. So above I updated the answer to not use isolate scopes. Below is the original answer:

Original answer for 1., using an isolate scope:

Name: <input type="text" focus-me="{{shouldBeOpen}}">

app.directive('focusMe', function($timeout) {
  return {
    scope: { trigger: '@focusMe' },
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if(value === "true") { 
          $timeout(function() {
            element[0].focus(); 
          });
        }
      });
    }
  };
});

Plunker.

Original answer for 2., using an isolate scope:

<button class="btn" ng-click="showForm=true; focusInput=true">show form and
 focus input</button>
<div ng-show="showForm">
  <input type="text" focus-me="focusInput">
  <button class="btn" ng-click="showForm=false">hide form</button>
</div>

app.directive('focusMe', function($timeout) {
  return {
    scope: { trigger: '=focusMe' },
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if(value === true) { 
          //console.log('trigger',value);
          //$timeout(function() {
            element[0].focus();
            scope.trigger = false;
          //});
        }
      });
    }
  };
});

Plunker.

Since we need to reset the trigger/focusInput property in the directive, '=' is used for two-way databinding. In the first directive, '@' was sufficient. Also note that when using '@' we compare the trigger value to "true" since @ always results in a string.

Passing array in GET for a REST call

Instead of using http GET, use http POST. And JSON. Or XML

This is how your request stream to the server would look like.

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

{users: [user:{id:id1}, user:{id:id2}]}

Or in XML,

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

<users><user id='id1'/><user id='id2'/></users>

You could certainly continue using GET as you have proposed, as it is certainly simpler.

/appointments?users=1d1,1d2

Which means you would have to keep your data structures very simple.

However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.

Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.

JQuery

If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:

class bankaccount():
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def earn_money(self, amount):
        self.money += amount

    def withdraw_money(self, amount):
        self.money -= amount

    def show_balance(self):
        print self.money

Now you have an abstract model of a simple account and its mechanism. The def __init__(self, name, money) is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:

spidermans_account = bankaccount("SpiderMan", 1000)

If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw method on his account:

spidermans_account.withdraw_money(100)

If he wants to see the balance he calls:

spidermans_account.show_balance()

The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.

How do I check if I'm running on Windows in Python?

You should be able to rely on os.name.

import os
if os.name == 'nt':
    # ...

edit: Now I'd say the clearest way to do this is via the platform module, as per the other answer.

How to Make Laravel Eloquent "IN" Query?

Syntax:

$data = Model::whereIn('field_name', [1, 2, 3])->get();

Use for Users Model

$usersList = Users::whereIn('id', [1, 2, 3])->get();

How does Java handle integer underflows and overflows and how would you check for it?

I think you should use something like this and it is called Upcasting:

public int multiplyBy2(int x) throws ArithmeticException {
    long result = 2 * (long) x;    
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
        throw new ArithmeticException("Integer overflow");
    }
    return (int) result;
}

You can read further here: Detect or prevent integer overflow

It is quite reliable source.

What does 'x packages are looking for funding' mean when running `npm install`?

npm decided to add a new command: npm fund that will provide more visibility to npm users on what dependencies are actively looking for ways to fund their work.

npm install will also show a single message at the end in order to let user aware that dependencies are looking for funding, it looks like this:

$ npm install
packages are looking for funding.
run `npm fund` for details.

Running npm fund <package> will open the url listed for that given package right in your browser.

For more details look here

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

Pandas column of lists, create a row for each list element

I found the easiest way was to:

  1. Convert the samples column into a DataFrame
  2. Joining with the original df
  3. Melting

Shown here:

    df.samples.apply(lambda x: pd.Series(x)).join(df).\
melt(['subject','trial_num'],[0,1,2],var_name='sample')

        subject  trial_num sample  value
    0         1          1      0  -0.24
    1         1          2      0   0.14
    2         1          3      0  -0.67
    3         2          1      0  -1.52
    4         2          2      0  -0.00
    5         2          3      0  -1.73
    6         1          1      1  -0.70
    7         1          2      1  -0.70
    8         1          3      1  -0.29
    9         2          1      1  -0.70
    10        2          2      1  -0.72
    11        2          3      1   1.30
    12        1          1      2  -0.55
    13        1          2      2   0.10
    14        1          3      2  -0.44
    15        2          1      2   0.13
    16        2          2      2  -1.44
    17        2          3      2   0.73

It's worth noting that this may have only worked because each trial has the same number of samples (3). Something more clever may be necessary for trials of different sample sizes.

How to handle ETIMEDOUT error?

We could look at error object for a property code that mentions the possible system error and in cases of ETIMEDOUT where a network call fails, act accordingly.

if (err.code === 'ETIMEDOUT') {
    console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}

HTML colspan in CSS

column-span: all; /* W3C */
-webkit-column-span: all; /* Safari & Chrome */
-moz-column-span: all; /* Firefox */
-ms-column-span: all; /* Internet Explorer */
-o-column-span: all; /* Opera */

http://www.quackit.com/css/css3/properties/css_column-span.cfm

Background image jumps when address bar hides iOS/Android/Mobile Chrome

this is my solution to resolve this issue, i have added comments directly on code. I've tested this solution and works fine. Hope we will be useful for everyone has the same problem.

//remove height property from file css because we will set it to first run of page
//insert this snippet in a script after declarations of your scripts in your index

var setHeight = function() {    
  var h = $(window).height();   
  $('#bg1, #bg2').css('height', h);
};

setHeight(); // at first run of webpage we set css height with a fixed value

if(typeof window.orientation !== 'undefined') { // this is more smart to detect mobile devices because desktop doesn't support this property
  var query = window.matchMedia("(orientation:landscape)"); //this is is important to verify if we put 
  var changeHeight = function(query) {                      //mobile device in landscape mode
    if (query.matches) {                                    // if yes we set again height to occupy 100%
      setHeight(); // landscape mode
    } else {                                                //if we go back to portrait we set again
      setHeight(); // portrait mode
    }
  }
  query.addListener(changeHeight);                          //add a listner too this event
} 
else { //desktop mode                                       //this last part is only for non mobile
  $( window ).resize(function() {                           // so in this case we use resize to have
    setHeight();                                            // responsivity resisizing browser window
  }); 
};

Convert unix time to readable date in pandas dataframe

Alternatively, by changing a line of the above code:

# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))

It should also work.

What is code coverage and how do YOU measure it?

For PHP you should take a look at the Github from Sebastian Bergmann

Provides collection, processing, and rendering functionality for PHP code coverage information.

https://github.com/sebastianbergmann/php-code-coverage

Get docker container id from container name

Docker image inspect ImageName\ImageId --format={{'.ConatinerConfig.Hostname'}}

Git push error pre-receive hook declined

Please check if JIRA status in "In Development". For me , it was not , when i changed jira status to "In Development", it worked for me.

Package php5 have no installation candidate (Ubuntu 16.04)

Ubuntu 16.04 comes with PHP7 as the standard, so there are no PHP5 packages

However if you like you can add a PPA to get those packages anyways:

Remove all the stock php packages

List installed php packages with dpkg -l | grep php| awk '{print $2}' |tr "\n" " " then remove unneeded packages with sudo aptitude purge your_packages_here or if you want to directly remove them all use :

sudo aptitude purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`

Add the PPA

sudo add-apt-repository ppa:ondrej/php

Install your PHP Version

sudo apt-get update
sudo apt-get install php5.6

You can install php5.6 modules too ..

Verify your version

sudo php -v

Based on https://askubuntu.com/a/756186/532957 (thanks @AhmedJerbi)

Restrict SQL Server Login access to only one database

I think this is what we like to do very much.

--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;


-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello; 


 -- step 3 (then authorized the user for that specific database , you have to use the  master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO

If you already created a user and assigned to that database before by doing

USE [yourDB] 
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo] 
GO

then kindly delete it by doing below and follow the steps

   USE yourDB;
   GO
   DROP USER newlogin;
   GO

For more information please follow the links:

Hiding databases for a login on Microsoft Sql Server 2008R2 and above

Detect if the app was launched/opened from a push notification

IN SWIFT:

I'm running Push Notifications (with background fetching). When my app is in the background and I receive a push notification, I found that didReceiveRemoteNotification in appDelegate would be called twice; once for when notification is received and another when user clicks on the notification alert.

To detect if notification alert was clicked, just check if applicationState raw value == 1 inside didReceiveRemoteNotification in appDelegate.

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) {
    // If not from alert click applicationState(1)
    if (application.applicationState.rawValue != 1) {
        // Run your code here
    }
}

I hope this helps.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Import and insert sql.gz file into database with putty

If you've got many database it import and the dumps is big (I often work with multigigabyte Gzipped dumps).

There here a way to do it inside mysql.

$ mkdir databases
$ cd databases
$ scp user@orgin:*.sql.gz .  # Here you would just use putty to copy into this dir.
$ mkfifo src
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.5.41-0
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database db1;
mysql> \! ( zcat  db1.sql.gz > src & )
mysql> source src
.
.
mysql> create database db2;
mysql> \! ( zcat  db2.sql.gz > src & )
mysql> source src

The only advantage this has over

zcat db1.sql.gz | mysql -u root -p 

is that you can easily do multiple without enter the password lots of times.

Any reason to prefer getClass() over instanceof when generating .equals()?

This is something of a religious debate. Both approaches have their problems.

  • Use instanceof and you can never add significant members to subclasses.
  • Use getClass and you violate the Liskov substitution principle.

Bloch has another relevant piece of advice in Effective Java Second Edition:

  • Item 17: Design and document for inheritance or prohibit it

Windows Batch Files: if else

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

Different between parseInt() and valueOf() in java?

From this forum:

parseInt() returns primitive integer type (int), whereby valueOf returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.

Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.

Get to UIViewController from UIView?

Since this has been the accepted answer for a long time, I feel I need to rectify it with a better answer.

Some comments on the need:

  • Your view should not need to access the view controller directly.
  • The view should instead be independent of the view controller, and be able to work in different contexts.
  • Should you need the view to interface in a way with the view controller, the recommended way, and what Apple does across Cocoa is to use the delegate pattern.

An example of how to implement it follows:

@protocol MyViewDelegate < NSObject >

- (void)viewActionHappened;

@end

@interface MyView : UIView

@property (nonatomic, assign) MyViewDelegate delegate;

@end

@interface MyViewController < MyViewDelegate >

@end

The view interfaces with its delegate (as UITableView does, for instance) and it doesn't care if its implemented in the view controller or in any other class that you end up using.

My original answer follows: I don't recommend this, neither the rest of the answers where direct access to the view controller is achieved

There is no built-in way to do it. While you can get around it by adding a IBOutlet on the UIView and connecting these in Interface Builder, this is not recommended. The view should not know about the view controller. Instead, you should do as @Phil M suggests and create a protocol to be used as the delegate.

Calculating number of full months between two dates in SQL

Is not necesary to create the function only the @result part. For example:

Select Name,
(SELECT CASE WHEN 
DATEPART(DAY, '2016-08-28') > DATEPART(DAY, '2016-09-29')   
THEN DATEDIFF(MONTH, '2016-08-28',  '2016-09-29') - 1
ELSE DATEDIFF(MONTH, '2016-08-28',  '2016-09-29') END) as NumberOfMonths

FROM 
tableExample;

Simulate a specific CURL in PostMan

I tried the approach mentioned by Onkaar Singh,

  1. Open POSTMAN
  2. Click on "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!

But the problem is it didn't work for the Apis which requires authorisation.

This was my curl request:

curl -v -H "Accept: application/json" -H "Content-type:
application/json" -X POST -d ' 
{"customer_id":"812122", "event":"add_to_cart", "email": "[email protected]", }' 
-u 9f4d7f5445e7: https://api.myapp.com/api/event

After importing the body got imported correctly, the headers and the Url also got imported. Only the api key 9f4d7f5445e7 which is

-u 9f4d7f5445e7: https://api.myapp.com/api/v1/event 

in the curl request did not import.

The way I solved it is, -u is basically used for Authorization. So while using it in Postman, you have to take the API key (which is 9f4d7f5445e7 in this case) and do Base64 Encode. Once encoded it will return the value OWY0ZDdmNTQ0NWU3. Then add a new header, the key name would be Authorization and key value would be Basic OWY0ZDdmNTQ0NWU3. After making that changes, the request worked for me.

There are online Base64 Encoders available, the one I used is http://www.url-encode-decode.com/base64-encode-decode/

Hope it helps!!!

Bootstrap carousel width and height

I found that if you just want to change the height of the element the image takes up, this will be the code that will help

.carousel-item { height: 600px !important; }

however, this won't make the size of the image dynamic, it will simply crop the image to its size.

The transaction manager has disabled its support for remote/network transactions

I was getting this issue intermittently, I had followed the instructions here and very similar ones elsewhere. All was configured correctly.

This page: http://sysadminwebsite.wordpress.com/2012/05/29/9/ helped me find the problem.

Basically I had duplicate CID's for the MSDTC across both servers. HKEY_CLASSES_ROOT\CID

See: http://msdn.microsoft.com/en-us/library/aa561924.aspx section Ensure that MSDTC is assigned a unique CID value

I am working with virtual servers and our server team likes to use the same image for every server. It's a simple fix and we didn't need a restart. But the DTC service did need setting to Automatic startup and did need to be started after the re-install.

How to create a hash or dictionary object in JavaScript

Don't use an array if you want named keys, use a plain object.

var a = {};
a["key1"] = "value1";
a["key2"] = "value2";

Then:

if ("key1" in a) {
   // something
} else {
   // something else 
}

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

What is the difference between C and embedded C?

C is a only programming language its used in system programming. but embedded C is used to implement the projects like real time applications

How do I change the string representation of a Python class?

The closest equivalent to Java's toString is to implement __str__ for your class. Put this in your class definition:

def __str__(self):
     return "foo"

You may also want to implement __repr__ to aid in debugging.

See here for more information:

Node.js fs.readdir recursive directory search

For Node 10.3+, here is a for-await solution:

#!/usr/bin/env node

const FS = require('fs');
const Util = require('util');
const readDir = Util.promisify(FS.readdir);
const Path = require('path');

async function* readDirR(path) {
    const entries = await readDir(path,{withFileTypes:true});
    for(let entry of entries) {
        const fullPath = Path.join(path,entry.name);
        if(entry.isDirectory()) {
            yield* readDirR(fullPath);
        } else {
            yield fullPath;
        }
    }
}

async function main() {
    const start = process.hrtime.bigint();
    for await(const file of readDirR('/mnt/home/media/Unsorted')) {
        console.log(file);
    }
    console.log((process.hrtime.bigint()-start)/1000000n);
}

main().catch(err => {
    console.error(err);
});

The benefit of this solution is that you can start processing the results immediately; e.g. it takes 12 seconds to read all the files in my media directory, but if I do it this way I can get the first result within a few milliseconds.

Set initial value in datepicker with jquery?

I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.

If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.

Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.

<script>
    $(document).ready(function () {
        $('#DateChanger').click(function() {
             $('#dtFrom').val("2012-12-22");
        });
    });
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>

Remember to include JQuery reference.

How do I list all files of a directory?

Another very readable variant for Python 3.4+ is using pathlib.Path.glob:

from pathlib import Path
folder = '/foo'
[f for f in Path(folder).glob('*') if f.is_file()]

It is simple to make more specific, e.g. only look for Python source files which are not symbolic links, also in all subdirectories:

[f for f in Path(folder).glob('**/*.py') if not f.is_symlink()]

Import Excel spreadsheet columns into SQL Server database

The import wizard does offer that option. You can either use the option to write your own query for the data to import, or you can use the copy data option and use the "Edit Mappings" button to ignore columns you do not want to import.

How to install pip with Python 3?

pip is installed together when you install Python. You can use sudo pip install (module) or python3 -m pip install (module).

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

Select query to get data from SQL Server

you can use ExecuteScalar() in place of ExecuteNonQuery() to get a single result use it like this

Int32 result= (Int32) command.ExecuteScalar();
Console.WriteLine(String.Format("{0}", result));

It will execute the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

As you want only one row in return, remove this use of SqlDataReader from your code

using (SqlDataReader reader = command.ExecuteReader())
{
    // iterate your results here
    Console.WriteLine(String.Format("{0}",reader["id"]));
}

because it will again execute your command and effect your page performance.

Runtime vs. Compile time

Compile Time:

Things that are done at compile time incur (almost) no cost when the resulting program is run, but might incur a large cost when you build the program. Run-Time:

More or less the exact opposite. Little cost when you build, more cost when the program is run.

From the other side; If something is done at compile time, it runs only on your machine and if something is run-time, it run on your users machine.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

I don't think so. I wanted this the other day. The closest I got was:

SELECT
  o.OrderId,
  CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN o.NegotiatedPrice 
     ELSE o.SuggestedPrice
  END
FROM Order o

This compilation unit is not on the build path of a Java project

If your project is imported as an existing maven project then --> Just right click on project and do maven update. It resolved my similar issue.

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I too encountered this issue while auto inserting a sysdate to a column.

What I did is I changed my system date format to match with SQL server's date format. e.g. my SQL format was mm/dd/yyyy and my system format was set to dd/mm/yyyy. I changed my system format to mm/dd/yyyy and error gone

-kb

Getting value of select (dropdown) before change

This is an improvement on @thisisboris answer. It adds a current value to data, so the code can control when a variable set to the current value is changed.

(function()
{
    // Initialize the previous-attribute
    var selects = $( 'select' );
    $.each( selects, function( index, myValue ) {
        $( myValue ).data( 'mgc-previous', myValue.value );
        $( myValue ).data( 'mgc-current', myValue.value );  
    });

    // Listen on the body for changes to selects
    $('body').on('change', 'select',
        function()
        {
            alert('I am a body alert');
            $(this).data('mgc-previous', $(this).data( 'mgc-current' ) );
            $(this).data('mgc-current', $(this).val() );
        }
    );
})();

find the array index of an object with a specific key value in underscore

Array.prototype.getIndex = function (obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][Id] == obj.Id) {
            return i;
        }
    }
    return -1;
}

List.getIndex(obj);

Align an element to bottom with flexbox

The solution with align-self: flex-end; didn't work for me but this one did in case you want to use flex:

Result

 -------------------
|heading 1          |
|heading 2          | 
|paragraph text     |
|                   |
|                   |
|                   | 
|link button        |
 -------------------

Code

Note: When "running the code snippet" you have to scroll down to see the link at the bottom.

_x000D_
_x000D_
.content {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-direction: column;_x000D_
  height: 300px;_x000D_
}_x000D_
_x000D_
.content .upper {_x000D_
  justify-content: normal;_x000D_
}_x000D_
_x000D_
/* Just to show container boundaries */_x000D_
.content .upper, .content .bottom, .content .upper > * {_x000D_
  border: 1px solid #ccc;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="upper">_x000D_
   <h1>heading 1</h1>_x000D_
   <h2>heading 2</h2>_x000D_
   <p>paragraph text</p>_x000D_
  </div>_x000D_
_x000D_
  <div class="bottom">_x000D_
   <a href="/" class="button">link button</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

npm ERR cb() never called

Try

sudo npm cache clean --force

More info refer: https://reactgo.com/npm-err-cb-never-called/

How to compare two Dates without the time portion?

My preference would be to use the Joda library insetad of java.util.Date directly, as Joda makes a distinction between date and time (see YearMonthDay and DateTime classes).

However, if you do wish to use java.util.Date I would suggest writing a utility method; e.g.

public static Date setTimeToMidnight(Date date) {
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( date );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

Printing leading 0's in C

There are 2 ways to output your number with leading zeroes:

Using the 0 flag and the width specifier:

int zipcode = 123;
printf("%05d\n", zipcode);  // outputs 00123

Using the precision specifier:

int zipcode = 123;
printf("%.5d\n", zipcode);  // outputs 00123

The difference between these is the handling of negative numbers:

printf("%05d\n", -123);  // outputs -0123 (pad to 5 characters)
printf("%.5d\n", -123);  // outputs -00123 (pad to 5 digits)

Zip codes are unlikely to be negative, so it should not matter.

Note however that zip codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.

Note that in both examples above, the 5 width or precision values can be specified as an int argument:

int width = 5;
printf("%0*d\n", width, 123);  // outputs 00123
printf("%.*d\n", width, 123);  // outputs 00123

There is one more trick to know: a precision of 0 causes no output for the value 0:

printf("|%0d|%0d|\n", 0, 1);  // outputs |0|1|
printf("|%.0d|%.0d|\n", 0, 1);  // outputs ||1|

How do I remove leading whitespace in Python?

The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:

s = """
    line 1 has 4 leading spaces
    line 2 has 4 leading spaces
    line 3 has 4 leading spaces
"""

if we print(s) we would get output like:

>>> print(s)
    this has 4 leading spaces 1
    this has 4 leading spaces 2
    this has 4 leading spaces 3

and if we used textwrap.dedent:

>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3

IIS w3svc error

Run cmd as administrator. Type iisreset. That's it.

Get all photos from Instagram which have a specific hashtag with PHP

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}

Reloading/refreshing Kendo Grid

In order to do a complete refresh, where the grid will be re-rendered alongwith new read request, you can do the following:

 Grid.setOptions({
      property: true/false
    });

Where property can be any property e.g. sortable

How to get Selected Text from select2 when using <input>

Also you can have the selected value using following code:

alert("Selected option value is: "+$('#SelectelementId').select2("val"));

Url.Action parameters?

you can returns a private collection named HttpValueCollection even the documentation says it's a NameValueCollection using the ParseQueryString utility. Then add the keys manually, HttpValueCollection do the encoding for you. And then just append the QueryString manually :

var qs = HttpUtility.ParseQueryString(""); 
qs.Add("name", "John")
qs.Add("contact", "calgary");
qs.Add("contact", "vancouver")

<a href="<%: Url.Action("GetByList", "Listing")%>?<%:qs%>">
    <span>People</span>
</a>

How can I create a copy of an Oracle table without copying the data?

you can also do a

create table abc_new as select * from abc; 

then truncate the table abc_new. Hope this will suffice your requirement.

pythonw.exe or python.exe?

To summarize and complement the existing answers:

  • python.exe is a console (terminal) application for launching CLI-type scripts.

    • Unless run from an existing console window, python.exe opens a new console window.
    • Standard streams sys.stdin, sys.stdout and sys.stderr are connected to the console window.
    • Execution is synchronous when launched from a cmd.exe or PowerShell console window: See eryksun's 1st comment below.

      • If a new console window was created, it stays open until the script terminates.
      • When invoked from an existing console window, the prompt is blocked until the script terminates.
  • pythonw.exe is a GUI app for launching GUI/no-UI-at-all scripts.

    • NO console window is opened.
    • Execution is asynchronous:
      • When invoked from a console window, the script is merely launched and the prompt returns right away, whether the script is still running or not.
    • Standard streams sys.stdin, sys.stdout and sys.stderr are NOT available.
      • Caution: Unless you take extra steps, this has potentially unexpected side effects:
        • Unhandled exceptions cause the script to abort silently.
        • In Python 2.x, simply trying to use print() can cause that to happen (in 3.x, print() simply has no effect).
        • To prevent that from within your script, and to learn more, see this answer of mine.
        • Ad-hoc, you can use output redirection:Thanks, @handle.
          pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt
          (from PowerShell:
          cmd /c pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt) to capture stdout and stderr output in files.
          If you're confident that use of print() is the only reason your script fails silently with pythonw.exe, and you're not interested in stdout output, use @handle's command from the comments:
          pythonw.exe yourScript.pyw 1>NUL 2>&1
          Caveat: This output redirection technique does not work when invoking *.pyw scripts directly (as opposed to by passing the script file path to pythonw.exe). See eryksun's 2nd comment and its follow-ups below.

You can control which of the executables runs your script by default - such as when opened from Explorer - by choosing the right filename extension:

  • *.py files are by default associated (invoked) with python.exe
  • *.pyw files are by default associated (invoked) with pythonw.exe

Random alpha-numeric string in JavaScript?

Use md5 library: https://github.com/blueimp/JavaScript-MD5

The shortest way:

md5(Math.random())

If you want to limit the size to 5:

md5(Math.random()).substr(0, 5)

How to do a batch insert in MySQL

Load data infile query is much better option but some servers like godaddy restrict this option on shared hosting so , only two options left then one is insert record on every iteration or batch insert , but batch insert has its limitaion of characters if your query exceeds this number of characters set in mysql then your query will crash , So I suggest insert data in chunks withs batch insert , this will minimize number of connections established with database.best of luck guys

git rm - fatal: pathspec did not match any files

I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web while inside the first web folder.

in a "using" block is a SqlConnection closed on return or exception?

I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.

     try
     {
       using (var con = new SqlConnection(@"Data Source=..."))
       {
         var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";

         using (var insertCommand = new SqlCommand(cad, con))
         {
           insertCommand.Parameters.AddWithValue("@r1", atxt);
           insertCommand.Parameters.AddWithValue("@r2", btxt);
           insertCommand.Parameters.AddWithValue("@r3", ctxt);
           con.Open();
           insertCommand.ExecuteNonQuery();
         }
       }
     }
     catch (Exception ex)
     {
       MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

No matter where's the try/catch placed, the exception will be caught without issues.

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

What svn command would list all the files modified on a branch?

You can also get a quick list of changed files if thats all you're looking for using the status command with the -u option

svn status -u

This will show you what revision the file is in the current code base versus the latest revision in the repository. I only use diff when I actually want to see differences in the files themselves.

There is a good tutorial on svn command here that explains a lot of these common scenarios: SVN Command Reference

How to convert UTF8 string to byte array?

The Google Closure library has functions to convert to/from UTF-8 and byte arrays. If you don't want to use the whole library, you can copy the functions from here. For completeness, the code to convert to a string to a UTF-8 byte array is:

goog.crypt.stringToUtf8ByteArray = function(str) {
  // TODO(user): Use native implementations if/when available
  var out = [], p = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    if (c < 128) {
      out[p++] = c;
    } else if (c < 2048) {
      out[p++] = (c >> 6) | 192;
      out[p++] = (c & 63) | 128;
    } else if (
        ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
        ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
      // Surrogate Pair
      c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
      out[p++] = (c >> 18) | 240;
      out[p++] = ((c >> 12) & 63) | 128;
      out[p++] = ((c >> 6) & 63) | 128;
      out[p++] = (c & 63) | 128;
    } else {
      out[p++] = (c >> 12) | 224;
      out[p++] = ((c >> 6) & 63) | 128;
      out[p++] = (c & 63) | 128;
    }
  }
  return out;
};

Get the last insert id with doctrine 2?

Here i post my code, after i have pushed myself for one working day to find this solution.

Function to get the last saved record :

private function getLastId($query) {
        $conn = $this->getDoctrine()->getConnection();
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $lastId = $stmt->fetch()['id'];
        return $lastId;
    }

Another Function which call the above function

private function clientNum() {
        $lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
        $noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
        return $noClient;
    }

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

What is the meaning of polyfills in HTML5?

Here are some high level thoughts and info that might help, aside from the other answers.

Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.

It kind of depends on the requirements of what your app/website needs to be compatible with.

You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/

Getting value of HTML Checkbox from onclick/onchange events

Use this

<input type="checkbox" onclick="onClickHandler()" id="box" />

<script>
function onClickHandler(){
    var chk=document.getElementById("box").value;

    //use this value

}
</script>

How to get distinct values from an array of objects in JavaScript?

Here's another way to solve this:

var result = {};
for(var i in array) {
    result[array[i].age] = null;
}
result = Object.keys(result);

I have no idea how fast this solution is compared to the others, but I like the cleaner look. ;-)


EDIT: Okay, the above seems to be the slowest solution of all here.

I've created a performance test case here: http://jsperf.com/distinct-values-from-array

Instead of testing for the ages (Integers), I chose to compare the names (Strings).

Method 1 (TS's solution) is very fast. Interestingly enough, Method 7 outperforms all other solutions, here I just got rid of .indexOf() and used a "manual" implementation of it, avoiding looped function calling:

var result = [];
loop1: for (var i = 0; i < array.length; i++) {
    var name = array[i].name;
    for (var i2 = 0; i2 < result.length; i2++) {
        if (result[i2] == name) {
            continue loop1;
        }
    }
    result.push(name);
}

The difference in performance using Safari & Firefox is amazing, and it seems like Chrome does the best job on optimization.

I'm not exactly sure why the above snippets is so fast compared to the others, maybe someone wiser than me has an answer. ;-)

How to use LocalBroadcastManager?

When you'll play enough with LocalBroadcastReceiver I'll suggest you to give Green Robot's EventBus a try - you will definitely realize the difference and usefulness of it compared to LBR. Less code, customizable about receiver's thread (UI/Bg), checking receivers availability, sticky events, events could be used as data delivery etc.

How to create a byte array in C++?

Byte is not a standard type in C/C++, so it is represented by char.

An advantage of this is that you can treat a basic_string as a byte array allowing for safe storage and function passing. This will help you avoid the memory leaks and segmentation faults you might encounter when using the various forms of char[] and char*.

For example, this creates a string as a byte array of null values:

typedef basic_string<unsigned char> u_string;

u_string bytes = u_string(16,'\0');

This allows for standard bitwise operations with other char values, including those stored in other string variables. For example, to XOR the char values of another u_string across bytes:

u_string otherBytes = "some more chars, which are just bytes";
for(int i = 0; i < otherBytes.length(); i++)
    bytes[i%16] ^= (int)otherBytes[i];

SQL Query to add a new column after an existing column in SQL Server 2005

If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.

Error: Cannot invoke an expression whose type lacks a call signature

The function that it returns has a call signature, but you told Typescript to completely ignore that by adding : any in its signature.

Convert HashBytes to VarChar

convert(varchar(34), HASHBYTES('MD5','Hello World'),1)

(1 for converting hexadecimal to string)

convert this to lower and remove 0x from the start of the string by substring:

substring(lower(convert(varchar(34), HASHBYTES('MD5','Hello World'),1)),3,32)

exactly the same as what we get in C# after converting bytes to string

How to disable Hyper-V in command line?

I tried all of stack overflow and all didn't works. But this works for me:

  1. Open System Configuration
  2. Click Service tab
  3. Uncheck all of Hyper-V related

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

Android - Launcher Icon Size

According to the Material design guidelines (here, under "DP unit grid"), your product icon should be of size 48 dp, with a padding of 1dp, except for the case of XXXHDPI, where the padding should be 4dp.

So, in pixels, the sizes are:

  • 48 × 48 (mdpi) , with 1 dp padding
  • 72 × 72 (hdpi), with 1 dp padding
  • 96 × 96 (xhdpi), with 1 dp padding
  • 144 × 144 (xxhdpi), with 1 dp padding
  • 192 × 192 (xxxhdpi) , with 4 dp padding

I recommend to avoid using VectorDrawable as some launchers don't support it, but I think WEBP should be ok as long as you have your minSdk support transparency for them (API 18 and above - Android 4.3).

If you publish on the Play Store, the requirement to what to upload there are (based on here) :

  • 32-bit PNG (with alpha)
  • Dimensions: 512px by 512px
  • Maximum file size: 1024KB

How and where are Annotations used in Java?

Following are some of the places where you can use annotations.

a. Annotations can be used by compiler to detect errors and suppress warnings
b. Software tools can use annotations to generate code, xml files, documentation etc., For example, Javadoc use annotations while generating java documentation for your class.
c. Runtime processing of the application can be possible via annotations.
d. You can use annotations to describe the constraints (Ex: @Null, @NotNull, @Max, @Min, @Email).
e. Annotations can be used to describe type of an element. Ex: @Entity, @Repository, @Service, @Controller, @RestController, @Resource etc.,
f. Annotation can be used to specify the behaviour. Ex: @Transactional, @Stateful
g. Annotation are used to specify how to process an element. Ex: @Column, @Embeddable, @EmbeddedId
h. Test frameworks like junit and testing use annotations to define test cases (@Test), define test suites (@Suite) etc.,
i. AOP (Aspect Oriented programming) use annotations (@Before, @After, @Around etc.,)
j. ORM tools like Hibernate, Eclipselink use annotations

You can refer this link for more details on annotations.

You can refer this link to see how annotations are used to build simple test suite.

Git diff against a stash

Just in case, to compare a file in the working tree and in the stash, use the below command

git diff stash@{0} -- fileName (with path)

PHP - Debugging Curl

Here is an even simplier way, by writing directly to php error output

curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, fopen('php://stderr', 'w'));

How do you follow an HTTP Redirect in Node.js?

If all you want to do is follow redirects but still want to use the built-in HTTP and HTTPS modules, I suggest you use https://github.com/follow-redirects/follow-redirects.

yarn add follow-redirects
npm install follow-redirects

All you need to do is replace:

var http = require('http');

with

var http = require('follow-redirects').http;

... and all your requests will automatically follow redirects.

With TypeScript you can also install the types

npm install @types/follow-redirects

and then use

import { http, https } from 'follow-redirects';

Disclosure: I wrote this module.

How to delete Tkinter widgets from a window?

Today I learn some simple and good click event handling using tkinter gui library in python3, which I would like to share inside this thread.

from tkinter import *

cnt = 0


def MsgClick(event):
    children = root.winfo_children()
    for child in children:
        # print("type of widget is : " + str(type(child)))
        if str(type(child)) == "<class 'tkinter.Message'>":
            # print("Here Message widget will destroy")
            child.destroy()
            return

def MsgMotion(event):
  print("Mouse position: (%s %s)" % (event.x, event.y))
  return


def ButtonClick(event):
    global cnt, msg
    cnt += 1
    msg = Message(root, text="you just clicked the button..." + str(cnt) + "...time...")
    msg.config(bg='lightgreen', font=('times', 24, 'italic'))
    msg.bind("<Button-1>", MsgClick)
    msg.bind("<Motion>", MsgMotion)
    msg.pack()
    #print(type(msg)) tkinter.Message


def ButtonDoubleClick(event):
    import sys; sys.exit()


root = Tk()

root.title("My First GUI App in Python")
root.minsize(width=300, height=300)
root.maxsize(width=400, height=350)
button = Button(
    root, text="Click Me!", width=40, height=3
)
button.pack()
button.bind("<Button-1>", ButtonClick)
button.bind("<Double-1>", ButtonDoubleClick)

root.mainloop()

Hope it will help someone...

Gunicorn worker timeout error

On Google Cloud Just add --timeout 90 to entrypoint in app.yaml

entrypoint: gunicorn -b :$PORT main:app --timeout 90

Sql select rows containing part of string

You can use the LIKE operator to compare the content of a T-SQL string, e.g.

SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.

The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".

cordova Android requirements failed: "Could not find an installed version of Gradle"

Perhaps you installed the latest Android Studio 2.3.1, it changed command android list targets to avdmanager list targets, so there is how to fix it:

add path <android-sdk>/tools/bin to PATH, this is for MacOX.

export PATH="$PATH:/Users/<username>/Library/Android/sdk/tools/bin"

change your cordova project code <your-cordova-project>/platforms/android/cordova/lib/android_sdk.js.

change

module.exports.list_targets_with_android = function() {
    return superspawn.spawn('android', ['list', 'targets'])

to

module.exports.list_targets_with_android = function() {
    return superspawn.spawn('avdmanager', ['list', 'targets'])

When should you NOT use a Rules Engine?

I get very nervous when I see people using very large rule sets (e.g., on the order of thousands of rules in a single rule set). This often happens when the rules engine is a singleton sitting in the center of the enterprise in the hope that keeping rules DRY will make them accessible to many apps that require them. I would defy anyone to tell me that a Rete rules engine with that many rules is well-understood. I'm not aware of any tools that can check to ensure that conflicts don't exist.

I think partitioning rules sets to keep them small is a better option. Aspects can be a way to share a common rule set among many objects.

I prefer a simpler, more data driven approach wherever possible.

How to return a value from __init__ in Python?

init() return none value solved perfectly

class Solve:
def __init__(self,w,d):
    self.value=w
    self.unit=d
def __str__(self):
    return str("my speed is "+str(self.value)+" "+str(self.unit))
ob=Solve(21,'kmh')
print (ob)

output: my speed is 21 kmh

PHP/MySQL insert row then get 'id'

As @NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.

// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been 
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);

Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php

How do I change db schema to dbo

I just posted this to a similar question: In sql server 2005, how do I change the "schema" of a table without losing any data?


A slight improvement to sAeid's excellent answer...

I added an exec to have this code self-execute, and I added a union at the top so that I could change the schema of both tables AND stored procedures:

DECLARE cursore CURSOR FOR 


select specific_schema as 'schema', specific_name AS 'name'
FROM INFORMATION_SCHEMA.routines
WHERE specific_schema <> 'dbo' 

UNION ALL

SELECT TABLE_SCHEMA AS 'schema', TABLE_NAME AS 'name'
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA <> 'dbo' 



DECLARE @schema sysname, 
 @tab sysname, 
 @sql varchar(500) 


OPEN cursore     
FETCH NEXT FROM cursore INTO @schema, @tab 

WHILE @@FETCH_STATUS = 0     
BEGIN 
 SET @sql = 'ALTER SCHEMA dbo TRANSFER [' + @schema + '].[' + @tab +']'    
 PRINT @sql   
 exec (@sql)  
 FETCH NEXT FROM cursore INTO @schema, @tab     
END 

CLOSE cursore     
DEALLOCATE cursore

I too had to restore a dbdump, and found that the schema wasn't dbo - I spent hours trying to get Sql Server management studio or visual studio data transfers to alter the destination schema... I ended up just running this against the restored dump on the new server to get things the way I wanted.

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

How to get the query string by javascript?

There is a new API called URLSearchParams in browsers which allow you to extract and change the values of the query string.

Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.

Initialize/Input

To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1) on the querystring, as Jake Archibald suggests:

var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12

In later implementations, you should be able to use it without slice:

var params = new URLSearchParams(window.location.search); // myParam=12

Get

You can get params from it via the .get method:

params.get('myParam'); // 12

Set

Params can be changed using .set:

params.set('myParam', 'newValue');

Output

And if the current querystring is needed again, the .toString method provides it:

params.toString(); // myParam=newValue

There are a host of other methods in this API.

Polyfill

As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

Search for string within text column in MySQL

Using like might take longer time so use full_text_search:

SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')

importing jar libraries into android-studio

I also faced same obstacle but not able to find out solution from given answers. Might be it's happening due to project path which is having special characters & space etc... So please try to add this line in your build.gradle.

compile files('../app/libs/jtwitter.jar')// pass your .jar file name

".." (Double dot) will find your root directory of your project.

Spark Dataframe distinguish columns with duplicated name

If you have a more complicated use case than described in the answer of Glennie Helles Sindholt e.g. you have other/few non-join column names that are also same and want to distinguish them while selecting it's best to use aliasses, e.g:

df3 = df1.select("a", "b").alias("left")\
   .join(df2.select("a", "b").alias("right"), ["a"])\
   .select("left.a", "left.b", "right.b")

df3.columns
['a', 'b', 'b']

CSS Background Opacity

This is because the inner div has 100% of the opacity of the div it is nested in (which has 40% opacity).

In order to circumvent it, there are a few things you could do.

You could create two separate divs like so:

<div id="background"></div>
<div id="bContent"></div>

Set your desired CSS opacity and other properties for the background and use the z-index property (z-index) to style and position the bContent div. With this you can place the div overtope of the background div without having it's opacity mucked with.


Another option is to RGBa. This will allow you to nest your divs and still achieve div specific opacity.


The last option is to simply make a semi transparent .png image of the color you want in your desired image editor of choice, set the background-image property to the URL of the image and then you won't have to worry about mucking about with the CSS and losing the capability and organization of a nested div structure.

Computational complexity of Fibonacci Sequence

Recursive algorithm's time complexity can be better estimated by drawing recursion tree, In this case the recurrence relation for drawing recursion tree would be T(n)=T(n-1)+T(n-2)+O(1) note that each step takes O(1) meaning constant time,since it does only one comparison to check value of n in if block.Recursion tree would look like

          n
   (n-1)      (n-2)
(n-2)(n-3) (n-3)(n-4) ...so on

Here lets say each level of above tree is denoted by i hence,

i
0                        n
1            (n-1)                 (n-2)
2        (n-2)    (n-3)      (n-3)     (n-4)
3   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)

lets say at particular value of i, the tree ends, that case would be when n-i=1, hence i=n-1, meaning that the height of the tree is n-1. Now lets see how much work is done for each of n layers in tree.Note that each step takes O(1) time as stated in recurrence relation.

2^0=1                        n
2^1=2            (n-1)                 (n-2)
2^2=4        (n-2)    (n-3)      (n-3)     (n-4)
2^3=8   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)    ..so on
2^i for ith level

since i=n-1 is height of the tree work done at each level will be

i work
1 2^1
2 2^2
3 2^3..so on

Hence total work done will sum of work done at each level, hence it will be 2^0+2^1+2^2+2^3...+2^(n-1) since i=n-1. By geometric series this sum is 2^n, Hence total time complexity here is O(2^n)

C# List of objects, how do I get the sum of a property

using System.Linq;

...

double total = myList.Sum(item => item.Amount);

How can I download a specific Maven artifact in one command line?

You could use the maven dependency plugin which has a nice dependency:get goal since version 2.1. No need for a pom, everything happens on the command line.

To make sure to find the dependency:get goal, you need to explicitly tell maven to use the version 2.1, i.e. you need to use the fully qualified name of the plugin, including the version:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=url \
    -Dartifact=groupId:artifactId:version

UPDATE: With older versions of Maven (prior to 2.1), it is possible to run dependency:get normally (without using the fully qualified name and version) by forcing your copy of maven to use a given version of a plugin.

This can be done as follows:

1. Add the following line within the <settings> element of your ~/.m2/settings.xml file:

<usePluginRegistry>true</usePluginRegistry>

2. Add the file ~/.m2/plugin-registry.xml with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<pluginRegistry xsi:schemaLocation="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0 http://maven.apache.org/xsd/plugin-registry-1.0.0.xsd"
xmlns="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <useVersion>2.1</useVersion>
      <rejectedVersions/>
    </plugin>
  </plugins>
</pluginRegistry>

But this doesn't seem to work anymore with maven 2.1/2.2. Actually, according to the Introduction to the Plugin Registry, features of the plugin-registry.xml have been redesigned (for portability) and the plugin registry is currently in a semi-dormant state within Maven 2. So I think we have to use the long name for now (when using the plugin without a pom, which is the idea behind dependency:get).

When should I write the keyword 'inline' for a function/method?

I'd like to contribute to all of the great answers in this thread with a convincing example to disperse any remaining misunderstanding.

Given two source files, such as:

  • inline111.cpp:

    #include <iostream>
    
    void bar();
    
    inline int fun() {
      return 111;
    }
    
    int main() {
      std::cout << "inline111: fun() = " << fun() << ", &fun = " << (void*) &fun;
      bar();
    }
    
  • inline222.cpp:

    #include <iostream>
    
    inline int fun() {
      return 222;
    }
    
    void bar() {
      std::cout << "inline222: fun() = " << fun() << ", &fun = " << (void*) &fun;
    }
    

  • Case A:

    Compile:

    g++ -std=c++11 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x4029a0
    inline222: fun() = 111, &fun = 0x4029a0
    

    Discussion:

    1. Even thou you ought to have identical definitions of your inline functions, C++ compiler does not flag it if that is not the case (actually, due to separate compilation it has no ways to check it). It is your own duty to ensure this!

    2. Linker does not complain about One Definition Rule, as fun() is declared as inline. However, because inline111.cpp is the first translation unit (which actually calls fun()) processed by compiler, the compiler instantiates fun() upon its first call-encounter in inline111.cpp. If compiler decides not to expand fun() upon its call from anywhere else in your program (e.g. from inline222.cpp), the call to fun() will always be linked to its instance produced from inline111.cpp (the call to fun() inside inline222.cpp may also produce an instance in that translation unit, but it will remain unlinked). Indeed, that is evident from the identical &fun = 0x4029a0 print-outs.

    3. Finally, despite the inline suggestion to the compiler to actually expand the one-liner fun(), it ignores your suggestion completely, which is clear because fun() = 111 in both of the lines.


  • Case B:

    Compile (notice reverse order):

    g++ -std=c++11 inline222.cpp inline111.cpp
    

    Output:

    inline111: fun() = 222, &fun = 0x402980
    inline222: fun() = 222, &fun = 0x402980
    

    Discussion:

    1. This case asserts what have been discussed in Case A.

    2. Notice an important point, that if you comment out the actual call to fun() in inline222.cpp (e.g. comment out cout-statement in inline222.cpp completely) then, despite the compilation order of your translation units, fun() will be instantiated upon it's first call encounter in inline111.cpp, resulting in print-out for Case B as inline111: fun() = 111, &fun = 0x402980.


  • Case C:

    Compile (notice -O2):

    g++ -std=c++11 -O2 inline222.cpp inline111.cpp
    

    or

    g++ -std=c++11 -O2 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x402900
    inline222: fun() = 222, &fun = 0x402900
    

    Discussion:

    1. As is described here, -O2 optimization encourages compiler to actually expand the functions that can be inlined (Notice also that -fno-inline is default without optimization options). As is evident from the outprint here, the fun() has actually been inline expanded (according to its definition in that particular translation unit), resulting in two different fun() print-outs. Despite this, there is still only one globally linked instance of fun() (as required by the standard), as is evident from identical &fun print-out.

How can I check what version/edition of Visual Studio is installed programmatically?

Open the installed visual studio software and click the Help menu select the About Microsoft Visual studio--> Get the visual studio Version

How do I zip two arrays in JavaScript?

Zip Arrays of same length:

Using Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
_x000D_
_x000D_

Zip Arrays of different length:

Using Array.from()

_x000D_
_x000D_
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
_x000D_
_x000D_

Using Array.prototype.fill() and Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
_x000D_
_x000D_

How to add fonts to create-react-app based projects?

Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

or

<style>
    @import url('https://fonts.googleapis.com/css?family=Roboto');
</style>

How to print binary tree diagram?

I wrote a binary tree printer in Java.

Code is on GitHub here.

It hasn't been optimized for run time efficiency, but since we're talking about printing in ASCII, I figured it's not going to be used on very large trees. It does have some nice features though.

  1. It makes efficient use of space in that a large subtree extends under a smaller one as much as possible.
  2. There's a parameter to set the minimum horizontal space between node labels.
  3. Node labels are strings of arbitrary length.
  4. In addition to a method for printing a single tree, there's a method for printing a list of trees horizontally across the page (with a parameter for page width), using as many rows as necessary.
  5. There's an option to print trees with diagonal branches (using slash and backslash characters) or with horizontal branches (using ascii box drawing characters). The latter is more compact and makes tree levels more visually clear.
  6. It works.

Some demo/test programs are included.

An example of a randomly generated binary tree, as printed by the program, follows. This illustrates the efficient use of space, with a large right subtree extending under a small left subtree:

             seven                                        
              / \                                         
             /   \                                        
            /     \                                       
           /       \                                      
          /         \                                     
         /           \                                    
       five        thirteen                               
       / \           / \                                  
      /   \         /   \                                 
     /     \       /     \                                
  three    six    /       \                               
   / \           /         \                              
  /   \         /           \                             
one   four     /             \                            
  \           /               \                           
  two        /                 \                          
           nine            twenty four                    
           / \                 / \                        
          /   \               /   \                       
         /     \             /     \                      
      eight   twelve        /       \                     
               /           /         \                    
             ten          /           \                   
               \         /             \                  
              eleven    /               \                 
                       /                 \                
                      /                   \               
                     /                     \              
                 eighteen              twenty seven       
                   / \                     / \            
                  /   \                   /   \           
                 /     \                 /     \          
                /       \               /       \         
               /         \             /         \        
              /           \           /           \       
             /             \    twenty five   twenty eight
            /               \         \             \     
           /                 \     twenty six      thirty 
       fourteen            nineteen                 /     
           \                   \              twenty nine 
         sixteen           twenty three                   
           / \                 /                          
          /   \           twenty two                      
         /     \             /                            
        /       \         twenty                          
       /         \           \                            
   fifteen    seventeen   twenty one                      

An example of printing all five node binary trees (with in-order labels) across the page:

one           one         one          one        one       one         one     
  \             \           \            \          \         \           \     
  two           two         two          two        two      three       three  
    \             \           \            \          \       / \         / \   
   three         three        four         five       five  two four    two five
      \             \         / \          /          /           \         /   
      four          five     /   \      three       four          five    four  
        \           /     three  five      \        /                           
        five      four                     four  three                          



one          one        one        one       one       one         one        two        
  \            \          \          \         \         \           \        / \        
  four         four       five       five      five      five        five    /   \       
  / \          / \        /          /         /         /           /     one  three    
two five      /   \     two        two      three      four        four            \     
  \        three  five    \          \       / \       /           /               four  
 three      /            three       four  two four  two        three                \   
          two               \        /                 \         /                   five
                            four  three               three    two                       



   two          two          two        two      three         three         three    
   / \          / \          / \        / \       / \           / \           / \     
  /   \       one four     one five   one five  one four       /   \        two four  
one  three        / \          /          /       \   \       /     \       /     \   
        \        /   \      three       four      two five  one     five  one     five
        five  three  five      \        /                     \     /                 
        /                      four  three                    two four                
      four                                                                            



   three      four      four         four         four            four       five    
    / \       / \       / \          / \          / \             / \        /       
  two five  one five  one five     two five      /   \           /   \     one       
  /   /       \         \          / \        three  five     three  five    \       
one four      two      three      /   \        /               /             two     
                \       /       one  three   one             two               \     
               three  two                      \             /                three  
                                               two         one                   \   
                                                                                 four



  five      five      five      five       five         five      five        five
  /         /         /         /          /            /         /           /   
one       one       one       one        two          two      three       three  
  \         \         \         \        / \          / \       / \         / \   
  two      three      four      four    /   \       one four  one four    two four
    \       / \       /         /     one  three        /       \         /       
    four  two four  two      three            \      three      two     one       
    /                 \       /               four                                
 three               three  two                                                   



    five      five         five        five          five
    /         /            /           /             /   
  four      four         four        four          four  
  /         /            /           /             /     
one       one          two        three         three    
  \         \          / \         /             /       
  two      three      /   \      one           two       
    \       /       one  three     \           /         
   three  two                      two       one 

The following is an example of the same tree printed 4 different ways, with horizontal spacing of 1 and of 3, and with diagonal and horizontal branches.

                   27        
             +-----------+   
             13          29  
      +-------------+  +---+ 
      8             23 28  30
   +-----+       +-----+     
   4     11      21    26    
 +---+  +-+    +---+  ++     
 2   5  9 12   18  22 24     
+-+  ++ ++   +---+    ++     
1 3   6  10  17  19    25    
      ++    ++   ++          
       7    15    20         
          +---+              
          14  16             


                 27        
                / \        
               /   \       
              13    29     
             / \   / \     
            /   \ 28  30   
           /     \         
          /       \        
         /         \       
        /           \      
       8             23    
      / \           / \    
     /   \         /   \   
    4     11      /     \  
   / \   / \     21      26
  2   5 9   12  / \     /  
 / \   \ \     18  22  24  
1   3   6 10  / \       \  
         \   17  19      25
          7 /     \        
           15      20      
          / \              
         14  16            


                             27            
                    +-----------------+    
                    13                29   
          +-------------------+    +-----+ 
          8                   23   28    30
     +---------+         +---------+       
     4         11        21        26      
  +-----+    +---+    +-----+     ++       
  2     5    9   12   18    22    24       
+---+   ++   ++    +-----+        ++       
1   3    6    10   17    19        25      
         ++       ++     ++                
          7       15      20               
               +-----+                     
               14    16                    


                      27         
                     / \         
                    /   \        
                   /     \       
                  /       \      
                 13        29    
                / \       / \    
               /   \     /   \   
              /     \   28    30 
             /       \           
            /         \          
           /           \         
          /             \        
         /               \       
        8                 23     
       / \               / \     
      /   \             /   \    
     /     \           /     \   
    4       11        /       \  
   / \     / \       21        26
  2   5   9   12    / \       /  
 / \   \   \       /   \     24  
1   3   6   10    18    22    \  
         \       / \           25
          7     /   \            
               17    19          
              /       \          
             15        20        
            / \                  
           /   \                 
          14    16               

if else statement in AngularJS templates

A possibility for Angular: I had to include an if - statement in the html part, I had to check if all variables of an URL that I produce are defined. I did it the following way and it seems to be a flexible approach. I hope it will be helpful for somebody.

The html part in the template:

    <div  *ngFor="let p of poemsInGrid; let i = index" >
        <a [routerLink]="produceFassungsLink(p[0],p[3])" routerLinkActive="active">
    </div>

And the typescript part:

  produceFassungsLink(titel: string, iri: string) {
      if(titel !== undefined && iri !== undefined) {
         return titel.split('/')[0] + '---' + iri.split('raeber/')[1];
      } else {
         return 'Linkinformation has not arrived yet';
      }
  }

Thanks and best regards,

Jan

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

Highlighting Text Color using Html.fromHtml() in Android?

Using color value from xml resource:

int labelColor = getResources().getColor(R.color.label_color);
String ?olorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!

Html.fromHtml(String.format("<font color=\"#%s\">text</font>", ?olorString), TextView.BufferType.SPANNABLE); 

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

Find object by id in an array of JavaScript objects

As others have pointed out, .find() is the way to go when looking for one object within your array. However, if your object cannot be found using this method, your program will crash:

_x000D_
_x000D_
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];_x000D_
const res = myArray.find(x => x.id === '100').foo; // Uh oh!_x000D_
/*_x000D_
Error:_x000D_
"Uncaught TypeError: Cannot read property 'foo' of undefined"_x000D_
*/
_x000D_
_x000D_
_x000D_

This can be fixed by checking whether the result of .find() is defined before using using .foo on it. Modern JS allows us to do this easily with optional chaining, returning undefined if the object cannot be found, rather than crashing your code:

_x000D_
_x000D_
const myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];_x000D_
const res = myArray.find(x => x.id === '100')?.foo; // No error!_x000D_
console.log(res); // undefined when the object cannot be found
_x000D_
_x000D_
_x000D_

Replace multiple strings with multiple other strings

This may not meet your exact need in this instance, but I've found this a useful way to replace multiple parameters in strings, as a general solution. It will replace all instances of the parameters, no matter how many times they are referenced:

String.prototype.fmt = function (hash) {
        var string = this, key; for (key in hash) string = string.replace(new RegExp('\\{' + key + '\\}', 'gm'), hash[key]); return string
}

You would invoke it as follows:

var person = '{title} {first} {last}'.fmt({ title: 'Agent', first: 'Jack', last: 'Bauer' });
// person = 'Agent Jack Bauer'

Any way to exit bash script, but not quitting the terminal

This is just like you put a run function inside your script run2.sh. You use exit code inside run while source your run2.sh file in the bash tty. If the give the run function its power to exit your script and give the run2.sh its power to exit the terminator. Then of cuz the run function has power to exit your teminator.

    #! /bin/sh
    # use . run2.sh

    run()
    {
        echo "this is run"
        #return 0
        exit 0
    }

    echo "this is begin"
    run
    echo "this is end"

Anyway, I approve with Kaz it's a design problem.

How to convert comma separated string into numeric array in javascript

just you need to use couple of methods for this, that's it!

var strVale = "130,235,342,124";
var resultArray = strVale.split(',').map(function(strVale){return Number(strVale);});

the output will be the array of numbers.

How do you tell if a checkbox is selected in Selenium for Java?

The mechanism of selenium framework:

Here selenium make request to the its server and fetch first subelement with tagname input

WebElement e = e.findElement(By.tagName("input"));

Than you try to receive attribute on that element

object attribute = e.getAttribute("checked")

So either use

findElement(By.attribute("checked")

or use

findElement(By.xpath("\\input[@checked='true']")

P.S. I'm not familiar with java's equivalent of selenium api so some method may be named slightly different.

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

Executing Javascript code "on the spot" in Chrome?

Have you tried something like this? Put it in the head for it to work properly.

<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(){
         //using DOMContentLoaded is good as it relies on the DOM being ready for
         //manipulation, rather than the windows being fully loaded. Just like
         //how jQuery's $(document).ready() does it.

         //loop through your inputs and set their values here
    }, false);
</script>

Adding a slide effect to bootstrap dropdown

I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click

$('.navbar .dropdown').hover(function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});

How to generate unique ID with node.js

nanoid achieves exactly the same thing that you want.

Example usage:

const { nanoid } = require("nanoid")

console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can also use the toBase64Image() method setting animation: false

var options = {
    bezierCurve : false,
    animation: false
};

Updated Fiddle

PG COPY error: invalid input syntax for integer

ERROR: invalid input syntax for integer: ""

"" isn't a valid integer. PostgreSQL accepts unquoted blank fields as null by default in CSV, but "" would be like writing:

SELECT ''::integer;

and fail for the same reason.

If you want to deal with CSV that has things like quoted empty strings for null integers, you'll need to feed it to PostgreSQL via a pre-processor that can neaten it up a bit. PostgreSQL's CSV input doesn't understand all the weird and wonderful possible abuses of CSV.

Options include:

  • Loading it in a spreadsheet and exporting sane CSV;
  • Using the Python csv module, Perl Text::CSV, etc to pre-process it;
  • Using Perl/Python/whatever to load the CSV and insert it directly into the DB
  • Using an ETL tool like CloverETL, Talend Studio, or Pentaho Kettle

Rotate image with javascript

You use a combination of CSS's transform (with vendor prefixes as necessary) and transform-origin, like this: (also on jsFiddle)

_x000D_
_x000D_
var angle = 0,_x000D_
  img = document.getElementById('container');_x000D_
document.getElementById('button').onclick = function() {_x000D_
  angle = (angle + 90) % 360;_x000D_
  img.className = "rotate" + angle;_x000D_
}
_x000D_
#container {_x000D_
  width: 820px;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
#container.rotate90,_x000D_
#container.rotate270 {_x000D_
  width: 100px;_x000D_
  height: 820px_x000D_
}_x000D_
#image {_x000D_
  transform-origin: top left;_x000D_
  /* IE 10+, Firefox, etc. */_x000D_
  -webkit-transform-origin: top left;_x000D_
  /* Chrome */_x000D_
  -ms-transform-origin: top left;_x000D_
  /* IE 9 */_x000D_
}_x000D_
#container.rotate90 #image {_x000D_
  transform: rotate(90deg) translateY(-100%);_x000D_
  -webkit-transform: rotate(90deg) translateY(-100%);_x000D_
  -ms-transform: rotate(90deg) translateY(-100%);_x000D_
}_x000D_
#container.rotate180 #image {_x000D_
  transform: rotate(180deg) translate(-100%, -100%);_x000D_
  -webkit-transform: rotate(180deg) translate(-100%, -100%);_x000D_
  -ms-transform: rotate(180deg) translateX(-100%, -100%);_x000D_
}_x000D_
#container.rotate270 #image {_x000D_
  transform: rotate(270deg) translateX(-100%);_x000D_
  -webkit-transform: rotate(270deg) translateX(-100%);_x000D_
  -ms-transform: rotate(270deg) translateX(-100%);_x000D_
}
_x000D_
<button id="button">Click me!</button>_x000D_
<div id="container">_x000D_
  <img src="http://i.stack.imgur.com/zbLrE.png" id="image" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get an object's unqualified (short) class name?

A good old regex seems to be faster than the most of the previous shown methods:

// both of the below calls will output: ShortClassName

echo preg_replace('/.*\\\\/', '', 'ShortClassName');
echo preg_replace('/.*\\\\/', '', 'SomeNamespace\SomePath\ShortClassName');

So this works even when you provide a short class name or a fully qualified (canonical) class name.

What the regex does is that it consumes all previous chars until the last separator is found (which is also consumed). So the remaining string will be the short class name.

If you want to use a different separator (eg. / ) then just use that separator instead. Remember to escape the backslash (ie. \) and also the pattern char (ie. /) in the input pattern.