Programs & Examples On #Inserter

Web API Put Request generates an Http 405 Method Not Allowed error

WebDav-SchmebDav.. ..make sure you create the url with the ID correctly. Don't send it like http://www.fluff.com/api/Fluff?id=MyID, send it like http://www.fluff.com/api/Fluff/MyID.

Eg.

PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
Host: www.fluff.com
Content-Length: 11

{"Data":"1"}

This was busting my balls for a small eternity, total embarrassment.

Use of for_each on map elements

For fellow programmers who stumble upon this question from google, there is a good way using boost.

Explained here : Is it possible to use boost::foreach with std::map?

Real example for your convenience :

// typedef in include, given here for info : 
typedef std::map<std::string, std::string> Wt::WEnvironment::CookieMap

Wt::WEnvironment::CookieMap cookie_map = environment.cookies();

BOOST_FOREACH( const Wt::WEnvironment::CookieMap::value_type &cookie, cookie_map )
{
    std::cout << "cookie : " << cookie.first << " = " << cookie.second << endl;
}

enjoy.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Your second example does not work if you send the argument by reference. Did you mean

void copyVecFast(vec<int> original) // no reference
{

  vector<int> new_;
  new_.swap(original); 
}

That would work, but an easier way is

vector<int> new_(original);

How to retrieve all keys (or values) from a std::map and put them into a vector?

You can use the versatile boost::transform_iterator. The transform_iterator allows you to transform the iterated values, for example in our case when you want to deal only with the keys, not the values. See http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/transform_iterator.html#example

java.lang.NoClassDefFoundError in junit

If you have more than one version of java, it may interfere with your program.

I suggest you download JCreator.

When you do, click configure, options, and JDK Profiles. Delete the old versions of Java from the list. Then click the play button. Your program should appear.

If it doesn't, press ctrl+alt+O and then press the play button again.

Determine which element the mouse pointer is on top of in JavaScript

Let me start out by saying that I don't recommend using the method I'm about to suggest. It's much better to use event driven development and bind events only to the elements you're interested in knowing whether or not the mouse is over with mouseover, mouseout, mouseenter, mouseleave, etc.

If you absolutely must have the ability to know which element the mouse is over, you'd need to write a function that binds the mouseover event to everything in the DOM, and then store whatever the current element is in some variable.

You could so something like this:

window.which_element_is_the_mouse_on = (function() {

    var currentElement;

    $("body *").on('mouseover', function(e) {
        if(e.target === e.currentTarget) {
            currentElement = this;
        }
    });

    return function() {
        console.log(currentElement);
    }
}());

Basically, I've created an immediate function which sets the event on all elements and stores the current element within the closure to minimize your footprint.

Here's a working demo that calls window.which_element_is_the_mouse_on every second and logs what element the mouse is currently over to the console.

http://jsfiddle.net/LWFpJ/1/

Setting state on componentDidMount()

It is not an anti-pattern to call setState in componentDidMount. In fact, ReactJS provides an example of this in their documentation:

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

Example From Doc

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

How to set the timeout for a TcpClient?

Set ReadTimeout or WriteTimeout property on the NetworkStream for synchronous reads/writes. Updating OP's code:

try
{
    TcpClient client = new TcpClient("remotehost", this.Port);
    Byte[] data = System.Text.Encoding.Unicode.GetBytes(this.Message);
    NetworkStream stream = client.GetStream();
    stream.WriteTimeout = 1000; //  <------- 1 second timeout
    stream.ReadTimeout = 1000; //  <------- 1 second timeout
    stream.Write(data, 0, data.Length);
    data = new Byte[512];
    Int32 bytes = stream.Read(data, 0, data.Length);
    this.Response = System.Text.Encoding.Unicode.GetString(data, 0, bytes);

    stream.Close();
    client.Close();    

    FireSentEvent();  //Notifies of success
}
catch (Exception ex)
{
    // Throws IOException on stream read/write timeout
    FireFailedEvent(ex); //Notifies of failure
}

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

Excel to CSV with UTF8 encoding

  1. Save the Excel sheet as "Unicode Text (.txt)". The good news is that all the international characters are in UTF16 (note, not in UTF8). However, the new "*.txt" file is TAB delimited, not comma delimited, and therefore is not a true CSV.

  2. (optional) Unless you can use a TAB delimited file for import, use your favorite text editor and replace the TAB characters with commas ",".

  3. Import your *.txt file in the target application. Make sure it can accept UTF16 format.

If UTF-16 has been properly implemented with support for non-BMP code points, that you can convert a UTF-16 file to UTF-8 without losing information. I leave it to you to find your favourite method of doing so.

I use this procedure to import data from Excel to Moodle.

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery // http://code.jquery.com/jquery-latest.js

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX

Java - sending HTTP parameters via POST method easily

I had the same issue. I wanted to send data via POST. I used the following code:

    URL url = new URL("http://example.com/getval.php");
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("param1", param1);
    params.put("param2", param2);

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    String urlParameters = postData.toString();
    URLConnection conn = url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(urlParameters);
    writer.flush();

    String result = "";
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        result += line;
    }
    writer.close();
    reader.close()
    System.out.println(result);

I used Jsoup for parse:

    Document doc = Jsoup.parseBodyFragment(value);
    Iterator<Element> opts = doc.select("option").iterator();
    for (;opts.hasNext();) {
        Element item = opts.next();
        if (item.hasAttr("value")) {
            System.out.println(item.attr("value"));
        }
    }

django import error - No module named core.management

For me, my server was using Python 2.4. I simply looked up Python 2.7, which was installed on my server, and created an alias.

alias python=python2.7

If you need to know more, I found the solution here

Get Image Height and Width as integer values?

Like this :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

How can I convert a string to an int in Python?

easy!

    if option == str(1):
        numberA = int(raw_input("enter first number. "))
        numberB= int(raw_input("enter second number. "))
        print " "
        print addition(numberA, numberB)
     etc etc etc

How to create a Custom Dialog box in android?

Simple first create a class

 public class ViewDialog {

        public void showDialog(Activity activity, String msg){
            final Dialog dialog = new Dialog(activity);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.custom_dialogbox_otp);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

            TextView text = (TextView) dialog.findViewById(R.id.txt_file_path);
            text.setText(msg);

            Button dialogBtn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
            dialogBtn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(getApplicationContext(),"Cancel" ,Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });

            Button dialogBtn_okay = (Button) dialog.findViewById(R.id.btn_okay);
            dialogBtn_okay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(getApplicationContext(),"Okay" ,Toast.LENGTH_SHORT).show();
                    dialog.cancel();
                }
            });

            dialog.show();
        }
    }

then create a custom_dialogbox_otp

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="330dp"
    android:layout_height="160dp"
    android:background="#00555555"
    android:orientation="vertical"
    android:padding="5dp"
    android:weightSum="100">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/round_layout_otp"
        android:orientation="vertical"
        android:padding="7dp"
        android:weightSum="100">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="60"
            android:orientation="horizontal"
            android:weightSum="100">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="80"
                android:gravity="center">

                <ImageView
                    android:id="@+id/a"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="#DA5F6A"
                    android:gravity="center"
                    android:scaleType="fitCenter"
                    android:src="@mipmap/infoonetwo" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="20">

                <TextView
                    android:id="@+id/txt_file_path"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:singleLine="true"
                    android:text="TEXTO"
                    android:textColor="#FFFFFF"
                    android:textSize="17sp"
                    android:textStyle="bold" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="40"
            android:background="@drawable/round_layout_white_otp"
            android:orientation="vertical"
            android:weightSum="100">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_weight="60">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="Do you wanna Exit..?"
                    android:textColor="#ff000000"
                    android:textSize="15dp"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="40"
                android:orientation="horizontal"
                android:weightSum="100">


                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="30dp"
                    android:layout_weight="50"
                    android:gravity="center|right">

                    <Button
                        android:id="@+id/btn_cancel"
                        android:layout_width="80dp"
                        android:layout_height="25dp"
                        android:background="@drawable/round_button"
                        android:gravity="center"
                        android:text="CANCEL"
                        android:textSize="13dp"
                        android:textStyle="bold"
                        android:textColor="#ffffffff" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="30dp"
                    android:layout_weight="50"
                    android:gravity="center|left">


                    <Button
                        android:id="@+id/btn_okay"
                        android:layout_width="80dp"
                        android:layout_height="25dp"
                        android:background="@drawable/round_button"
                        android:text="OKAY"
                        android:textSize="13dp"
                        android:textStyle="bold"
                        android:textColor="#ffffffff" />

                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

then in your drawable create beneath xml files.
for round_layout_white_otp.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- <corners android:radius="10dp" /> -->
    <corners
        android:bottomLeftRadius="18dp"
        android:bottomRightRadius="16dp"
        android:topLeftRadius="38dp"
        android:topRightRadius="36dp" />
    <solid android:color="#C0C0C0" />
    </shape>

for round_layout_otp.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- <corners android:radius="10dp" /> -->
    <corners
        android:bottomLeftRadius="18dp"
        android:bottomRightRadius="16dp"
        android:topLeftRadius="38dp"
        android:topRightRadius="38dp" />
    <solid android:color="#DA5F6A" />
    </shape>

round_button

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- <corners android:radius="10dp" /> -->
    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />
    <solid android:color="#06A19E" />
    </shape>

Then finally use the underneath code to visual ur dialog :)

ViewDialog alert = new ViewDialog();
        alert.showDialog(ReceivingOTPRegActivity.this, "OTP has been sent to your Mail ");

your output :)

enter image description here

PHP checkbox set to check based on database value

This simplest ways is to add the "checked attribute.

<label for="tag_1">Tag 1</label>
<input type="checkbox" name="tag_1" id="tag_1" value="yes" 
    <?php if($tag_1_saved_value === 'yes') echo 'checked="checked"';?> />

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

A different take with a simple jQuery plugin

Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.

This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.

You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.

All you have to do is to use this plugin on the client side. An Ajax request would look like this:

$.ajax({
    type: "POST",
    url: "SomeURL",
    data: $.toDictionary(yourComplexJSONobject),
    success: function() { ... },
    error: function() { ... }
});

But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.

Regular Expression for matching parentheses

Because ( is special in regex, you should escape it \( when matching. However, depending on what language you are using, you can easily match ( with string methods like index() or other methods that enable you to find at what position the ( is in. Sometimes, there's no need to use regex.

How to set a transparent background of JPanel?

Calling setOpaque(false) on the upper JPanel should work.

From your comment, it sounds like Swing painting may be broken somewhere -

First - you probably wanted to override paintComponent() rather than paint() in whatever component you have paint() overridden in.

Second - when you do override paintComponent(), you'll first want to call super.paintComponent() first to do all the default Swing painting stuff (of which honoring setOpaque() is one).

Example -

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class TwoPanels {
    public static void main(String[] args) {

        JPanel p = new JPanel();
        // setting layout to null so we can make panels overlap
        p.setLayout(null);

        CirclePanel topPanel = new CirclePanel();
        // drawing should be in blue
        topPanel.setForeground(Color.blue);
        // background should be black, except it's not opaque, so 
        // background will not be drawn
        topPanel.setBackground(Color.black);
        // set opaque to false - background not drawn
        topPanel.setOpaque(false);
        topPanel.setBounds(50, 50, 100, 100);
        // add topPanel - components paint in order added, 
        // so add topPanel first
        p.add(topPanel);

        CirclePanel bottomPanel = new CirclePanel();
        // drawing in green
        bottomPanel.setForeground(Color.green);
        // background in cyan
        bottomPanel.setBackground(Color.cyan);
        // and it will show this time, because opaque is true
        bottomPanel.setOpaque(true);
        bottomPanel.setBounds(30, 30, 100, 100);
        // add bottomPanel last...
        p.add(bottomPanel);

        // frame handling code...
        JFrame f = new JFrame("Two Panels");
        f.setContentPane(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    // Panel with a circle drawn on it.
    private static class CirclePanel extends JPanel {

        // This is Swing, so override paint*Component* - not paint
        protected void paintComponent(Graphics g) {
            // call super.paintComponent to get default Swing 
            // painting behavior (opaque honored, etc.)
            super.paintComponent(g);
            int x = 10;
            int y = 10;
            int width = getWidth() - 20;
            int height = getHeight() - 20;
            g.drawArc(x, y, width, height, 0, 360);
        }
    }
}

How to do URL decoding in Java?

Using java.net.URI class:

public String getDecodedURL(String encodedUrl) {
    try {
        URI uri = new URI(encodedUrl);
        return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
    } catch (Exception e) {
        return "";
    }
}

Please note that exception handling can be better, but it's not much relevant for this example.

MySQL select one column DISTINCT, with corresponding other columns

SELECT DISTINCT(firstName), ID, LastName from tableName GROUP BY firstName

Would be the best bet IMO

Alert handling in Selenium WebDriver (selenium 2) with Java

Write the following method:

public boolean isAlertPresent() {
    try {
        driver.switchTo().alert();
        return true;
    } // try
    catch (Exception e) {
        return false;
    } // catch
}

Now, you can check whether alert is present or not by using the method written above as below:

if (isAlertPresent()) {
    driver.switchTo().alert();
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();
}

How to change the color of winform DataGridview header?

It can be done.

From the designer: Select your DataGridView Open the Properties Navigate to ColumnHeaderDefaultCellStype Hit the button to edit the style.

You can also do it programmatically:

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Purple;

Hope that helps!

This action could not be completed. Try Again (-22421)

For June 1 2017

Certain combined steps from answer of this thread that worked for me. I am writing the process that worked fine for me.

1) Open terminal and run this

cd ~

mv .itmstransporter/ .old_itmstransporter/

"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"

iTMSTransporter will then update itself, wait till process completes.

2) Logout the apple account from Xcode preferences account and login again instead of creating new Id on iTunes and developer account.

3) Clean the project and archive then export the app from organiser as an IPA for app store distribution.

4) Logging into application loader with same account and upload the ipa.

5) Process will complete successfully.

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

If you have pushed the commit to remote and then erroneously amended changes to that commit this will fix your problem. Issue a git log to find the SHA before the commit. (this assumes remote is named origin). Now issue these command using that SHA.

git reset --soft <SHA BEFORE THE AMMEND>
#you now see all the changes in the commit and the amend undone

#save ALL the changes to the stash
git stash

git pull origin <your-branch> --ff-only
#if you issue git log you can see that you have the commit you didn't want to amend

git stash pop
#git status reveals only the changes you incorrectly amended

#now you can create your new unamended commit

A regex for version number parsing

Another try:

^(((\d+)\.)?(\d+)\.)?(\d+|\*)$

This gives the three parts in groups 4,5,6 BUT: They are aligned to the right. So the first non-null one of 4,5 or 6 gives the version field.

  • 1.2.3 gives 1,2,3
  • 1.2.* gives 1,2,*
  • 1.2 gives null,1,2
  • *** gives null,null,*
  • 1.* gives null,1,*

Running Python on Windows for Node.js dependencies

For me, these steps fixed the issue:

1- Running this cmd as admin:

npm install --global --production windows-build-tools

2- Then running npm rebuild after the 1st step is completed (especially completing the python 2.7 installation, which was the main cause of the issue)

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

this is my simple implementation for ASYNC requests with jQuery. I hope this help anyone.

var queueUrlsForRemove = [
    'http://dev-myurl.com/image/1', 
    'http://dev-myurl.com/image/2',
    'http://dev-myurl.com/image/3',
];

var queueImagesDelete = function(){

    deleteImage( queueUrlsForRemove.splice(0,1), function(){
        if (queueUrlsForRemove.length > 0) {
            queueImagesDelete();
        }
    });

}

var deleteImage = function(url, callback) {
    $.ajax({
        url: url,
        method: 'DELETE'
    }).done(function(response){
        typeof(callback) == 'function' ? callback(response) : null;
    });
}

queueImagesDelete();

Is there a better way to do optional function parameters in JavaScript?

The test for undefined is unnecessary and isn't as robust as it could be because, as user568458 pointed out, the solution provided fails if null or false is passed. Users of your API might think false or null would force the method to avoid that parameter.

function PaulDixonSolution(required, optionalArg){
   optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
   console.log(optionalArg);
};
PaulDixonSolution("required");
PaulDixonSolution("required", "provided");
PaulDixonSolution("required", null);
PaulDixonSolution("required", false);

The result is:

defaultValue
provided
null
false

Those last two are potentially bad. Instead try:

function bulletproof(required, optionalArg){
   optionalArg = optionalArg ? optionalArg : "defaultValue";;
   console.log(optionalArg);
};
bulletproof("required");
bulletproof("required", "provided");
bulletproof("required", null);
bulletproof("required", false);

Which results in:

defaultValue
provided
defaultValue
defaultValue

The only scenario where this isn't optimal is when you actually have optional parameters that are meant to be booleans or intentional null.

Unable to set variables in bash script

Five problems:

  1. Don't put a space before or after the equal sign.
  2. Use "$(...)" to get the output of a command as text.
  3. [ is a command. Put a space between it and the arguments.
  4. Commands are case-sensitive. You want echo.
  5. Use double quotes around variables. rm "$folderToBeMoved"

deleting folder from java

It could be problem with nested folders. Your code deletes the folders in the order they were found, which is top-down, which does not work. It might work if you reverse the folder list first.

But I would recommend you just use a library like Commons IO for this.

Mockito test a void method throws an exception

If you ever wondered how to do it using the new BDD style of Mockito:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing:

willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I had the same Error,

 Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

in my case the WAR had application.properties inside that pointed to development server
where external application.properties was pointing to the right DB server.

make sure you don't have any other application.properties in the classpath / jars...

Remove last character from string. Swift language

var str = "Hello, playground"

extension String {
    var stringByDeletingLastCharacter: String {
        return dropLast(self)
    }
}

println(str.stringByDeletingLastCharacter)   // "Hello, playgroun"

How to create a simple map using JavaScript/JQuery

function Map() {
    this.keys = new Array();
    this.data = new Object();

    this.put = function (key, value) {
        if (this.data[key] == null) {
            this.keys.push(key);
        }
        this.data[key] = value;
    };

    this.get = function (key) {
        return this.data[key];
    };

    this.remove = function (key) {
        this.keys.remove(key);
        this.data[key] = null;
    };

    this.each = function (fn) {
        if (typeof fn != 'function') {
            return;
        }
        var len = this.keys.length;
        for (var i = 0; i < len; i++) {
            var k = this.keys[i];
            fn(k, this.data[k], i);
        }
    };

    this.entrys = function () {
        var len = this.keys.length;
        var entrys = new Array(len);
        for (var i = 0; i < len; i++) {
            entrys[i] = {
                key: this.keys[i],
                value: this.data[i]
            };
        }
        return entrys;
    };

    this.isEmpty = function () {
        return this.keys.length == 0;
    };

    this.size = function () {
        return this.keys.length;
    };
}

How to parse data in JSON format?

For URL or file, use json.load(). For string with .json content, use json.loads().

#! /usr/bin/python

import json
# from pprint import pprint

json_file = 'my_cube.json'
cube = '1'

with open(json_file) as json_data:
    data = json.load(json_data)

# pprint(data)

print "Dimension: ", data['cubes'][cube]['dim']
print "Measures:  ", data['cubes'][cube]['meas']

Clearing coverage highlighting in Eclipse

For those using Cobertura and only have the Coverage Session View like I do,just try closing Eclipse and starting it up again. This got rid of the highlighting for me.

display:inline vs display:block

Display:block It very much behaves the same way as 'p' tags and it takes up the entire row and there can't be any element next to it until it's floated. Display:inline It's just uses as much space as required and allows other elements to be aligned alongside itself.

Use these properties in case of forms and you will get a better understanding.

GIT commit as different user without email / or only email

The specific format is:

git commit --author="John Doe <[email protected]>" -m "Impersonation is evil." 

How can I make the cursor turn to the wait cursor?

For Windows Forms applications an optional disabling of a UI-Control can be very useful. So my suggestion looks like this:

public class AppWaitCursor : IDisposable
{
    private readonly Control _eventControl;

    public AppWaitCursor(object eventSender = null)
    {
         _eventControl = eventSender as Control;
        if (_eventControl != null)
            _eventControl.Enabled = false;

        Application.UseWaitCursor = true;
        Application.DoEvents();
    }

    public void Dispose()
    {
        if (_eventControl != null)
            _eventControl.Enabled = true;

        Cursor.Current = Cursors.Default;
        Application.UseWaitCursor = false;
    }
}

Usage:

private void UiControl_Click(object sender, EventArgs e)
{
    using (new AppWaitCursor(sender))
    {
        LongRunningCall();
    }
}

How can I wrap or break long text/word in a fixed width span?

Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.

By defining the the full span as display:inline-block you might have a hard time displaying images.

Therefore I prefer to define a span like so:

span {
  display:block;
  width:150px;
  word-wrap:break-word;      
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
  display:inline-block;
}
img{
  display:block;
}

How to extract filename.tar.gz file

If file filename.tar.gz gives this message: POSIX tar archive, the archive is a tar, not a GZip archive.

Unpack a tar without the z, it is for gzipped (compressed), only:

mv filename.tar.gz filename.tar # optional
tar xvf filename.tar

Or try a generic Unpacker like unp (https://packages.qa.debian.org/u/unp.html), a script for unpacking a wide variety of archive formats.

determine the file type:

$ file ~/Downloads/filename.tbz2
/User/Name/Downloads/filename.tbz2: bzip2 compressed data, block size = 400k

Return an empty Observable

For typescript you can specify generic param of your empty observable like this:

import 'rxjs/add/observable/empty' 

Observable.empty<Response>();

How to block users from closing a window in Javascript?

If you don't want to display popup for all event you can add conditions like

window.onbeforeunload = confirmExit;
    function confirmExit() {
        if (isAnyTaskInProgress) {
           return "Some task is in progress. Are you sure, you want to close?";
        }
    }

This works fine for me

How to comment out particular lines in a shell script

for single line comment add # at starting of a line
for multiple line comments add ' (single quote) from where you want to start & add ' (again single quote) at the point where you want to end the comment line.

MSBUILD : error MSB1008: Only one project can be specified

If you are using Azure DevOps MSBuild task the error may be caused by doubled configuration flag. Please make sure you put $(BuildConfiguration) in specified box instead of MSBuild Arguments one: enter image description here

How do I use FileSystemObject in VBA?

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

How do I create a branch?

  • Create a new folder outside of your current project. You can give it any name. (Example: You have a checkout for a project named "Customization". And it has many projects, like "Project1", "Project2"....And you want to create a branch of "Project1". So first open the "Customization", right click and create a new folder and give it a name, "Project1Branch").
  • Right click on "Myproject1"....TortoiseSVN -> Branch/Tag.
  • Choose working copy.
  • Open browser....Just right of parallel on "To URL".
  • Select customization.....right click then Add Folder. and go through the folder which you have created. Here it is "Project1Branch". Now clik the OK button to add.
  • Take checkout of this new banch.
  • Again go to your project which branch you want to create. Right click TorotoiseSVN -> branch/tag. Then select working copy. And you can give the URL as your branch name. like {your IP address/svn/AAAA/Customization/Project1Branch}. And you can set the name in the URL so it will create the folder with this name only. Like {Your IP address/svn/AAAA/Customization/Project1Branch/MyProject1Branch}.
  • Press the OK button. Now you can see the logs in ...your working copy will be stored in your branch.
  • Now you can take a check out...and let you enjoy your work. :)

BACKUP LOG cannot be performed because there is no current database backup

Originally, I created a database and then restored the backup file to my new empty database:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

This was wrong. I shouldn't have first created the database.

Now, instead, I do this:

Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK

AngularJS access parent scope from child controller

When you are using as syntax, like ParentController as parentCtrl, to define a controller then to access parent scope variable in child controller use following :

var id = $scope.parentCtrl.id;

Where parentCtrl is name of parent controller using as syntax and id is a variable defined in same controller.

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.

for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php

to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

How to add a downloaded .box file to Vagrant?

Solution for Windows:

  • Open the cmd or powershell as admin
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box 'name_of_my_box.box'
  • vagrant box list should show the new box in the list

Solution for MAC:

  • Open terminal
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box "./name_of_my_box.box"
  • vagrant box list should show the new box in the list

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

Vendor code 17002 to connect to SQLDeveloper

I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.

See LISTENER: TNS-12545 ... No such file or directory.

How do I detect IE 8 with jQuery?

You can easily detect which type and version of the browser, using this jquery

$(document).ready(function()
{
 if ( $.browser.msie ){
    if($.browser.version == '6.0')
    {   $('html').addClass('ie6');
    }
    else if($.browser.version == '7.0')
    {   $('html').addClass('ie7');
    }
    else if($.browser.version == '8.0')
    {   $('html').addClass('ie8');
    }
    else if($.browser.version == '9.0')
    {   $('html').addClass('ie9');
    }
 }
 else if ( $.browser.webkit )
 { $('html').addClass('webkit');
 }
 else if ( $.browser.mozilla )
 { $('html').addClass('mozilla');
 }
 else if ( $.browser.opera )
 { $('html').addClass('opera');
 }
});

Set max-height on inner div so scroll bars appear, but not on parent div

If you make

overflow: hidden in the outer div and overflow-y: scroll in the inner div it will work.

http://jsfiddle.net/C8MuZ/11/

Switching to a TabBar tab view programmatically?

My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:

tabBarController.selectedIndex = 2

However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:

override var shouldAutomaticallyForwardAppearanceMethods: Bool 
{
    return true
}

How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

Less than or equal to

You can use:

EQU - equal

NEQ - not equal

LSS - less than

LEQ - less than or equal

GTR - greater than

GEQ - greater than or equal

AVOID USING:

() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=

How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Easily readable and customisable way to get a timestamp in your desired format, without use of any library:

function timestamp(){
  function pad(n) {return n<10 ? "0"+n : n}
  d=new Date()
  dash="-"
  colon=":"
  return d.getFullYear()+dash+
  pad(d.getMonth()+1)+dash+
  pad(d.getDate())+" "+
  pad(d.getHours())+colon+
  pad(d.getMinutes())+colon+
  pad(d.getSeconds())
}

(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")

How to increase code font size in IntelliJ?

In IntellJ 13

File 
 |
  ---- Settings 
       |
        ------- Editor
                 |
                  ------- Colors & Fonts
                          |
                           ------ Font -> [Size]

enter image description here

Make JQuery UI Dialog automatically grow or shrink to fit its contents

var w = $('#dialogText').text().length;

$("#dialog").dialog('option', 'width', (w * 10));

did what i needed it to do for resizing the width of the dialog.

What does "export" do in shell programming?

it makes the assignment visible to subprocesses.

$ foo=bar
$ bash -c 'echo $foo'

$ export foo
$ bash -c 'echo $foo'
bar

JavaScript split String with white space

You can just split on the word boundary using \b. See MDN

"\b: Matches a zero-width word boundary, such as between a letter and a space."

You should also make sure it is followed by whitespace \s. so that strings like "My car isn't red" still work:

var stringArray = str.split(/\b(\s)/);

The initial \b is required to take multiple spaces into account, e.g. my car is red

EDIT: Added grouping

Set selected option of select box

This would be another option:

$('.id_100 option[value=val2]').prop('selected', true);

Changing an element's ID with jQuery

What you mean to do is:

jQuery(this).prev("li").attr("id", "newID");

That will set the ID to the new ID

count distinct values in spreadsheet

Not exactly what the user asked, but an easy way to just count unique values:

Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:

=COUNTUNIQUE(A1:B10)

How do you rename a Git tag?

This wiki page has this interesting one-liner, which reminds us that we can push several refs:

git push origin refs/tags/<old-tag>:refs/tags/<new-tag> :refs/tags/<old-tag> && git tag -d <old-tag>

and ask other cloners to do git pull --prune --tags

So the idea is to push:

  • <new-tag> for every commits referenced by <old-tag>: refs/tags/<old-tag>:refs/tags/<new-tag>,
  • the deletion of <old-tag>: :refs/tags/<old-tag>

See as an example "Change naming convention of tags inside a git repository?".

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

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

Generic method to call the API:

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

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


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

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

Call the method:

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

Add to Array jQuery

For JavaScript arrays, you use push().

var a = [];
a.push(12);
a.push(32);

For jQuery objects, there's add().

$('div.test').add('p.blue');

Note that while push() modifies the original array in-place, add() returns a new jQuery object, it does not modify the original one.

Posting parameters to a url using the POST method without using a form

it can be done with CURL or AJAX. The response is equally cryptic as the answer.

MySQL: Set user variable from result of query

Yes, but you need to move the variable assignment into the query:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

Test case:

CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);

Result:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

+--------+-------+
| user   | group |
+--------+-------+
| 123456 |     5 |
| 111111 |     5 |
+--------+-------+
2 rows in set (0.00 sec)

Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.


UPDATE:

Further to comments below, you may also do the following:

SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group; 
SELECT * FROM user WHERE `group` = @group;

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Python Remove last 3 characters of a string

It doesn't work as you expect because strip is character based. You need to do this instead:

foo = foo.replace(' ', '')[:-3].upper()

How can I measure the actual memory usage of an application or process?

#!/bin/ksh
#
# Returns total memory used by process $1 in kb.
#
# See /proc/NNNN/smaps if you want to do something
# more interesting.
#

IFS=$'\n'

for line in $(</proc/$1/smaps)
do
   [[ $line =~ ^Size:\s+(\S+) ]] && ((kb += ${.sh.match[1]}))
done

print $kb

How can I show a combobox in Android?

In android it is called a Spinner you can take a look at the tutorial here.

Hello, Spinner

And this is a very vague question, you should try to be more descriptive of your problem.

Python: How to increase/reduce the fontsize of x and y tick labels?

It is simpler than I thought it would be.

To set the font size of the x-axis ticks:

x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)

To do it for the y-axis ticks:

y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

The arguments rotation and fontsize can easily control what I was after.

Reference: http://matplotlib.org/api/axes_api.html

Converting Integer to Long

Simply:

Integer i = 7;
Long l = new Long(i);

ActiveRecord find and only return selected columns

pluck(column_name)

This method is designed to perform select by a single column as direct SQL query Returns Array with values of the specified column name The values has same data type as column.

Examples:

Person.pluck(:id) # SELECT people.id FROM people
Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
Person.where(:confirmed => true).limit(5).pluck(:id)

see http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck

Its introduced rails 3.2 onwards and accepts only single column. In rails 4, it accepts multiple columns

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

None of the other answers worked for me.

This did: (in Startup.cs)

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        WebApiConfig.Register(config);

        // Here: 
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    }
}

(or you can put it in WebApiConfig.cs):

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // Here: 
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    }
}

Intellij idea cannot resolve anything in maven

I was getting this error because my project was not setup correctly. It had imported main and test folders as modules. When I deleted the 2 modules (but retained them as source and test folders), my code started compiling correctly.

Usage of \b and \r in C

As for the meaning of each character described in C Primer Plus, what you expected is an 'correct' answer. It should be true for some computer architectures and compilers, but unfortunately not yours.

I wrote a simple c program to repeat your test, and got that 'correct' answer. I was using Mac OS and gcc. enter image description here

Also, I am very curious what is the compiler that you were using. :)

How to escape comma and double quote at same time for CSV file?

"cell one","cell "" two","cell "" ,three"

Save this to csv file and see the results, so double quote is used to escape itself

Important Note

"cell one","cell "" two", "cell "" ,three"

will give you a different result because there is a space after the comma, and that will be treated as "

console.log showing contents of array object

there are two potential simple solutions to dumping an array as string. Depending on the environment you're using:

…with modern browsers use JSON:

JSON.stringify(filters);
// returns this
"{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"

…with something like node.js you can use console.info()

console.info(filters);
// will output:
{ dvals: 
[ { brand: '1', count: '1' },
  { brand: '2', count: '2' },
  { brand: '3', count: '3' } ] }

Edit:

JSON.stringify comes with two more optional parameters. The third "spaces" parameter enables pretty printing:

JSON.stringify(
                obj,      // the object to stringify
                replacer, // a function or array transforming the result
                spaces    // prettyprint indentation spaces
              )

example:

JSON.stringify(filters, null, "  ");
// returns this
"{
 "dvals": [
  {
   "brand": "1",
   "count": "1"
  },
  {
   "brand": "2",
   "count": "2"
  },
  {
   "brand": "3",
   "count": "3"
  }
 ]
}"

git pull keeping local changes

We can also try git pull with rebase

git pull --rebase origin dev

How to convert minutes to Hours and minutes (hh:mm) in java

(In Kotlin) If you are going to put the answer into a TextView or something you can instead use a string resource:

<string name="time">%02d:%02d</string>

And then you can use this String resource to then set the text at run time using:

private fun setTime(time: Int) {
    val hour = time / 60
    val min = time % 60
    main_time.text = getString(R.string.time, hour, min)
}

JavaScript: How to pass object by value?

You're a little confused about how objects work in JavaScript. The object's reference is the value of the variable. There is no unserialized value. When you create an object, its structure is stored in memory and the variable it was assigned to holds a reference to that structure.

Even if what you're asking was provided in some sort of easy, native language construct it would still technically be cloning.

JavaScript is really just pass-by-value... it's just that the value passed might be a reference to something.

How to check for Is not Null And Is not Empty string in SQL server?

in basic way

SELECT *
FROM [TableName]
WHERE column_name!='' AND column_name IS NOT NULL

How do I use .toLocaleTimeString() without displaying seconds?

Even though this is an older question, I had the same one myself recently, and came up with a more simple solution using regular expressions and the string replace function as another alternative (no need for external js libraries or reliance on the ECMAScript Internalization API):

var d = new Date();
var localeTime = d.toLocaleTimeString();
var localeTimeSansSeconds = localeTime.replace(/:(\d{2}) (?=[AP]M)/, " ");

This approach uses a regex look-ahead to grab the :ss AM/PM end of the string and replaces the :ss part with a space, returning the rest of the string untouched. (Literally says "Find a colon with two digits and a space that is followed by either AM or PM and replace the colon, two digits, and space portion with just a space).

This expression/approach only works for en-US and en-US-like Locales. If you also wanted a similar outcome with, say, British English (en-GB), which doesn't use AM/PM, a different regular expression is needed.

Based on the original questioner's sample output, I assume that they were primarily dealing with American audiences and the en-US time schema.

How do I resolve `The following packages have unmet dependencies`

I tried lots of method but below work like charm....

After this command run these :-

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

Now check…

node -v
npm -v

Formatting "yesterday's" date in python

To expand on the answer given by Chris

if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know

>>> from datetime import date, timedelta                   
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'

If you want it as an integer (which can be useful)

>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]

someFunc(items)

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

How do you convert a C++ string to an int?

in "stdapi.h"

StrToInt

This function tells you the result, and how many characters participated in the conversion.

A cycle was detected in the build path of project xxx - Build Path Problem

Just restarting Eclipse fixed the issue in my project

Delete a database in phpMyAdmin

If you want to delete your database from phpmyAdmin or mySQl. Simply go to SQL command and write command "drop DATABASE databasename;"

Example: drop DATABASE rainbowonlineshopping;

enter image description here

Then click on "Go" Button. Your Database will be deleted and you get information like this

enter image description here

How to list all dates between two dates

You can create a stored procedure passing 2 dates

CREATE PROCEDURE SELECTALLDATES
(
@StartDate as date,
@EndDate as date
)
AS
Declare @Current as date = DATEADD(DD, 1, @BeginDate);

Create table #tmpDates
(displayDate date)

WHILE @Current < @EndDate
BEGIN
insert into #tmpDates
VALUES(@Current);
set @Current = DATEADD(DD, 1, @Current) -- add 1 to current day
END

Select * 
from #tmpDates

drop table #tmpDates

how to calculate percentage in python

You're performing an integer division. Append a .0 to the number literals:

per=float(tota)*(100.0/500.0)

In Python 2.7 the division 100/500==0.

As pointed out by @unwind, the float() call is superfluous since a multiplication/division by a float returns a float:

per= tota*100.0 / 500

How to remove empty lines with or without whitespace in Python

If you are not willing to try regex (which you should), you can use this:

s.replace('\n\n','\n')

Repeat this several times to make sure there is no blank line left. Or chaining the commands:

s.replace('\n\n','\n').replace('\n\n','\n')


Just to encourage you to use regex, here are two introductory videos that I find intuitive:
Regular Expressions (Regex) Tutorial
Python Tutorial: re Module

Calling a class function inside of __init__

In parse_file, take the self argument (just like in __init__). If there's any other context you need then just pass it as additional arguments as usual.

changing kafka retention period during runtime

I tested and used this command in kafka confluent V4.0.0 and apache kafka V 1.0.0 and 1.0.1

/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config  retention.ms=55000

test is the topic name.

I think it works well in other versions too

Error: Could not find or load main class

This solved the issue for me today:

cd /path/to/project
cd build
rm -r classes

Then clean&build it and run the individual files you need.

C++ template constructor

template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;

the above helpers let you work with types as values.

class A {
  template<class T>
  A( tag<T> );
};

the tag<T> type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:

auto a = A(tag<int>{});

You can pass in more than one type:

class A {
  template<class T, class U, class V>
  A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});

How to check permissions of a specific directory?

On OS X you can use:

ls -lead

The e option shows ACLs. And ACLs are very important to knowing what the exact permissions on your system are.

Undefined symbols for architecture i386

At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:

"_OBJC_CLASS_$_RadioKit", referenced from:
  objc-class-ref in RadioPlayerViewController.o

If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that

Radiokit *rk;

has "Radiokit" in green when the actual decalaration should be:

RadioKit *rk;

This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.

How to set web.config file to show full error message

not sure if it'll work in your scenario, but try adding the following to your web.config under <system.web>:

  <system.web>
    <customErrors mode="Off" />
  ...
  </system.web>

works in my instance.

also see:

CustomErrors mode="Off"

Powershell import-module doesn't find modules

I had this problem, but only in Visual Studio Code, not in ISE. Turns out I was using an x86 session in VSCode. I displayed the PowerShell Session Menu and switched to the x64 session, and all the modules began working without full paths. I am using Version 1.17.2, architecture x64 of VSCode. My modules were stored in the C:\Windows\System32\WindowsPowerShell\v1.0\Modules directory.

How do you copy and paste into Git Bash

enter image description here

In windows after this setting you can use ctrl + shift + v ( for windows)

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

To create both of the created_at and updated_at columns:

$t->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$t->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

You will need MySQL version >= 5.6.5 to have multiple columns with CURRENT_TIMESTAMP

Difference between ProcessBuilder and Runtime.exec()

There are no difference between ProcessBuilder.start() and Runtime.exec() because implementation of Runtime.exec() is:

public Process exec(String command) throws IOException {
    return exec(command, null, null);
}

public Process exec(String command, String[] envp, File dir)
    throws IOException {
    if (command.length() == 0)
        throw new IllegalArgumentException("Empty command");

    StringTokenizer st = new StringTokenizer(command);
    String[] cmdarray = new String[st.countTokens()];
    for (int i = 0; st.hasMoreTokens(); i++)
        cmdarray[i] = st.nextToken();
    return exec(cmdarray, envp, dir);
}

public Process exec(String[] cmdarray, String[] envp, File dir)
    throws IOException {
    return new ProcessBuilder(cmdarray)
        .environment(envp)
        .directory(dir)
        .start();
}

So code:

List<String> list = new ArrayList<>();
new StringTokenizer(command)
.asIterator()
.forEachRemaining(str -> list.add((String) str));
new ProcessBuilder(String[])list.toArray())
            .environment(envp)
            .directory(dir)
            .start();

should be the same as:

Runtime.exec(command)

Thanks dave_thompson_085 for comment

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

Java: convert seconds to minutes, hours and days

Thanks guys for all the help, I really appreciate but I actually did some thinking and start doing some pseudo code and came up with this.

import java.util.Scanner;

public class Project {

public static void main(String[] args) {



//variable declaration  
Scanner scan = new Scanner(System.in);
final int MIN = 60, HRS = 3600, DYS = 84600;
int input, days, seconds, minutes, hours, rDays, rHours;

//input 
System.out.println("Enter amount of seconds!");
input = scan.nextInt();


//calculations
days = input/DYS;
rDays = input%DYS;
hours = rDays/HRS;
rHours = rDays%HRS;
minutes = rHours/MIN;
seconds = rHours%MIN;

//output
if (input >= DYS) {
    System.out.println(input + " seconds equals to " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= HRS && input < DYS) {
    System.out.println(input + " seconds equals to " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
}

else if (input >= MIN && input < HRS) {
    System.out.println(input + " seconds equals to " + minutes + " minutes " + seconds + " seconds");
}

else if (input < MIN) {
    System.out.println(input + " seconds equals to seconds");
}

scan.close();


}   

I know it looks really noobie but keep in mind I'm still new not just Java but programming entirely, and who knew pseudo code was actually really helpful.

Print number of keys in Redis

For getting count total number of keys, use below command:

127.0.0.1:6379> DBSIZE

Render HTML to PDF in Django site

Try the solution from Reportlab.

Download it and install it as usual with python setup.py install

You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.

Here is an usage example:

First define this function:

import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape


def render_to_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

Then you can use it like this:

def myview(request):
    #Retrieve data or whatever you need
    return render_to_pdf(
            'mytemplate.html',
            {
                'pagesize':'A4',
                'mylist': results,
            }
        )

The template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>My Title</title>
        <style type="text/css">
            @page {
                size: {{ pagesize }};
                margin: 1cm;
                @frame footer {
                    -pdf-frame-content: footerContent;
                    bottom: 0cm;
                    margin-left: 9cm;
                    margin-right: 9cm;
                    height: 1cm;
                }
            }
        </style>
    </head>
    <body>
        <div>
            {% for item in mylist %}
                RENDER MY CONTENT
            {% endfor %}
        </div>
        <div id="footerContent">
            {%block page_foot%}
                Page <pdf:pagenumber>
            {%endblock%}
        </div>
    </body>
</html>

Hope it helps.

How to convert color code into media.brush?

For simplicity you could create an extension:-

    public static SolidColorBrush ToSolidColorBrush(this string hex_code)
    {
        return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
    }

And then to use:-

 SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

jQuery Set Selected Option Using Next

$('#next').click( function(){
    $('#colored_background option:selected').next('option').attr('selected', 'selected');
    changeBackgroundColor();
});

Working at What is my favorite color?. Click on the arrows.

How to call a stored procedure from Java and JPA

The following works for me:

Query query = em.createNativeQuery("BEGIN VALIDACIONES_QPAI.RECALC_COMP_ASSEMBLY('X','X','X',0); END;");
query.executeUpdate();

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

How to print object array in JavaScript?

Emm... Why not to use something like this?

_x000D_
_x000D_
function displayArrayObjects(arrayObjects) {_x000D_
        var len = arrayObjects.length, text = "";_x000D_
_x000D_
        for (var i = 0; i < len; i++) {_x000D_
            var myObject = arrayObjects[i];_x000D_
            _x000D_
            for (var x in myObject) {_x000D_
                text += ( x + ": " + myObject[x] + " ");_x000D_
            }_x000D_
            text += "<br/>";_x000D_
        }_x000D_
_x000D_
        document.getElementById("message").innerHTML = text;_x000D_
    }_x000D_
            _x000D_
            _x000D_
            var lineChartData = [{_x000D_
                date: new Date(2009, 10, 2),_x000D_
                value: 5_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 25),_x000D_
                value: 30_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 26),_x000D_
                value: 72,_x000D_
                customBullet: "images/redstar.png"_x000D_
            }];_x000D_
_x000D_
            displayArrayObjects(lineChartData);
_x000D_
<h4 id="message"></h4>
_x000D_
_x000D_
_x000D_

result:

date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5 
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30 
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png 

jsfiddle

MySQL Great Circle Distance (Haversine formula)

 SELECT *, (  
    6371 * acos(cos(radians(search_lat)) * cos(radians(lat) ) *   
cos(radians(lng) - radians(search_lng)) + sin(radians(search_lat)) *         sin(radians(lat)))  
) AS distance  
FROM table  
WHERE lat != search_lat AND lng != search_lng AND distance < 25  
 ORDER BY distance  
FETCH 10 ONLY 

for distance of 25 km

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Configuring angularjs with eclipse IDE

Download angular js from this link and add as new software in eclipse http://oss.opensagres.fr/angularjs-eclipse/0.6.0/

Simplest way to detect a mobile device in PHP

In case you care about screen size you can store screen width and Height as cookie values if they do not exists yet and then make self page redirection.

Now you have cookies on client and server side and can use it to determine mobile phones, tablets and other devices

Here a quick example how you can do it with JavaScript. Warning! [this code contain pseudo code].

if (!getcookie("screen_size")) {
    var screen_width = screen.width;
    var screen_height = screen.height;
    setcookie("screen_size", screen_width+", " +screen_height);
    go2(geturl());
}

How to check if an object is an array?

A simple function for testing if an input value is an array is the following:

function isArray(value)
{
  return Object.prototype.toString.call(value) === '[object Array]';
}

This works cross browser, and with older browsers. This is pulled from T.J. Crowders' blog post

PHP: Get key from array?

If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.

How to move screen without moving cursor in Vim?

Sometimes it is useful to scroll the text with the K and J keys, so I have this "scroll mode" function in my .vimrc (also bound to zs).

See scroll_mode.vim.

Allow only pdf, doc, docx format for file upload?

var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

jquery animate background position

You cannot use simple jquery's Animate to do that as it involves 2 values.

To solve it just include Background Position Plugin and you can animate Backgrounds at will.

How to include duplicate keys in HashMap?

Use Map<Integer, List<String>>:

Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();

map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...

To add a new key/value pair in this map:

public void add(Integer key, String newValue) {
    List<String> currentValue = map.get(key);
    if (currentValue == null) {
        currentValue = new ArrayList<String>();
        map.put(key, currentValue);
    }
    currentValue.add(newValue);
}

CSV in Python adding an extra carriage return, on Windows

You can introduce the lineterminator='\n' parameter in the csv writer command.

import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
    writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='',  lineterminator='\n')
    writer.writerow(['A1' , 'B1', 'C1'])
    writer.writerow(['A2' , 'B2', 'C2'])
    writer.writerow(['A3' , 'B3', 'C3'])

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Add the loading screen in starting of the android application

If the application is not doing anything in that 10 seconds, this will form a bad design only to make the user wait for 10 seconds doing nothing.

If there is something going on in that, or if you wish to implement 10 seconds delay splash screen,Here is the Code :

ProgressDialog pd;
pd = ProgressDialog.show(this,"Please Wait...", "Loading Application..", false, true);
pd.setCanceledOnTouchOutside(false);
Thread t = new Thread()
{ 
      @Override
      public void run()
      {
                try
                {
                    sleep(10000)  //Delay of 10 seconds
                } 
        catch (Exception e) {}
        handler.sendEmptyMessage(0);
        }
} ;
t.start();

//Handles the thread result of the Backup being executed.
private Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg) 
    {
        pd.dismiss();
        //Start the Next Activity here...

    }
};

Auto-center map with multiple markers in Google Maps API v3

This work for me in Angular 9:

  import {GoogleMap, GoogleMapsModule} from "@angular/google-maps";
  @ViewChild('Map') Map: GoogleMap; /* Element Map */

  locations = [
   { lat: 7.423568, lng: 80.462287 },
   { lat: 7.532321, lng: 81.021187 },
   { lat: 6.117010, lng: 80.126269 }
  ];

  constructor() {
   var bounds = new google.maps.LatLngBounds();
    setTimeout(() => {
     for (let u in this.locations) {
      var marker = new google.maps.Marker({
       position: new google.maps.LatLng(this.locations[u].lat, 
       this.locations[u].lng),
      });
      bounds.extend(marker.getPosition());
     }

     this.Map.fitBounds(bounds)
    }, 200)
  }

And it automatically centers the map according to the indicated positions.

Result:

enter image description here

Setting the character encoding in form submit for Internet Explorer

If you have any access to the server at all, convert its processing to UTF-8. The art of submitting non-UTF-8 forms is a long and sorry story; this document about forms and i18n may be of interest. I understand you do not seem to care about international support; you can always convert the UTF-8 data to html entities to make sure it stays Latin-1.

How to create NSIndexPath for TableView

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Count textarea characters

    $(document).ready(function(){ 
    $('#characterLeft').text('140 characters left');
    $('#message').keydown(function () {
        var max = 140;
        var len = $(this).val().length;
        if (len >= max) {
            $('#characterLeft').text('You have reached the limit');
            $('#characterLeft').addClass('red');
            $('#btnSubmit').addClass('disabled');            
        } 
        else {
            var ch = max - len;
            $('#characterLeft').text(ch + ' characters left');
            $('#btnSubmit').removeClass('disabled');
            $('#characterLeft').removeClass('red');            
        }
    });    
});

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

How to set time to midnight for current day?

Try this:

DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
   .AddSeconds(-DateTime.Now.Second);

Output will be like:

07/29/2015 00:00:00

\n or \n in php echo not print

PHP only interprets escaped characters (with the exception of the escaped backslash \\ and the escaped single quote \') when in double quotes (")

This works (results in a newline):

"\n"

This does not result in a newline:

'\n'

How do I make a simple makefile for gcc on Linux?

The simplest make file can be

all : test

test : test.o
        gcc -o test test.o 

test.o : test.c
        gcc -c test.c

clean :
        rm test *.o

initialize a const array in a class initializer in C++

It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).

How do I clone into a non-empty directory?

I had a similar problem with a new Apache web directory (account created with WHM) that I planned to use as a staging web server. I needed to initially clone my new project with the code base there and periodically deploy changes by pulling from repository.

The problem was that the account already contained web server files like:

.bash_history
.bash_logout
.bash_profile
.bashrc
.contactemail
.cpanel/
...

...that I did not want to either delete or commit to my repository. I needed them to just stay there unstaged and untracked.

What I did:

I went to my web folder (existing_folder):

cd /home/existing_folder

and then:

git init
git remote add origin PATH/TO/REPO
git pull origin master
git status

It displayed (as expected) a list of many not staged files - those that already existed initially from my cPanel web account.

Then, thanks to this article, I just added the list of those files to:

**.git/info/exclude**

This file, almost like the .gitignore file, allows you to ignore files from being staged. After this I had nothing to commit in the .git/ directory - it works like a personal .gitignore that no one else can see.

Now checking git status returns:

On branch master
nothing to commit, working tree clean

Now I can deploy changes to this web server by simply pulling from my git repository. Hope this helps some web developers to easily create a staging server.

How to correctly use the ASP.NET FileUpload control

My solution in code behind was:

System.Web.UI.WebControls.FileUpload fileUpload;

I don't know why, but when you are using FileUpload without System.Web.UI.WebControls it is referencing to YourProject.FileUpload not System.Web.UI.WebControls.FileUpload.

How to move table from one tablespace to another in oracle 11g

Try this:-

ALTER TABLE <TABLE NAME to be moved> MOVE TABLESPACE <destination TABLESPACE NAME>

Very nice suggestion from IVAN in comments so thought to add in my answer

Note: this will invalidate all table's indexes. So this command is usually followed by

alter index <owner>."<index_name>" rebuild;

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

Detecting user leaving page with react-router

You can use this prompt.

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Prompt } from "react-router-dom";

function PreventingTransitionsExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Form</Link>
          </li>
          <li>
            <Link to="/one">One</Link>
          </li>
          <li>
            <Link to="/two">Two</Link>
          </li>
        </ul>
        <Route path="/" exact component={Form} />
        <Route path="/one" render={() => <h3>One</h3>} />
        <Route path="/two" render={() => <h3>Two</h3>} />
      </div>
    </Router>
  );
}

class Form extends Component {
  state = { isBlocking: false };

  render() {
    let { isBlocking } = this.state;

    return (
      <form
        onSubmit={event => {
          event.preventDefault();
          event.target.reset();
          this.setState({
            isBlocking: false
          });
        }}
      >
        <Prompt
          when={isBlocking}
          message={location =>
            `Are you sure you want to go to ${location.pathname}`
          }
        />

        <p>
          Blocking?{" "}
          {isBlocking ? "Yes, click a link or the back button" : "Nope"}
        </p>

        <p>
          <input
            size="50"
            placeholder="type something to block transitions"
            onChange={event => {
              this.setState({
                isBlocking: event.target.value.length > 0
              });
            }}
          />
        </p>

        <p>
          <button>Submit to stop blocking</button>
        </p>
      </form>
    );
  }
}

export default PreventingTransitionsExample;

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

How to swap two variables in JavaScript

let a = 2, b = 4;
[b, a] = [a, b];

a more verbose approach would be

let a = 2, b = 4;
a = [a, b];
b = a[0];
a = a[1];

Select mysql query between date?

select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()

or using >= and <= :

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:

SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name 
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)

I haven't executed it, so there may be a syntax error or two there.

@selector() in Swift?

Also, if your (Swift) class does not descend from an Objective-C class, then you must have a colon at the end of the target method name string and you must use the @objc property with your target method e.g.

var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))

@objc func method() {
    // Something cool here   
} 

otherwise you will get a "Unrecognised Selector" error at runtime.

Generics in C#, using type of a variable as parameter

You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.

In other words, after compilation,

DoesEntityExist<int>

is a different type to

DoesEntityExist<string>

This is how the compiler is able to enfore compile-time type safety.

For the scenario you describe, you should pass the type as an argument that can be examined at run time.

The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.

Where to find Application Loader app in Mac?

Now you can upload your app binary with the Transporter app.

You can download Transporter from Mac AppStore Here

Here apple mentioned its used for uploading.

How can I express that two values are not equal to eachother?

Just put a '!' in front of the boolean expression

Difference between OData and REST web services

From the OData documentation:

The OData Protocol is an application-level protocol for interacting with data via RESTful web services.

...

The OData Protocol is different from other REST-based web service approaches in that it provides a uniform way to describe both the data and the data model.

How to use the CancellationToken property?

You have to pass the CancellationToken to the Task, which will periodically monitors the token to see whether cancellation is requested.

// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;  

// Task need to be cancelled with CancellationToken 
Task task = Task.Run(async () => {     
  while(!token.IsCancellationRequested) {
      Console.Write("*");         
      await Task.Delay(1000);
  }
}, token);

Console.WriteLine("Press enter to stop the task"); 
Console.ReadLine(); 
cancellationTokenSource.Cancel(); 

In this case, the operation will end when cancellation is requested and the Task will have a RanToCompletion state. If you want to be acknowledged that your task has been cancelled, you have to use ThrowIfCancellationRequested to throw an OperationCanceledException exception.

Task task = Task.Run(async () =>             
{                 
    while (!token.IsCancellationRequested) {
         Console.Write("*");                      
         await Task.Delay(1000);                
    }           
    token.ThrowIfCancellationRequested();               
}, token)
.ContinueWith(t =>
 {
      t.Exception?.Handle(e => true);
      Console.WriteLine("You have canceled the task");
 },TaskContinuationOptions.OnlyOnCanceled);  
 
Console.WriteLine("Press enter to stop the task");                 
Console.ReadLine();                 
cancellationTokenSource.Cancel();                 
task.Wait(); 

Hope this helps to understand better.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

How to initialize an array in angular2 and typescript

you can create and initialize array of any object like this.

hero:Hero[]=[];

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

How do I pass a datetime value as a URI parameter in asp.net mvc?

i realize it works after adding a slash behind like so

mysite/Controller/Action/21-9-2009 10:20/

Remove carriage return in Unix

The simplest way on Linux is, in my humble opinion,

sed -i 's/\r$//g' <filename>

The strong quotes around the substitution operator 's/\r//' are essential. Without them the shell will interpret \r as an escape+r and reduce it to a plain r, and remove all lower case r. That's why the answer given above in 2009 by Rob doesn't work.

And adding the /g modifier ensures that even multiple \r will be removed, and not only the first one.

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

Find Java classes implementing an interface

Package Level Annotations

I know this question has already been answered a long time ago but another solution to this problem is to use Package Level Annotations.

While its pretty hard to go find all the classes in the JVM its actually pretty easy to browse the package hierarchy.

Package[] ps = Package.getPackages();
for (Package p : ps) {
  MyAno a = p.getAnnotation(MyAno.class)
  // Recursively descend
}

Then just make your annotation have an argument of an array of Class. Then in your package-info.java for a particular package put the MyAno.

I'll add more details (code) if people are interested but most probably get the idea.

MetaInf Service Loader

To add to @erickson answer you can also use the service loader approach. Kohsuke has an awesome way of generating the the required META-INF stuff you need for the service loader approach:

http://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html

How to declare an array of strings in C++?

Declare an array of strings in C++ like this : char array_of_strings[][]

For example : char array_of_strings[200][8192];

will hold 200 strings, each string having the size 8kb or 8192 bytes.

use strcpy(line[i],tempBuffer); to put data in the array of strings.

Set background image on grid in WPF using C#

I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.

  ImageBrush myBrush = new ImageBrush();
  Image image = new Image();
  image.Source = new BitmapImage(
      new Uri(
         "pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
  myBrush.ImageSource = image.Source;
  Grid grid = new Grid();
  grid.Background = myBrush;          

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

In my case, I got this while overloading

ostream & operator << (ostream &out, const MyClass &obj)

and forgot to return out. In other systems this just generates a warning, but on macos it also generated an error (although it seems to print correctly).

The error was resolved by adding the correct return value. In my case, adding the -mmacosx-version-min flag had no effect.

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

adding a datatable in a dataset

I assume that you haven't set the TableName property of the DataTable, for example via constructor:

var tbl = new DataTable("dtImage");

If you don't provide a name, it will be automatically created with "Table1", the next table will get "Table2" and so on.

Then the solution would be to provide the TableName and then check with Contains(nameOfTable).

To clarify it: You'll get an ArgumentException if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException if there's already a DataTable in the DataSet with the same name(not case-sensitive).

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

How to get the exact local time of client?

Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api

_x000D_
_x000D_
fetch("https://worldtimeapi.org/api/ip")
  .then(response => response.json())
  .then(data => console.log(data.dst,data.datetime));
_x000D_
_x000D_
_x000D_

SQL Server: Cannot insert an explicit value into a timestamp column

How to insert current time into a timestamp with SQL Server:

In newer versions of SQL Server, timestamp is renamed to RowVersion. Rightly so, because timestamp name is misleading.

SQL Server's timestamp IS NOT set by the user and does not represent a date or a time. Timestamp is only good for making sure a row hasn't changed since it's been read.

If you want to store a date or a time, do not use timestamp, you must use one of the other datatypes, like for example datetime, smalldatetime, date, time or DATETIME2

For example:

create table wtf (
    id INT,
    leet timestamp
)

insert into wtf (id) values (15)

select * from wtf

15    0x00000000000007D3 

'timestamp' in mssql is some kind of internal datatype. Casting that number to datetime produces a nonsense number.

No templates in Visual Studio 2017

If you have installed .NET desktop development and still you can't see the templates, then VS is probably getting the templates from your custom templates folder and not installed.

To fix that, copy the installed templates folder to custom.

This is your "installed" folder

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates

This is your "custom" folder

C:\Users[your username]\Documents\Visual Studio\2017\Templates\ProjectTemplates

Typically this happens when you are at the office and you are running VS as an administrator and visual studio is confused how to merge both of them and if you notice they don't have the same folder structure and folder names.. One is CSHARP and the other C#....

I didn't have the same problem when I installed VS 2017 community edition at home though. This happened when I installed visual studio 2017 "enterprise" edition.

CSS selector for first element with class

I got this one in my project.

_x000D_
_x000D_
div > .b ~ .b:not(:first-child) {_x000D_
 background: none;_x000D_
}_x000D_
div > .b {_x000D_
    background: red;_x000D_
}
_x000D_
<div>_x000D_
      <p class="a">The first paragraph.</p>_x000D_
      <p class="a">The second paragraph.</p>_x000D_
      <p class="b">The third paragraph.</p>_x000D_
      <p class="b">The fourth paragraph.</p>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to downgrade tensorflow, multiple versions possible?

You can try to use the options of --no-cache-dir together with -I to overwrite the cache of the previous version and install the new version. For example:

pip3 install --no-cache-dir -I tensorflow==1.1

Then use the following command to check the version of tensorflow:

python3 -c ‘import tensorflow as tf; print(tf.__version__)’

It should show the right version got installed.

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

How to keep an iPhone app running on background fully operational

Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

I infer from the opening comment that the use case is delineating whether a response is HTML or JSON. In which case, when you do receive JSON, you probably ought to be parsing it and handling invalid JSON at some point in your code anyway. Aside from anything, I imagine you would like to be informed by your browser should JSON be expected but invalid JSON received (as will users by proxy of some meaningful error message)!

Doing a full regex for JSON is unnecessary therefore (as it would be - in my experience - for most use-cases). You would probably be better off using something like the below:

function (someString) {
  // test string is opened with curly brace or machine bracket
  if (someString.trim().search(/^(\[|\{){1}/) > -1) {
    try { // it is, so now let's see if its valid JSON
      var myJson = JSON.parse(someString);
      // yep, we're working with valid JSON
    } catch (e) {
      // nope, we got what we thought was JSON, it isn't; let's handle it.
    }
  } else {
    // nope, we're working with non-json, no need to parse it fully
  }
}

that should save you having to exception handle valid non-JSON code and take care of duff json at the same time.

DataTables: Cannot read property style of undefined

I had this issue when i set colspan in table header. So my table was:

        <thead>
            <tr>
                <th colspan="2">Expenses</th>

                <th colspan="2">Income</th>

                <th>Profit/Loss</th>
            </tr>
        </thead>

Then once i change it to:

        <thead>
            <tr>
                <th>Expenses</th>
                <th></th>
                <th>Income</th>
                <th></th>
                <th>Profit/Loss</th>
            </tr>
        </thead>

Everything worked just fine.

C++ Vector of pointers

It means something like this:

std::vector<Movie *> movies;

Then you add to the vector as you read lines:

movies.push_back(new Movie(...));

Remember to delete all of the Movie* objects once you are done with the vector.

Why can't radio buttons be "readonly"?

I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.

<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>

For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.

<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>

This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.

Fragment pressing back button

You can use getFragmentManager().popBackStack() in basic Fragment to go back.

How can I symlink a file in Linux?

There are two types of links:

symbolic links: Refer to a symbolic path indicating the abstract location of another file

hard links: Refer to the specific location of physical data.

In your case symlinks:

ln -s source target

you can refer to http://man7.org/linux/man-pages/man7/symlink.7.html

you can create too hard links

A hard link to a file is indistinguishable from the original directory entry; any changes to a file are effectively independent of the name used to reference the file. Hard links may not normally refer to directories and may not span file systems.

ln source link

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

How to convert seconds to time format?

just one small additional example

requested time in miliseconds

    // ms2time( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array
    function ms2time($ms){
        $return = array();
        // ms
        $return['ms'] = (int) number_format( ($ms - (int) $ms), 2, '', '');
        $seconds = (int) $ms;
        unset($ms);

        if ($seconds%60 > 0){
            $return['s'] = $seconds%60;
        } else {
            $return['s'] = 0;
        }

        if ( ($minutes = intval($seconds/60))){
            $return['m'] = $minutes;
        }

        if (isset($return['m'])){
            $return['h'] = intval($return['m'] / 60);
            $return['m']  = $return['m'] % 60; 
        }


        if (isset($return['h'])){
            $return['d'] = intval($return['h'] / 24);
            $return['h']  = $return['h'] % 24; 
        }

        if (isset($return['d']))
            $return['mo'] = intval($return['d'] / 30);

        foreach($return as $k=>$v){
            if ($v == 0)
                unset($return[$k]);
        }

        return $return;
    }

    // ms2time2string( (microtime(true) - ( time() - rand(0,1000000) ) ) );
    // return array     
    function ms2time2string($ms){
        $array = array(
            'ms' => 'ms',
            's'  => 'seconds',
            'm'  => 'minutes',
            'h'  => 'hours',
            'd'  => 'days',
            'mo' => 'month',
        );


        if ( ( $return = ms2time($ms) )  && count($ms) > 0){

            foreach($return as $key=>$data){
                $return[$key] = $data .' '.$array[$key];
            }

        }
        return implode(" ", array_reverse($return));
    }

How do ACID and database transactions work?

ACID are desirable properties of any transaction processing engine.

A DBMS is (if it is any good) a particular kind of transaction processing engine that exposes, usually to a very large extent but not quite entirely, those properties.

But other engines exist that can also expose those properties. The kind of software that used to be called "TP monitors" being a case in point (nowadays' equivalent mostly being web servers).

Such TP monitors can access resources other than a DBMS (e.g. a printer), and still guarantee ACID toward their users. As an example of what ACID might mean when a printer is involved in a transaction:

  • Atomicity: an entire document gets printed or nothing at all
  • Consistency: at end-of-transaction, the paper feed is positioned at top-of-page
  • Isolation: no two documents get mixed up while printing
  • Durability: the printer can guarantee that it was not "printing" with empty cartridges.

DATEDIFF function in Oracle

You can simply subtract two dates. You have to cast it first, using to_date:

select to_date('2000-01-01', 'yyyy-MM-dd')
       - to_date('2000-01-02', 'yyyy-MM-dd')
       datediff
from   dual
;

The result is in days, to the difference of these two dates is -1 (you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.

JavaScript - get the first day of the week from current date

var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));

This will work well.

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Remove the WebDAV works perfectly for my case:

<modules>
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="WebDAV" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" 
       type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

it always better to solve the problem through the web.config instead of going to fix it through the iis or machine.config to grantee it wouldn't happen if the app hosted at another machine

How to save username and password in Git?

In that case you need git credential helper to tell git to remember your GitHub password and username by using following command line :

git config --global credential.helper wincred 

and if you are using repo using SSH key then you need SSH key to authenticate.

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

How to import a class from default package

From some where I found below :-

In fact, you can.

Using reflections API you can access any class so far. At least I was able to :)

Class fooClass = Class.forName("FooBar");
Method fooMethod =
    fooClass.getMethod("fooMethod", new Class[] { String.class });

String fooReturned =
    (String) fooMethod.invoke(fooClass.newInstance(), "I did it");