Programs & Examples On #Wikitext

From [MediaWiki.org](http://www.mediawiki.org/wiki/Wikitext): Wikitext is a document written in a wiki markup language.

Find and replace in file and overwrite file doesn't work, it empties the file

You should try using the option -i for in-place editing.

Sending a JSON to server and retrieving a JSON in return, without JQuery

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

How to return multiple objects from a Java method?

Alternatively, in situations where I want to return a number of things from a method I will sometimes use a callback mechanism instead of a container. This works very well in situations where I cannot specify ahead of time just how many objects will be generated.

With your particular problem, it would look something like this:

public class ResultsConsumer implements ResultsGenerator.ResultsCallback
{
    public void handleResult( String name, Object value )
    {
        ... 
    }
}

public class ResultsGenerator
{
    public interface ResultsCallback
    {
        void handleResult( String aName, Object aValue );
    }

    public void generateResults( ResultsGenerator.ResultsCallback aCallback )
    {
        Object value = null;
        String name = null;

        ...

        aCallback.handleResult( name, value );
    }
}

Using context in a fragment

Previously I'm using onAttach (Activity activity) to get context in Fragment

Problem

The onAttach (Activity activity) method was deprecated in API level 23.

Solution

Now to get context in Fragment we can use onAttach (Context context)

onAttach (Context context)

  • Called when a fragment is first attached to its context. onCreate(Bundle) will be called after this.

Documentation

/**
 * Called when a fragment is first attached to its context.
 * {@link #onCreate(Bundle)} will be called after this.
 */
@CallSuper
public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

SAMPLE CODE

public class FirstFragment extends Fragment {


    private Context mContext;
    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rooView=inflater.inflate(R.layout.fragment_first, container, false);

        Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
        // Inflate the layout for this fragment
        return rooView;
    }

}

NOTE

We can also use getActivity() to get context in Fragments but getActivity() can return null if the your fragment is not currently attached to a parent activity,

Concat strings by & and + in VB.Net

You can write '&' to add string and integer :

processDetails=objProcess.ProcessId & ":" & objProcess.name
message = msgbox(processDetails,16,"Details")

output will be:

5577:wscript.exe

Authentication failed because remote party has closed the transport stream

I ran into the same error message while using the ChargifyNET.dll to communicate with the Chargify API. Adding chargify.ProtocolType = SecurityProtocolType.Tls12; to the configuration solved the problem for me.

Here is the complete code snippet:

public ChargifyConnect GetChargifyConnect()
{
    var chargify = new ChargifyConnect();
    chargify.apiKey = ConfigurationManager.AppSettings["Chargify.apiKey"];
    chargify.Password = ConfigurationManager.AppSettings["Chargify.apiPassword"];
    chargify.URL = ConfigurationManager.AppSettings["Chargify.url"];

    // Without this an error will be thrown.
    chargify.ProtocolType = SecurityProtocolType.Tls12;

    return chargify;
}

Getting list of pixel values from PIL

pixVals = list(pilImg.getdata())

output is a list of all RGB values from the picture:

[(248, 246, 247), (246, 248, 247), (244, 248, 247), (244, 248, 247), (246, 248, 247), (248, 246, 247), (250, 246, 247), (251, 245, 247), (253, 244, 247), (254, 243, 247)]

HTML input textbox with a width of 100% overflows table cells

Width value doesn't take into account border or padding:

http://www.htmldog.com/reference/cssproperties/width/

You get 2px of padding in each side, plus 1px of border in each side.
100% + 2*(2px +1px) = 100% + 6px, which is more than the 100% child-content the parent td has.

You have the option of:

  • Either setting box-sizing: border-box; as per @pricco's answer;
  • Or using 0 margin and padding (avoiding the extra size).

How to add an image to the emulator gallery in android studio?

I'd like to complement Mithilesh Izardar's answer:

Indeed the best approach is simply to "Drag and Drop", which afterwards you can find the files in the emulator at Settings ? Storage ? Internal Storage ? Explore ? Download (API 25). The problem for me was that after following these steps the pics weren't appearing neither in the "Gallery" nor in the "Downloads" (by simply clicking the "Downloads" icon).

The reason for this is because by default everything in the emulator has no permissions...so all you gotta do is give the "Gallery" storage permission: Settings ? Apps ? Gallery ? Permissions (API 25)

Ps: If you just copied the pictures, the new ones won't show up right away. You should either restart the emulator, or remount the sdcard (at Settings ? Storage unmount the sdcard by clicking the eject icon then remount it)

How do I get column names to print in this C# program?

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        ColumnName = column.ColumnName;
        ColumnData = row[column].ToString();
    }
}

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Binding to static property

In .NET 4.5 it's possible to bind to static properties, read more

You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:

public static event EventHandler MyPropertyChanged; 
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; 

Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.

Round up to Second Decimal Place in Python

Here is a more general one-liner that works for any digits:

import math
def ceil(number, digits) -> float: return math.ceil((10.0 ** digits) * number) / (10.0 ** digits)

Example usage:

>>> ceil(1.111111, 2)
1.12

Caveat: as stated by nimeshkiranverma:

>>> ceil(1.11, 2) 
1.12  #Because: 1.11 * 100.0 has value 111.00000000000001

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

iOS - Ensure execution on main thread

there any rule I can follow to be sure that my app executes my own code just in the main thread?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

If you want to be really sure, you can do things like

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)

Change directory in Node.js command prompt

That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.

In Windows, there should be a Node.js command prompt in your Start menu or start screen:

Windows Search for node.js

Which will open a command prompt window that looks like this:

Node.js command prompt window

From there you can switch directories using the cd command.

from unix timestamp to datetime

The /Date(ms + timezone)/ is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.

Set background colour of cell to RGB value of data in cell

To color each cell based on its current integer value, the following should work, if you have a recent version of Excel. (Older versions don't handle rgb as well)

Sub Colourise()
'
' Colourise Macro
'
' Colours all selected cells, based on their current integer rgb value
' For e.g. (it's a bit backward from what you might expect)
' 255 = #ff0000 = red
' 256*255 = #00ff00 = green
' 256*256*255 #0000ff = blue
' 255 + 256*256*255 #ff00ff = magenta
' and so on...
'
' Keyboard Shortcut: Ctrl+Shift+C (or whatever you want to set it to)
'
  For Each cell In Selection
    If WorksheetFunction.IsNumber(cell) Then
      cell.Interior.Color = cell.Value
    End If
  Next cell
End Sub

If instead of a number you have a string then you can split the string into three numbers and combine them using rgb().

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

Format number to always show 2 decimal places

Extend Math object with precision method

_x000D_
_x000D_
Object.defineProperty(Math, 'precision',{_x000D_
   value: function (value,precision,type){_x000D_
             var v = parseFloat(value),_x000D_
                 p = Math.max(precision,0)||0,_x000D_
                 t = type||'round';_x000D_
              return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);_x000D_
          }_x000D_
    });_x000D_
_x000D_
console.log(_x000D_
    Math.precision(3.1,3), // round 3 digits _x000D_
    Math.precision(0.12345,2,'ceil'), // ceil 2 digits_x000D_
    Math.precision(1.1) // integer part_x000D_
)
_x000D_
_x000D_
_x000D_

Delete default value of an input text on click

Why remove value? its useful, but why not try CSS

input[submit] {
   font-size: 0 !important;
}

Value is important to check & validate ur PHP

How to return a class object by reference in C++?

Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).

The trick is this:

  1. A line A a = b.make(); is internally converted to a constructor of A, i.e. as if you had written A a(b.make());.
  2. Now b.make() should result a new class, with a callback function.
  3. This whole thing can be fine handled only by classes, without any template.

Here is my minimal example. Check only the main(), as you can see it is simple. The internals aren't.

From the viewpoint of the speed: the size of a Factory::Mediator class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.

#include <stdio.h>

class Factory {
  public:
    class Mediator;

    class Result {
      public:
        Result() {
          printf ("Factory::Result::Result()\n");
        };

        Result(Mediator fm) {
          printf ("Factory::Result::Result(Mediator)\n");
          fm.call(this);
        };
    };

    typedef void (*MakeMethod)(Factory* factory, Result* result);

    class Mediator {
      private:
        Factory* factory;
        MakeMethod makeMethod;

      public:
        Mediator(Factory* factory, MakeMethod makeMethod) {
          printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
          this->factory = factory;
          this->makeMethod = makeMethod;
        };

        void call(Result* result) {
          printf ("Factory::Mediator::call(Result*)\n");
          (*makeMethod)(factory, result);
        };
    };
};

class A;

class B : private Factory {
  private:
    int v;

  public:
    B(int v) {
      printf ("B::B()\n");
      this->v = v;
    };

    int getV() const {
      printf ("B::getV()\n");
      return v;
    };

    static void makeCb(Factory* f, Factory::Result* a);

    Factory::Mediator make() {
      printf ("Factory::Mediator B::make()\n");
      return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
    };
};

class A : private Factory::Result {
  friend class B;

  private:
    int v;

  public:
    A() {
      printf ("A::A()\n");
      v = 0;
    };

    A(Factory::Mediator fm) : Factory::Result(fm) {
      printf ("A::A(Factory::Mediator)\n");
    };

    int getV() const {
      printf ("A::getV()\n");
      return v;
    };

    void setV(int v) {
      printf ("A::setV(%i)\n", v);
      this->v = v;
    };
};

void B::makeCb(Factory* f, Factory::Result* r) {
      printf ("B::makeCb(Factory*, Factory::Result*)\n");
      B* b = static_cast<B*>(f);
      A* a = static_cast<A*>(r);
      a->setV(b->getV()+1);
    };

int main(int argc, char **argv) {
  B b(42);
  A a = b.make();
  printf ("a.v = %i\n", a.getV());
  return 0;
}

Is it not possible to define multiple constructors in Python?

If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance-based approach mentioned in another answer, and instead use keyword arguments.

If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:

class C(object):

    def __init__(self, fd):
        # Assume fd is a file-like object.
        self.fd = fd

    @classmethod
    def fromfilename(cls, name):
        return cls(open(name, 'rb'))

# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')

Notice all those classmethods still go through the same __init__, but using classmethods can be much more convenient than having to remember what combinations of keyword arguments to __init__ work.

isinstance is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file), because there are many file-like objects that do not subclass file (like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.

How do I get rid of the "cannot empty the clipboard" error?

I copied a picture (instead of text) that I had in my excel 2007 file and that solved the problem for me. The picture copied to the (then empty) clipboard. I could then copy cells normally even after clearing the clipboard of the picture. I think a graph object should also do the trick.

How to dynamically change a web page's title?

The simplest way is to delete <title> tag from index.html, and include

<head>
<title> Website - The page </title></head>

in every page in the web. Spiders will find this and will be shown in search results :)

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

it's also a good thing to make sure you have the right import

I had an issue like that and I found out that the bean was using

    javax.faces.view.ViewScoped;
                 ^

instead of

    javax.faces.bean.ViewScoped;
                 ^

OpenSSL and error in reading openssl.conf file

I just had a similar error using the openssl.exe from the Apache for windows bin folder. I had the -config flag specified by had a typo in the path of the openssl.cnf file. I think you'll find that

openssl req -config C:\OpenSSL\bin\openssl.conf -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem

should be

openssl req -config "C:\OpenSSL\bin\openssl.cnf" -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem

Note: the conf should probably be cnf.

Extract every nth element of a vector

Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:

foo[ c( rep(FALSE, 5), TRUE ) ]

What is the difference between a static and a non-static initialization code block

You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.

You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..

A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.

What is the best/safest way to reinstall Homebrew?

Process is to clean up and then reinstall with the following commands:

rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install )"

Notes:

Get changes from master into branch in Git

You have a couple options. git rebase master aqonto the branch which will keep the commit names, but DO NOT REBASE if this is a remote branch. You can git merge master aq if you don't care about keeping the commit names. If you want to keep the commit names and it is a remote branch git cherry-pick <commit hash> the commits onto your branch.

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

How get an apostrophe in a string in javascript

You can try the following:

theAnchorText = "I'm home";

OR

theAnchorText = 'I\'m home';

How can I get CMake to find my alternative Boost installation?

After digging around in CMake and experimenting, I determined that CMake was unhappy with the fact that all of my Boost libraries were contained in /usr/local/lib/boost and not /usr/local/lib. Once I soft-linked them back out, the build worked.

Java Garbage Collection Log messages

I just wanted to mention that one can get the detailed GC log with the

-XX:+PrintGCDetails 

parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

Example usage:

java -Xloggc:./memory.log -XX:+PrintGCDetails Memory

To visualize the data better you can try gcviewer (a more recent version can be found on github).

Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

How to call another controller Action From a controller in Mvc

Your sample looks like psuedo code. You need to return the result of RedirectToAction:

return RedirectToAction("B", 
                        "FileUploadMsgView",
                        new { FileUploadMsg = "File uploaded successfully" });

jQuery - trapping tab select event

This post shows a complete working HTML file as an example of triggering code to run when a tab is clicked. The .on() method is now the way that jQuery suggests that you handle events.

jQuery development history

To make something happen when the user clicks a tab can be done by giving the list element an id.

<li id="list">

Then referring to the id.

$("#list").on("click", function() {
 alert("Tab Clicked!");
});

Make sure that you are using a current version of the jQuery api. Referencing the jQuery api from Google, you can get the link here:

https://developers.google.com/speed/libraries/devguide#jquery

Here is a complete working copy of a tabbed page that triggers an alert when the horizontal tab 1 is clicked.

<!-- This HTML doc is modified from an example by:  -->
<!-- http://keith-wood.name/uiTabs.html#tabs-nested -->

<head>
<meta charset="utf-8">
<title>TabDemo</title>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/south-street/jquery-ui.css">

<style>
pre {
clear: none;
}
div.showCode {
margin-left: 8em;
}
.tabs {
margin-top: 0.5em;
}
.ui-tabs { 
padding: 0.2em; 
background: url(http://code.jquery.com/ui/1.8.23/themes/south-street/images/ui-bg_highlight-hard_100_f5f3e5_1x100.png) repeat-x scroll 50% top #F5F3E5; 
border-width: 1px; 
} 
.ui-tabs .ui-tabs-nav { 
padding-left: 0.2em; 
background: url(http://code.jquery.com/ui/1.8.23/themes/south-street/images/ui-bg_gloss-wave_100_ece8da_500x100.png) repeat-x scroll 50% 50% #ECE8DA; 
border: 1px solid #D4CCB0;
-moz-border-radius: 6px; 
-webkit-border-radius: 6px; 
border-radius: 6px; 
} 
.ui-tabs-nav .ui-state-active {
border-color: #D4CCB0;
}
.ui-tabs .ui-tabs-panel { 
background: transparent; 
border-width: 0px; 
}
.ui-tabs-panel p {
margin-top: 0em;
}
#minImage {
margin-left: 6.5em;
}
#minImage img {
padding: 2px;
border: 2px solid #448844;
vertical-align: bottom;
}

#tabs-nested > .ui-tabs-panel {
padding: 0em;
}
#tabs-nested-left {
position: relative;
padding-left: 6.5em;
}
#tabs-nested-left .ui-tabs-nav {
position: absolute;
left: 0.25em;
top: 0.25em;
bottom: 0.25em;
width: 6em;
padding: 0.2em 0 0.2em 0.2em;
}
#tabs-nested-left .ui-tabs-nav li {
right: 1px;
width: 100%;
border-right: none;
border-bottom-width: 1px !important;
-moz-border-radius: 4px 0px 0px 4px;
-webkit-border-radius: 4px 0px 0px 4px;
border-radius: 4px 0px 0px 4px;
overflow: hidden;
}
#tabs-nested-left .ui-tabs-nav li.ui-tabs-selected,
#tabs-nested-left .ui-tabs-nav li.ui-state-active {
border-right: 1px solid transparent;
}
#tabs-nested-left .ui-tabs-nav li a {
float: right;
width: 100%;
text-align: right;
}
#tabs-nested-left > div {
height: 10em;
overflow: auto;
}
</pre>

</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>

<script>
    $(function() {
    $('article.tabs').tabs();
    });
</script>

</head>
<body>
<header role="banner">
    <h1>jQuery UI Tabs Styling</h1>
</header>

<section>

<article id="tabs-nested" class="tabs">
<script>
    $(document).ready(function(){
    $("#ForClick").on("click", function() {
        alert("Tab Clicked!");
    });
    });
</script>
<ul>
    <li id="ForClick"><a href="#tabs-nested-1">First</a></li>
    <li><a href="#tabs-nested-2">Second</a></li>
    <li><a href="#tabs-nested-3">Third</a></li>
</ul>
<div id="tabs-nested-1">
    <article id="tabs-nested-left" class="tabs">
        <ul>
            <li><a href="#tabs-nested-left-1">First</a></li>
            <li><a href="#tabs-nested-left-2">Second</a></li>
            <li><a href="#tabs-nested-left-3">Third</a></li>
        </ul>
        <div id="tabs-nested-left-1">
            <p>Nested tabs, horizontal then vertical.</p>


<form action="/sign" method="post">
  <div><textarea name="content" rows="5" cols="100"></textarea></div>
  <div><input type="submit" value="Sign Guestbook"></div>
</form>
        </div>
        <div id="tabs-nested-left-2">
            <p>Nested Left Two</p>
        </div>
        <div id="tabs-nested-left-3">
            <p>Nested Left Three</p>
        </div>
    </article>
</div>
<div id="tabs-nested-2">
    <p>Tab Two Main</p>
</div>
<div id="tabs-nested-3">
    <p>Tab Three Main</p>
</div>
</article>

</section>

</body>
</html>

How do I know the script file name in a Bash script?

With bash >= 3 the following works:

$ ./s
0 is: ./s
BASH_SOURCE is: ./s
$ . ./s
0 is: bash
BASH_SOURCE is: ./s

$ cat s
#!/bin/bash

printf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"

check if file exists in php

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( '/path/to/images/thumbnail.jpg' )).

Random number from a range in a Bash Script

According to the bash man page, $RANDOM is distributed between 0 and 32767; that is, it is an unsigned 15-bit value. Assuming $RANDOM is uniformly distributed, you can create a uniformly-distributed unsigned 30-bit integer as follows:

$(((RANDOM<<15)|RANDOM))

Since your range is not a power of 2, a simple modulo operation will only almost give you a uniform distribution, but with a 30-bit input range and a less-than-16-bit output range, as you have in your case, this should really be close enough:

PORT=$(( ((RANDOM<<15)|RANDOM) % 63001 + 2000 ))

How to use a different version of python during NPM install?

You can use --python option to npm like so:

npm install --python=python2.7

or set it to be used always:

npm config set python python2.7

Npm will in turn pass this option to node-gyp when needed.

(note: I'm the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )

How to call function of one php file from another php file and pass parameters to it?

you can write the function in a separate file (say common-functions.php) and include it wherever needed.

function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}

You can include common-functions.php in another file as below.

include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);

You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.

How to show full column content in a Spark Dataframe?

results.show(20,false) did the trick for me in Scala.

When should you use 'friend' in C++?

The short answer would be: use friend when it actually improves encapsulation. Improving readability and usability (operators << and >> are the canonical example) is also a good reason.

As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.

How could I convert data from string to long in c#

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value

Change URL and redirect using jQuery

tell you the true, I still don't get what you need, but

window.location(url);

should be

window.location = url;

a search on window.location reference will tell you that.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Oracle get previous day records

this

    SELECT field,datetime_field 
FROM database
WHERE datetime_field > (sysdate-1)

will work. The question is: is the 'datetime_field' has the same format as sysdate ? My way to handle that: use 'to_char()' function (only works in Oracle).

samples: previous day:

select your_column
from your_table
where to_char(sysdate-1, 'dd.mm.yyyy')

or

select extract(day from date_field)||'/'|| 
       extract(month from date_field)||'/'||
       extract(year from date_field)||'/'||
as mydate
from dual(or a_table)
where extract(day from date_field) = an_int_number and
      extract(month from date_field) = an_int_number and so on..

comparing date:

select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate, 'dd.mm.yyyy')

time range between yesterday and a day before yesterday:

select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-1, 'dd.mm.yyyy') and
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-2, 'dd.mm.yyyy')

other time range variation

select your_column
from your_table
where 
to_char(a_datetime_column, 'dd.mm.yyyy') is between to_char(sysdate-1, 'dd.mm.yyyy') 
and to_char(sysdate-2, 'dd.mm.yyyy')

How to Write text file Java

It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).

Formatting DataBinder.Eval data

Why not use the simpler syntax?

<asp:Label id="lblNewsDate" runat="server" Text='<%# Eval("publishedDate", "{0:dddd d MMMM}") %>'</label>

This is the template control "Eval" that takes in the expression and the string format:

protected internal string Eval(
string expression,
string format

)

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

How to call JavaScript function instead of href in HTML

<a href="#" onclick="javascript:ShowOld(2367,146986,2)">

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

how to specify new environment location for conda create

I ran into a similar situation. I did have access to a larger data drive. Depending on your situation, and the access you have to the server you can consider

ln -s /datavol/path/to/your/.conda /home/user/.conda

Then subsequent conda commands will put data to the symlinked dir in datavol

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Is the practice of returning a C++ reference variable evil?

You should return a reference to an existing object that isn't going away immediately, and where you don't intend any transfer of ownership.

Never return a reference to a local variable or some such, because it won't be there to be referenced.

You can return a reference to something independent of the function, which you don't expect the calling function to take the responsibility for deleting. This is the case for the typical operator[] function.

If you are creating something, you should return either a value or a pointer (regular or smart). You can return a value freely, since it's going into a variable or expression in the calling function. Never return a pointer to a local variable, since it will go away.

Apk location in New Android Studio

Click on Build-Build Bundles/Apks-Build Apk.

A notification will which shows app location when you click on 'locate' on the notification.

If you have already done creating apk, goto : C:\Users\\AndroidStudioProjects\\app\build\outputs\apk\debug

How can I get phone serial number (IMEI)

Use below code for IMEI:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();

Xcode doesn't see my iOS device but iTunes does

Ran into this issue having upgraded from XCode 9 to 10.1. No devices at all were appearing in XCode, despite performing all the steps listed in other answers.

For me the solution was to do a clean CMake build, deleting the old Xcode project files.

How to create separate AngularJS controller files?

Not so graceful, but the very much simple in implementation solution - using global variable.

In the "first" file:


window.myApp = angular.module("myApp", [])
....

in the "second" , "third", etc:


myApp.controller('MyController', function($scope) {
    .... 
    }); 

What is the difference between float and double?

When using floating point numbers you cannot trust that your local tests will be exactly the same as the tests that are done on the server side. The environment and the compiler are probably different on you local system and where the final tests are run. I have seen this problem many times before in some TopCoder competitions especially if you try to compare two floating point numbers.

sqlite database default time value 'now'

i believe you can use

CREATE TABLE test (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  t TIMESTAMP
  DEFAULT CURRENT_TIMESTAMP
);

as of version 3.1 (source)

How to parse dates in multiple formats using SimpleDateFormat

I was having multiple date formats into json, and was extracting csv with universal format. I looked multiple places, tried different ways, but at the end I'm able to convert with the following simple code.

private String getDate(String anyDateFormattedString) {
    @SuppressWarnings("deprecation")
    Date date = new Date(anyDateFormattedString);
    SimpleDateFormat dateFormat = new SimpleDateFormat(yourDesiredDateFormat);
        String convertedDate = dateFormat.format(date);
    return convertedDate;
}

Doctrine findBy 'does not equal'

There is no built-in method that allows what you intend to do.

You have to add a method to your repository, like this:

public function getWhatYouWant()
{
    $qb = $this->createQueryBuilder('u');
    $qb->where('u.id != :identifier')
       ->setParameter('identifier', 1);

    return $qb->getQuery()
          ->getResult();
}

Hope this helps.

Show tables, describe tables equivalent in redshift

Tomasz Tybulewicz answer is good way to go.

SELECT * FROM pg_table_def WHERE tablename = 'YOUR_TABLE_NAME' AND schemaname = 'YOUR_SCHEMA_NAME';

If schema name is not defined in search path , that query will show empty result. Please first check search path by below code.

SHOW SEARCH_PATH

If schema name is not defined in search path , you can reset search path.

SET SEARCH_PATH to '$user', public, YOUR_SCEHMA_NAME

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I had the same problem. Go to Project Properties -> Deployment Assemplbly and add jstl jar

how to configure config.inc.php to have a loginform in phpmyadmin

First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php) will display an identification form, asking for a login and password.

To get that form, you should not use :

$cfg['Servers'][$i]['auth_type'] = 'config';

But you should use :

$cfg['Servers'][$i]['auth_type'] = 'cookie';

(At least, that's what I have on a server which prompts for login/password, using a form)


For more informations, you can take a look at the documentation :

'config' authentication ($auth_type = 'config') is the plain old way: username and password are stored in config.inc.php.

'cookie' authentication mode ($auth_type = 'cookie') as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.

Java "user.dir" property - what exactly does it mean?

System.getProperty("user.dir") fetches the directory or path of the workspace for the current project

How to change the application launcher icon on Flutter?

Follow these steps:-

1. Add dependencies of flutter_luncher_icons in pubspec.yaml file.You can find this plugin from here.

2. Add your required images in asstes folder and pubspec.yaml file as below .

pubspec.yaml

name: NewsApi.org
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
      sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.1
  fluttertoast: ^7.1.6
  toast: ^0.1.5
  flutter_launcher_icons: ^0.8.0




dev_dependencies:
  flutter_test:
    sdk: flutter

flutter_icons:
  image_path: "assets/icon/newsicon.png"
  android: true
  ios: false

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
  assets:
    - assets/images/dropbox.png



  fonts:
    - family: LangerReguler
      fonts:
        - asset: assets/langer_reguler.ttf




  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

3. Then run the command in terminal flutter pub get and then flutter_luncher_icon.This is what I get the result after the successfully run the command . And luncher icon is also generated successfully.

My Terminal

[E:\AndroidStudioProjects\FlutterProject\NewsFlutter\news_flutter>flutter pub get
Running "flutter pub get" in news_flutter...                       881ms

E:\AndroidStudioProjects\FlutterProject\NewsFlutter\news_flutter>flutter pub run flutter_launcher_icons:main
  --------------------------------------------
     FLUTTER LAUNCHER ICONS (v0.8.0)
  --------------------------------------------

• Creating default icons Android
• Overwriting the default Android launcher icon with a new icon

? Successfully generated launcher icons

Convert pandas Series to DataFrame

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

pd.DataFrame({'email':sf.index, 'list':sf.values})

There are lots of ways to construct a df, see the docs

How to finish current activity in Android

When you want start a new activity and finish the current activity you can do this:

API 11 or greater

Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

API 10 or lower

Intent intent = new Intent(OldActivity.this, NewActivity.class);
intent.setFlags(IntentCompat.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

I hope this can help somebody =)

SSL Error: CERT_UNTRUSTED while using npm command

I had same problem and finally I understood that my node version is old. For example, you can install the current active LTS node version in Ubuntu by the following steps:

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

Installation instructions for more versions and systems can be found in the following link:

https://github.com/nodesource/distributions/blob/master/README.md

Java Timer vs ExecutorService?

According to Java Concurrency in Practice:

  • Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't.
  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory).
  • Runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.

If you can use ScheduledThreadExecutor instead of Timer, do so.

One more thing... while ScheduledThreadExecutor isn't available in Java 1.4 library, there is a Backport of JSR 166 (java.util.concurrent) to Java 1.2, 1.3, 1.4, which has the ScheduledThreadExecutor class.

Ignore Duplicates and Create New List of Unique Values in Excel

=SORT(UNIQUE(A:A))

The above formula works best if you want to list unique values in a column.

Reversing a String with Recursion in Java

public class ReverseString{

private static  String reverse(String text, String reverseStr){
    if(text == null || text.length() == 0){
        return reverseStr;
    }
    return reverse(text.substring(1), text.charAt(0)+reverseStr);
}
public static void main(String [] args){
    System.out.println(reverse("hello", "")); //output is "olleh"
}

}

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

PHPExcel auto size column width

If a column is set to AutoSize, PHPExcel attempts to calculate the column width based on the calculated value of the column (so on the result of any formulae), and any additional characters added by format masks such as thousand separators.

By default, this is an estimated width: a more accurate calculation method is available, based on using GD, which can also handle font style features such as bold and italic; but this is a much bigger overhead, so it is turned off by default. You can enable the more accurate calculation using

PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);

However, autosize doesn't apply to all Writer formats... for example CSV. You don't mention what writer you're using.

But you also need to identify the columns to set dimensions:

foreach(range('B','G') as $columnID) {
    $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
        ->setAutoSize(true);
}

$objPHPExcel->getActiveSheet()->getColumnDimension() expects a column ID.

$objPHPExcel->getActiveSheet()->getColumnDimensions() will return an array of all the defined column dimension records; but unless a column dimension record has been explicitly created (perhaps by loading a template, or by manually calling getColumnDimension()) then it won't exist (memory saving).

Android design support library for API 28 (P) not working

Below code worked perfectly with me:

dependencies {
    api 'com.android.support:design:28.0.0-alpha3'

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'androidx.test:runner:1.1.0-alpha2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha2'
}

Total width of element (including padding and border) in jQuery

$(document).ready(function(){     
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");   
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");         
});


<div class="width">Width of this div container without including padding is: </div>  
<div class="innerWidth">width of this div container including padding is: </div> 
<div class="outerWidth">width of this div container including padding and margin is:     </div>

Remove an onclick listener

Perhaps setOnClickListener(null) ?

Generating UML from C++ code?

Whoever wants UML deserves Rational Rose :)

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

How to calculate number of days between two given dates?

without using Lib just pure code:

#Calculate the Days between Two Date

daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def isLeapYear(year):

    # Pseudo code for this algorithm is found at
    # http://en.wikipedia.org/wiki/Leap_year#Algorithm
    ## if (year is not divisible by 4) then (it is a common Year)
    #else if (year is not divisable by 100) then (ut us a leap year)
    #else if (year is not disible by 400) then (it is a common year)
    #else(it is aleap year)
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

def Count_Days(year1, month1, day1):
    if month1 ==2:
        if isLeapYear(year1):
            if day1 < daysOfMonths[month1-1]+1:
                return year1, month1, day1+1
            else:
                if month1 ==12:
                    return year1+1,1,1
                else:
                    return year1, month1 +1 , 1
        else: 
            if day1 < daysOfMonths[month1-1]:
                return year1, month1, day1+1
            else:
                if month1 ==12:
                    return year1+1,1,1
                else:
                    return year1, month1 +1 , 1
    else:
        if day1 < daysOfMonths[month1-1]:
             return year1, month1, day1+1
        else:
            if month1 ==12:
                return year1+1,1,1
            else:
                    return year1, month1 +1 , 1


def daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):

    if y1 > y2:
        m1,m2 = m2,m1
        y1,y2 = y2,y1
        d1,d2 = d2,d1
    days=0
    while(not(m1==m2 and y1==y2 and d1==d2)):
        y1,m1,d1 = Count_Days(y1,m1,d1)
        days+=1
    if end_day:
        days+=1
    return days


# Test Case

def test():
    test_cases = [((2012,1,1,2012,2,28,False), 58), 
                  ((2012,1,1,2012,3,1,False), 60),
                  ((2011,6,30,2012,6,30,False), 366),
                  ((2011,1,1,2012,8,8,False), 585 ),
                  ((1994,5,15,2019,8,31,False), 9239),
                  ((1999,3,24,2018,2,4,False), 6892),
                  ((1999,6,24,2018,8,4,False),6981),
                  ((1995,5,24,2018,12,15,False),8606),
                  ((1994,8,24,2019,12,15,True),9245),
                  ((2019,12,15,1994,8,24,True),9245),
                  ((2019,5,15,1994,10,24,True),8970),
                  ((1994,11,24,2019,8,15,True),9031)]

    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

What is the equivalent of the C++ Pair<L,R> in Java?

another terse lombok implementation

import lombok.Value;

@Value(staticConstructor = "of")
public class Pair<F, S> {
    private final F first;
    private final S second;
}

How to get a list of installed Jenkins plugins with name and version pair

Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins. Simple fix for the code:

List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
              .each { plugin ->
                   println ("${plugin.shortName}:${plugin.version}")
              }

Use the http://<jenkins-url>/script URL to run the code.

How to remove jar file from local maven repository which was added with install:install-file?

Although deleting files manually works, there is an official way of removing dependencies of your project from your local (cache) repository and optionally re-resolving them from remote repositories.

The goal purge-local-repository, on the standard Maven dependency plugin, will remove the locally installed dependencies of this project from your cache. Optionally, you may re-resolve them from the remote repositories at the same time.

This should be used as part of a project phase because it applies to the dependencies for the containing project. Also transitive dependencies will be purged (locally) as well, by default.

If you want to explicitly remove a single artifact from the cache, use purge-local-repository with the manualInclude parameter. For example, from the command line:

mvn dependency:purge-local-repository -DmanualInclude="groupId:artifactId, ..."

The documentation implies that this does not remove transitive dependencies by default. If you are running with a non-standard cache location, or on multiple platforms, these are more reliable than deleting files "by hand".

The full documentation is in the maven-dependency-plugin spec.

Note: Older versions of the maven dependency plugin had a manual-purge-local-repository goal, which is now (version 2.8) implied by the use of manualInclude. The documentation for manualIncludes (with an s) should be read as well.

What is difference between @RequestBody and @RequestParam?

@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

For example Angular request for Spring RequestParam(s) would look like that:

$http.post('http://localhost:7777/scan/l/register?username="Johny"&password="123123"&auth=true')
      .success(function (data, status, headers, config) {
                        ...
                    })

Endpoint with RequestParam:

@RequestMapping(method = RequestMethod.POST, value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestParam String username,
                                    @RequestParam String password,
                                    @RequestParam boolean auth,
                                    HttpServletRequest httpServletRequest) {...

@RequestBody annotated parameters get linked to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. This annotation indicates a method parameter should be bound to the body of the web request.

For example Angular request for Spring RequestBody would look like that:

$scope.user = {
            username: "foo",
            auth: true,
            password: "bar"
        };    
$http.post('http://localhost:7777/scan/l/register', $scope.user).
                        success(function (data, status, headers, config) {
                            ...
                        })

Endpoint with RequestBody:

@RequestMapping(method = RequestMethod.POST, produces = "application/json", 
                value = "/register")
public Map<String, String> register(Model uiModel,
                                    @RequestBody User user,
                                    HttpServletRequest httpServletRequest) {... 

Hope this helps.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

I added the variables in the ~/.bash_profile in the following way. After you are done restart/log out and log in

export M2_HOME=/Users/robin/softwares/apache-maven-3.2.3
export ANT_HOME=/Users/robin/softwares/apache-ant-1.9.4
launchctl setenv M2_HOME $M2_HOME
launchctl setenv ANT_HOME $ANT_HOME
export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/robin/softwares/apache-maven-3.2.3/bin:/Users/robin/softwares/apache-ant-1.9.4/bin
launchctl setenv PATH $PATH

NOTE: without restart/log out and log in you can apply these changes using;

source ~/.bash_profile

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

Remove all the children DOM elements in div

In Dojo 1.7 or newer, use domConstruct.empty(String|DomNode):

require(["dojo/dom-construct"], function(domConstruct){
  // Empty node's children byId:
  domConstruct.empty("someId");
});

In older Dojo, use dojo.empty(String|DomNode) (deprecated at Dojo 1.8):

dojo.empty( id or DOM node );

Each of these empty methods safely removes all children of the node.

How to auto adjust the <div> height according to content in it?

If you haven't gotten the answer yet, your "float:left;" is messing up what you want. In your HTML create a container below your closing tags that have floating applied. For this container, include this as your style:

#container {
clear:both;
}

Done.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Get the week start date and week end date from week number

Get Start Date & End Date by Custom Date


   DECLARE @Date NVARCHAR(50)='05/19/2019' 
   SELECT
      DATEADD(DAY,CASE WHEN DATEPART(WEEKDAY, @Date)=1 THEN -6 ELSE 2 - DATEPART(WEEKDAY, @Date) END, CAST(@Date AS DATE)) [Week_Start_Date]
     ,DATEADD(DAY,CASE WHEN DATEPART(WEEKDAY, @Date)=1 THEN 0 ELSE  8 - DATEPART(WEEKDAY, @Date) END, CAST(@Date AS DATE)) [Week_End_Date]

How to change the background color of Action Bar's Option Menu in Android 4.2?

Following are the changes required in your theme for changing action bar & overflow menu background color. You need to configure "android:background" of actionBarStyle & popupMenuStyle

<application
            android:name="...."
            android:theme="@style/AppLightTheme">

<style name="AppLightTheme" parent="android:Theme.Holo.Light">      
        <item name="android:actionBarStyle">@style/ActionBarLight</item>
        <item name="android:popupMenuStyle">@style/ListPopupWindowLight</item>
</style>

<style name="ActionBarLight" parent="android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">@color/white</item>
</style>


<style name="ListPopupWindowLight"parent="@android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:background">@color/white</item>
</style>

Distinct() with lambda?

A tricky way to do this is use Aggregate() extension, using a dictionary as accumulator with the key-property values as keys:

var customers = new List<Customer>();

var distincts = customers.Aggregate(new Dictionary<int, Customer>(), 
                                    (d, e) => { d[e.CustomerId] = e; return d; },
                                    d => d.Values);

And a GroupBy-style solution is using ToLookup():

var distincts = customers.ToLookup(c => c.CustomerId).Select(g => g.First());

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

Android Failed to install HelloWorld.apk on device (null) Error

@Bolton 's answer worked for me. Some details...

I got my phone a few weeks ago. I tried the HelloAndroid sample app right away (after installing req'd software, etc.). The app worked in the emulator AND on the phone--right away!

Shortly after that, I rooted my phone but did not flash any roms or kernels. I was only experimenting on the emulator until yesterday (writing a simple notepad app). When I tried debugging the app on the phone, here's what I observed:

  1. Eclipse console reported the "...failed to install on device...(null)" message. BUT

  2. The HelloAndroid app DID get pushed to the phone! (It appeared in the apps drawer AND I was able to launch it.)

  3. It simply would not launch on the phone from the Eclipse run.

I searched around here and elsewhere last night (including this thread) with no luck. Finally, I rebooted my phone--which I never tried (doh!) 'cause I didn't think it would make a difference--and the app launched from an Eclipse start!

Still don't know the cause, but I'll come back here if I figure it out.

what's the default value of char?

The default char is the character with an int value of 0 (zero).

char NULLCHAR = (char) 0;

char NULLCHAR = '\0';

Last non-empty cell in a column

=MATCH("*";A1:A10;-1) for textual data

=MATCH(0;A1:A10;-1) for numerical data

How to get TimeZone from android mobile?

ZoneId from java.time and ThreeTenABP

Modern answer:

    ZoneId zone = ZoneId.systemDefault();
    System.out.println(zone);

When I ran this snippet in Australia/Sydney time zone, the output was exactly that:

Australia/Sydney

If you want the summer time (DST) aware time zone name or abbreviation:

    DateTimeFormatter longTimeZoneFormatter = DateTimeFormatter.ofPattern("zzzz", Locale.getDefault());
    String longTz = ZonedDateTime.now(zone).format(longTimeZoneFormatter);
    System.out.println(longTz);

    DateTimeFormatter shortTimeZoneFormatter = DateTimeFormatter.ofPattern("zzz", Locale.getDefault());
    String shortTz = ZonedDateTime.now(zone).format(shortTimeZoneFormatter);
    System.out.println(shortTz);
Eastern Summer Time (New South Wales)
EST

The TimeZone class used in most of the other answers was what we had when the question was asked in 2011, even though it was poorly designed. Today it’s long outdated, and I recommend that instead we use java.time, the modern Java date and time API that came out in 2014.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Does mobile Google Chrome support browser extensions?

Extensions are not supported, see: https://developers.google.com/chrome/mobile/docs/faq .

Specifically:

Does Chrome for Android now support the embedded WebView for a hybrid native/web app?

A Chrome-based WebView is included in Android 4.4 (KitKat) and later. See the WebView overview for details.

Does Chrome for Android support apps and extensions?

Chrome apps and extensions are currently not supported on Chrome for Android. We have no plans to announce at this time.

Can I write and deploy web apps on Chrome for Android?

Though Chrome apps are not currently supported, we would love to see great interactive web sites accessible by URL.

Convert SQL Server result set into string

DECLARE @result varchar(1000)

SELECT @result = ISNULL(@result, '') + StudentId + ',' FROM Student WHERE condition = xyz

select substring(@result, 0, len(@result) - 1) --trim extra "," at end

How to declare and add items to an array in Python?

Just for sake of completion, you can also do this:

array = []
array += [valueToBeInserted]

If it's a list of strings, this will also work:

array += 'string'

How to use SSH to run a local shell script on a remote machine?

This is an old question, and Jason's answer works fine, but I would like to add this:

ssh user@host <<'ENDSSH'
#commands to run on remote host
ENDSSH

This can also be used with su and commands which require user input. (note the ' escaped heredoc)

Edit: Since this answer keeps getting bits of traffic, i would add even more info to this wonderful use of heredoc:

You can nest commands with this syntax, and thats the only way nesting seems to work (in a sane way)

ssh user@host <<'ENDSSH'
#commands to run on remote host
ssh user@host2 <<'END2'
# Another bunch of commands on another host
wall <<'ENDWALL'
Error: Out of cheese
ENDWALL
ftp ftp.secureftp-test.com <<'ENDFTP'
test
test
ls
ENDFTP
END2
ENDSSH

You can actually have a conversation with some services like telnet, ftp, etc. But remember that heredoc just sends the stdin as text, it doesn't wait for response between lines

Edit: I just found out that you can indent the insides with tabs if you use <<-END !

ssh user@host <<-'ENDSSH'
    #commands to run on remote host
    ssh user@host2 <<-'END2'
        # Another bunch of commands on another host
        wall <<-'ENDWALL'
            Error: Out of cheese
        ENDWALL
        ftp ftp.secureftp-test.com <<-'ENDFTP'
            test
            test
            ls
        ENDFTP
    END2
ENDSSH

(I think this should work)

Also see http://tldp.org/LDP/abs/html/here-docs.html

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

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

How do I prevent the padding property from changing width or height in CSS?

Put a div in your newdiv with width: auto and margin-left: 20px

Remove the padding from newdiv.

The W3 Box model page has good info.

error: src refspec master does not match any

Only because your local branch does not math the one in your remote repository. git push origin HEAD:master Enable you to ignore the conflict and upload your commit anyway.

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

filename and line number of Python script

Filename:

__file__
# or
sys.argv[0]

Line:

inspect.currentframe().f_lineno

(not inspect.currentframe().f_back.f_lineno as mentioned above)

Best way to generate xml?

Using lxml:

from lxml import etree

# create XML 
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)

# pretty string
s = etree.tostring(root, pretty_print=True)
print s

Output:

<root>
  <child/>
  <child>some text</child>
</root>

See the tutorial for more information.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Try this

SELECT t1.*
FROM 
 some_table t1,
  (SELECT relevant_field
  FROM some_table
  GROUP BY relevant_field
  HAVING COUNT (*) > 1) t2
WHERE
 t1.relevant_field = t2.relevant_field;

Get all variables sent with POST?

So, something like the $_POST array?

You can use http_build_query($_POST) to get them in a var=xxx&var2=yyy string again. Or just print_r($_POST) to see what's there.

How can I create an object based on an interface file definition in TypeScript?

If you want an empty object of an interface, you can do just:

var modal = <IModal>{};

The advantage of using interfaces in lieu of classes for structuring data is that if you don't have any methods on the class, it will show in compiled JS as an empty method. Example:

class TestClass {
    a: number;
    b: string;
    c: boolean;
}

compiles into

var TestClass = (function () {
    function TestClass() {
    }
    return TestClass;
})();

which carries no value. Interfaces, on the other hand, don't show up in JS at all while still providing the benefits of data structuring and type checking.

Writing to a new file if it doesn't exist, and appending to a file if it does

Using the pathlib module (python's object-oriented filesystem paths)

Just for kicks, this is perhaps the latest pythonic version of the solution.

from pathlib import Path 

path = Path(f'{player}.txt')
path.touch()  # default exists_ok=True
with path.open('a') as highscore:
   highscore.write(f'Username:{player}')

Setting POST variable without using form

you can do it using ajax or by sending http headers+content like:

POST /xyz.php HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme

Combine :after with :hover

Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

#alertlist li.selected:after, #alertlist li:hover:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}

Using a BOOL property

Apple simply recommends declaring an isX getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:

@property (nonatomic, assign) BOOL working;

[self setWorking:YES];         // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;

Or

@property (nonatomic, assign, getter=isWorking) BOOL working;

[self setWorking:YES];           // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above

Use :hover to modify the css of another class?

You can do it by making the following CSS. you can put here the css you need to affect child class in case of hover on the root

_x000D_
_x000D_
.root:hover    .child {_x000D_
   _x000D_
}
_x000D_
_x000D_
_x000D_

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

How is Java platform-independent when it needs a JVM to run?

JVM will be platform dependent.
But whatever it will generate that will be platform independent. [which we called as bytecode or simply you can say...the class file]. for that why Java is called Platform independent.
you can run the same class file on Mac as well on Windows but it will require JRE.

Is embedding background image data into CSS as Base64 good or bad practice?

Base64 adds about 10% to the image size after GZipped but that outweighs the benefits when it comes to mobile. Since there is a overall trend with responsive web design, it is highly recommended.

W3C also recommends this approach for mobile and if you use asset pipeline in rails, this is a default feature when compressing your css

http://www.w3.org/TR/mwabp/#bp-conserve-css-images

Java String new line

Here it is!! NewLine is known as CRLF(Carriage Return and Line Feed).

  • For Linux and Mac, we can use "\n".
  • For Windows, we can use "\r\n".

Sample:

System.out.println("I\r\nam\r\na\r\nboy");

Result:
output

It worked for me.

How to search in array of object in mongodb

You can do this in two ways:

  1. ElementMatch - $elemMatch (as explained in above answers)

    db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })

  2. Use $and with find

    db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})

How do you overcome the svn 'out of date' error?

I sometimes get this with TortoiseSVN on windows. The solution for me is to svn update the directory, even though there are no revisions to download or update. It does something to the metadata, which magically fixes it.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

Pass parameter to controller from @Html.ActionLink MVC 4

The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g

@{         
     var blogPostId = 1;          
 }

If the error disappers, then u need to make sure that your model Id has a value before passing it to the view

How can I create directory tree in C++/Linux?

So I need mkdirp() today, and found the solutions on this page overly complicated. Hence I wrote a fairly short snippet, that easily be copied in for others who stumble upon this thread an wonder why we need so many lines of code.

mkdirp.h

#ifndef MKDIRP_H
#define MKDIRP_H

#include <sys/stat.h>

#define DEFAULT_MODE      S_IRWXU | S_IRGRP |  S_IXGRP | S_IROTH | S_IXOTH

/** Utility function to create directory tree */
bool mkdirp(const char* path, mode_t mode = DEFAULT_MODE);

#endif // MKDIRP_H

mkdirp.cpp

#include <errno.h>

bool mkdirp(const char* path, mode_t mode) {
  // const cast for hack
  char* p = const_cast<char*>(path);

  // Do mkdir for each slash until end of string or error
  while (*p != '\0') {
    // Skip first character
    p++;

    // Find first slash or end
    while(*p != '\0' && *p != '/') p++;

    // Remember value from p
    char v = *p;

    // Write end of string at p
    *p = '\0';

    // Create folder from path to '\0' inserted at p
    if(mkdir(path, mode) == -1 && errno != EEXIST) {
      *p = v;
      return false;
    }

    // Restore path to it's former glory
    *p = v;
  }

  return true;
}

If you don't like const casting and temporarily modifying the string, just do a strdup() and free() it afterwards.

Google maps API V3 method fitBounds()

I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds() at the wrong time may leave you with a result like in the Q. The best way I found is to place the call in an idle handler like this:

google.maps.event.addListenerOnce(map, 'idle', function() {
    map.fitBounds(markerBounds);
});

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

C# listView, how do I add items to columns 2, 3 and 4 etc?

You can add items / sub-items to the ListView like:

ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

listView1.View = View.Details;

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

Add items to comboBox in WPF

Use this

string[] str = new string[] {"Foo", "Bar"};

myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;

OR

foreach (string s in str)
    myComboBox.Items.Add(s);

myComboBox.SelectedIndex = 0;      

Vue Js - Loop via v-for X times (in a range)

In 2.2.0+, when using v-for with a component, a key is now required.

<div v-for="item in items" :key="item.id">

Source

MessageBox Buttons?

This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.

DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
            if (d == DialogResult.Yes)
            {
                //Contents
            }
            else if (d == DialogResult.No)
            {
                //Contents
            }

How do I create a unique constraint that also allows nulls?

SQL Server 2008 +

You can create a unique index that accept multiple NULLs with a WHERE clause. See the answer below.

Prior to SQL Server 2008

You cannot create a UNIQUE constraint and allow NULLs. You need set a default value of NEWID().

Update the existing values to NEWID() where NULL before creating the UNIQUE constraint.

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

How to uncompress a tar.gz in another directory

You can use the option -C (or --directory if you prefer long options) to give the target directory of your choice in case you are using the Gnu version of tar. The directory should exist:

mkdir foo
tar -xzf bar.tar.gz -C foo

If you are not using a tar capable of extracting to a specific directory, you can simply cd into your target directory prior to calling tar; then you will have to give a complete path to your archive, of course. You can do this in a scoping subshell to avoid influencing the surrounding script:

mkdir foo
(cd foo; tar -xzf ../bar.tar.gz)  # instead of ../ you can use an absolute path as well

Or, if neither an absolute path nor a relative path to the archive file is suitable, you also can use this to name the archive outside of the scoping subshell:

TARGET_PATH=a/very/complex/path/which/might/even/be/absolute
mkdir -p "$TARGET_PATH"
(cd "$TARGET_PATH"; tar -xzf -) < bar.tar.gz

Get time difference between two dates in seconds

Accurate and fast will give output in seconds:

 let startDate = new Date()
 let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
 let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);

Redirecting to URL in Flask

For this you can simply use the redirect function that is included in flask

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("https://www.exampleURL.com", code = 302)

if __name__ == "__main__":
    app.run()

Another useful tip(as you're new to flask), is to add app.debug = True after initializing the flask object as the debugger output helps a lot while figuring out what's wrong.

Git removing upstream from local repository

Using git version 1.7.9.5 there is no "remove" command for remote. Use "rm" instead.

$ git remote rm upstream
$ git remote add upstream https://github.com/Foo/repos.git

or, as noted in the previous answer, set-url works.

I don't know when the command changed, but Ubuntu 12.04 shipped with 1.7.9.5.

Value does not fall within the expected range

This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

Cheers,

IntelliJ Organize Imports

Shortcut for the Mac: (ctrl + opt + o)

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

How to access the value of a promise?

Maybe this small Typescript code example will help.

private getAccount(id: Id) : Account {
    let account = Account.empty();
    this.repository.get(id)
        .then(res => account = res)
        .catch(e => Notices.results(e));
    return account;
}

Here the repository.get(id) returns a Promise<Account>. I assign it to the variable account within the then statement.

android.os.NetworkOnMainThreadException with android 4.2

Use StrictMode Something like this:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }

What is SaaS, PaaS and IaaS? With examples

Adding to that, I have used AWS, heroku and currently using Jelastic and found -

Jelastic offers a Java and PHP cloud hosting platform. Jelastic automatically scales Java and PHP applications and allocates server resources, thus delivering true next-generation Java and PHP cloud computing. http://blog.jelastic.com/2013/04/16/elastic-beanstalk-vs-jelastic/ or http://cloud.dzone.com/articles/jelastic-vs-heroku-1

Personally I found -

  • Jelastic is faster
  • You don’t need to code to any jelastic APIs – just upload your application and select your stack. You can also mix and match software stacks at will.

Try any of them and explore yourself. Its fun :-)

MyISAM versus InnoDB

I've worked on a high-volume system using MySQL and I've tried both MyISAM and InnoDB.

I found that the table-level locking in MyISAM caused serious performance problems for our workload which sounds similar to yours. Unfortunately I also found that performance under InnoDB was also worse than I'd hoped.

In the end I resolved the contention issue by fragmenting the data such that inserts went into a "hot" table and selects never queried the hot table.

This also allowed deletes (the data was time-sensitive and we only retained X days worth) to occur on "stale" tables that again weren't touched by select queries. InnoDB seems to have poor performance on bulk deletes so if you're planning on purging data you might want to structure it in such a way that the old data is in a stale table which can simply be dropped instead of running deletes on it.

Of course I have no idea what your application is but hopefully this gives you some insight into some of the issues with MyISAM and InnoDB.

How can I remove the last character of a string in python?

For a path use os.path.abspath

import os    
print os.path.abspath(my_file_path)

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

If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:

-- Queries the backup file for the file list in backup set, where Type denotes 
-- type of file. Can be L,D,F or S
-- info: https://docs.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:\Temp\DB_backup.bak'
GO

You will get results similar to the following:

enter image description here

And then you can use those logical names in the queries:

    -- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
    RESTORE DATABASE DB 
    FROM DISK='C:\Temp\DB_backup.bak'
    WITH REPLACE,
      MOVE 'DB' TO 'E:\MSSQL\Data\DB.mdf', -- "DB" is the mdf logical name from query above
      MOVE 'DB_log' TO 'F:\MSSQL\Logs\DB.ldf'; -- "DB_log" is LDF logical name from query above

More info on RESTORE FILELISTONLY can be found from the SQL Server docs.

how to check for datatype in node js- specifically for integer

You can check your numbers by checking their constructor.

var i = "5";

if( i.constructor !== Number )
{
 console.log('This is not number'));
}

How do I get the result of a command in a variable in windows?

I would like to add a remark to the above solutions:

All these syntaxes work perfectly well IF YOUR COMMAND IS FOUND WITHIN THE PATH or IF THE COMMAND IS A cmdpath WITHOUT SPACES OR SPECIAL CHARACTERS.

But if you try to use an executable command located in a folder which path contains special characters then you would need to enclose your command path into double quotes (") and then the FOR /F syntax does not work.

Examples:

$ for /f "tokens=* USEBACKQ" %f in (
    `""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" Hello '"F:\GLW7\Distrib\System\Shells and scripting"'`
) do echo %f
The filename, directory name, or volume label syntax is incorrect.

or

$ for /f "tokens=* USEBACKQ" %f in (
      `"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'F:\GLW7\Distrib\System\Shells' is not recognized as an internal or external command, operable program or batch file.

or

`$ for /f "tokens=* USEBACKQ" %f in (
     `""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello' is not recognized as an internal or external command, operable program or batch file.

In that case, the only solution I found to use a command and store its result in a variable is to set (temporarily) the default directory to the one of command itself :

pushd "%~d0%~p0"
FOR /F "tokens=* USEBACKQ" %%F IN (
    `FOLDERBROWSE "Hello world!" "F:\GLW7\Distrib\System\Layouts (print,display...)"`
) DO (SET MyFolder=%%F)
popd
echo My selected folder: %MyFolder%

The result is then correct:

My selected folder: F:\GLW7\Distrib\System\OS install, recovery, VM\
Press any key to continue . . .

Of course in the above example, I assume that my batch script is located in the same folder as the one of my executable command so that I can use the "%~d0%~p0" syntax. If this is not your case, then you have to find a way to locate your command path and change the default directory to its path.

NB: For those who wonder, the sample command used here (to select a folder) is FOLDERBROWSE.EXE. I found it on the web site f2ko.de (http://f2ko.de/en/cmd.php).

If anyone has a better solution for that kind of commands accessible through a complex path, I will be very glad to hear of it.

Gilles

Scroll Automatically to the Bottom of the Page

I have an Angular app with dynamic content and I tried several of the above answers with not much success. I adapted @Konard's answer and got it working in plain JS for my scenario:

HTML

<div id="app">
    <button onClick="scrollToBottom()">Scroll to Bottom</button>
    <div class="row">
        <div class="col-md-4">
            <br>
            <h4>Details for Customer 1</h4>
            <hr>
            <!-- sequence Id -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="ID">
            </div>
            <!-- name -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Name">
            </div>
            <!-- description -->
            <div class="form-group">
                <textarea type="text" style="min-height: 100px" placeholder="Description" ></textarea>
            </div>
            <!-- address -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Address">
            </div>
            <!-- postcode -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Postcode">
            </div>
            <!-- Image -->
            <div class="form-group">
                <img style="width: 100%; height: 300px;">
                <div class="custom-file mt-3">
                    <label class="custom-file-label">{{'Choose file...'}}</label>
                </div>
            </div>
            <!-- Delete button -->
            <div class="form-group">
                <hr>
                <div class="row">
                    <div class="col">
                        <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to save">Save</button>
                        <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to update">Update</button>
                    </div>
                    <div class="col">
                        <button class="btn btn-danger btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to remove">Remove</button>
                    </div>
                </div>
                <hr>
            </div>
        </div>
    </div>
</div>

CSS

body {
    background: #20262E;
    padding: 20px;
    font-family: Helvetica;
}

#app {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    transition: all 0.2s;
}

JS

function scrollToBottom() {
    scrollInterval;
    stopScroll;

    var scrollInterval = setInterval(function () {
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    }, 50);

    var stopScroll = setInterval(function () {
        clearInterval(scrollInterval);
    }, 100);
}

Tested on the latest Chrome, FF, Edge, and stock Android browser. Here's a fiddle:

https://jsfiddle.net/cbruen1/18cta9gd/16/

Change the background color of a pop-up dialog

You can create a custom alertDialog and use a xml layout. in the layout, you can set the background color and textcolor.

Something like this:

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));
dialog.setContentView(view);

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I did everything provided in the previous answers to this question, but still had the issue. I did have the update installed, but I ran the installer again, reapplying the update while SQL 2012 Installer was open on the screen where I could run the check again. After it finished, I ran the check again and it passed.

Best practice when adding whitespace in JSX

use {} or {``} or &nbsp; to create space between span element and content.

<b> {notif.name} </b> <span id="value"> &nbsp;{ notif.count }{``} </span>

Can I make a function available in every controller in angular?

Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.

Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.

Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.

How to remove border from specific PrimeFaces p:panelGrid?

If you just want something more simple, you can just change:

<p:panelGrid >

</p:panelGrid>

to:

<h:panelGrid border="0">

</h:panelGrid>

That's worked fine for me

Apply multiple functions to multiple groupby columns

This is a twist on 'exans' answer that uses Named Aggregations. It's the same but with argument unpacking which allows you to still pass in a dictionary to the agg function.

The named aggs are a nice feature, but at first glance might seem hard to write programmatically since they use keywords, but it's actually simple with argument/keyword unpacking.

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                         'height': [9.1, 6.0, 9.5, 34.0],
                         'weight': [7.9, 7.5, 9.9, 198.0]})
 
agg_dict = {
    "min_height": pd.NamedAgg(column='height', aggfunc='min'),
    "max_height": pd.NamedAgg(column='height', aggfunc='max'),
    "average_weight": pd.NamedAgg(column='weight', aggfunc=np.mean)
}

animals.groupby("kind").agg(**agg_dict)

The Result

      min_height  max_height  average_weight
kind                                        
cat          9.1         9.5            8.90
dog          6.0        34.0          102.75

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll('data-foo')

to get list of all elements having attribute data-foo

If you want to get element with data attribute which is having some specific value e.g

<div data-foo="1"></div>
<div data-foo="2" ></div>

and I want to get div with data-foo set to "2"

document.querySelector('[data-foo="2"]')

But here comes the twist what if I want to match the data attirubte value with some variable's value like I want to get element if data-foo attribute is set to i

var i=2;

so you can dynamically select the element having specific data element using template literals

document.querySelector(`[data-foo="${i}"]`)

Note even if you don't write value in string it gets converted to string like if I write

<div data-foo=1></div>

and then inspect the element in Chrome developer tool the element will be shown as below

<div data-foo="1"></div>

You can also cross verify by writing below code in console

console.log(typeof document.querySelector(`[data-foo]="${i}"`).dataset('dataFoo'))

why I have written 'dataFoo' though the attribute is data-foo reason dataset properties are converted to camelCase properties

I have referred below links

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-* https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

This is my first answer on stackoverflow please let me know how can I improve my answer writing way.

C++ alignment when printing cout <<

Another way to make column aligned is as follows:

using namespace std;

cout.width(20); cout << left << "Artist";
cout.width(20); cout << left << "Title";
cout.width(10); cout << left << "Price";
...
cout.width(20); cout << left << artist;
cout.width(20); cout << left << title;
cout.width(10); cout << left << price;

We should estimate maximum length of values for each column. In this case, values of "Artist" column should not exceed 20 characters and so on.

JavaScript checking for null vs. undefined and difference between == and ===

The spec is the place to go for full answers to these questions. Here's a summary:

  1. For a variable x, you can:

    • check whether it's null by direct comparison using ===. Example: x === null
    • check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
    • check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.

  2. The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.

More reading:

The PowerShell -and conditional operator

Try like this:

if($user_sam -ne $NULL -and $user_case -ne $NULL)

Empty variables are $null and then different from "" ([string]::empty).

Capitalize words in string

Since everyone has given you the JavaScript answer you've asked for, I'll throw in that the CSS property text-transform: capitalize will do exactly this.

I realize this might not be what you're asking for - you haven't given us any of the context in which you're running this - but if it's just for presentation, I'd definitely go with the CSS alternative.

Reading a file character by character in C

Here's one simple way to ignore everything but valid brainfuck characters:

#define BF_VALID "+-><[].,"

if (strchr(BF_VALID, c))
    code[n++] = c;

What is the naming convention in Python for variable and function names?

As the Style Guide for Python Code admits,

The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent

Note that this refers just to Python's standard library. If they can't get that consistent, then there hardly is much hope of having a generally-adhered-to convention for all Python code, is there?

From that, and the discussion here, I would deduce that it's not a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, internal consistency matters most.

Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.

How to search for a string in an arraylist

List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
           for (String string : list) {
               if(pattern.matcher(string).find()) {
                   listClone.add(string);
                   continue;
               }
           }
        System.out.println(listClone);

How to use SharedPreferences in Android to store, fetch and edit values

Simple solution of how to store login value in by SharedPreferences.

You can extend the MainActivity class or other class where you will store the "value of something you want to keep". Put this into writer and reader classes:

public static final String GAME_PREFERENCES_LOGIN = "Login";

Here InputClass is input and OutputClass is output class, respectively.

// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";

// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();

// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();

Now you can use it somewhere else, like other class. The following is OutputClass.

SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");

// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);

How does numpy.histogram() work?

A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".)

The Numpy histogram function doesn't draw the histogram, but it computes the occurrences of input data that fall within each bin, which in turns determines the area (not necessarily the height if the bins aren't of equal width) of each bar.

In this example:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])

There are 3 bins, for values ranging from 0 to 1 (excl 1.), 1 to 2 (excl. 2) and 2 to 3 (incl. 3), respectively. The way Numpy defines these bins if by giving a list of delimiters ([0, 1, 2, 3]) in this example, although it also returns the bins in the results, since it can choose them automatically from the input, if none are specified. If bins=5, for example, it will use 5 bins of equal width spread between the minimum input value and the maximum input value.

The input values are 1, 2 and 1. Therefore, bin "1 to 2" contains two occurrences (the two 1 values), and bin "2 to 3" contains one occurrence (the 2). These results are in the first item in the returned tuple: array([0, 2, 1]).

Since the bins here are of equal width, you can use the number of occurrences for the height of each bar. When drawn, you would have:

  • a bar of height 0 for range/bin [0,1] on the X-axis,
  • a bar of height 2 for range/bin [1,2],
  • a bar of height 1 for range/bin [2,3].

You can plot this directly with Matplotlib (its hist function also returns the bins and the values):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()

enter image description here

How to add parameters to a HTTP GET request in Android?

The method

setParams() 

like

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));

only adds HttpProtocol parameters.

To execute the httpGet you should append your parameters to the url manually

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

or use the post request the difference between get and post requests are explained here, if you are interested

%Like% Query in spring JpaRepository

The spring data JPA query needs the "%" chars as well as a space char following like in your query, as in

@Query("Select c from Registration c where c.place like %:place%").

Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.

You may want to get rid of the @Queryannotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line

List<Registration> findByPlaceContaining(String place);

is sufficient.

Best way to clear a PHP array's values

I see this questions is realla old, but for that problem I wrote a recursive function to unset all values in an array. Recursive because its possible that values from the given array are also an array. So that works for me:

function empty_array(& $complete_array) {
    foreach($complete_array as $ckey => $cvalue)
    {
        if (!is_array($cvalue)) {
            $complete_array[$ckey] = "";
        } else {
            empty_array( $complete_array[$ckey]);
        }

    }
    return $complete_array;

}

So with that i get the array with all keys and sub-arrays, but empty values.

TreeMap sort by value

polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.

This code:...

Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
nonSortedMap.put("ape", 1);
nonSortedMap.put("pig", 3);
nonSortedMap.put("cow", 1);
nonSortedMap.put("frog", 2);

for (Entry<String, Integer> entry  : entriesSortedByValues(nonSortedMap)) {
    System.out.println(entry.getKey()+":"+entry.getValue());
}

Would output:

ape:1
frog:2
pig:3

Note how our cow dissapeared as it shared the value "1" with our ape :O!

This modification of the code solves that issue:

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

You don't have permission to access / on this server

Check file permissions of the /var/www/html and the ALLOW directive in your apache conf

Make sure all files are readable by the webserver and the allow directive is like

 <Directory "/var/www/html">
    Order allow,deny
    Allow from all
  </Directory>

if you can see files then consider sorting the directive to be more restrictive

How to convert byte array to string and vice versa?

private static String toHexadecimal(byte[] digest){
        String hash = "";
    for(byte aux : digest) {
        int b = aux & 0xff;
        if (Integer.toHexString(b).length() == 1) hash += "0";
        hash += Integer.toHexString(b);
    }
    return hash;
}

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Add shadow to custom shape on Android

The following worked for me: Just save as custom_shape.xml.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- "shadow" -->
    <item>
        <shape android:shape="rectangle" >
           <solid android:color="#000000"/>
           <corners android:radius="12dp" />
        </shape>
    </item>


    <item android:bottom="3px">
        <shape android:shape="rectangle"> 
            <solid android:color="#90ffffff"/>
            <corners android:radius="12dp" />
         </shape>
    </item>

</layer-list>

How to use ConcurrentLinkedQueue?

Just use it as you would a non-concurrent collection. The Concurrent[Collection] classes wrap the regular collections so that you don't have to think about synchronizing access.

Edit: ConcurrentLinkedList isn't actually just a wrapper, but rather a better concurrent implementation. Either way, you don't have to worry about synchronization.

REST API Best practices: Where to put parameters?

As per the REST Implementation,

1) Path variables are used for the direct action on the resources, like a contact or a song ex..
GET etc /api/resource/{songid} or
GET etc /api/resource/{contactid} will return respective data.

2) Query perms/argument are used for the in-direct resources like metadata of a song ex.., GET /api/resource/{songid}?metadata=genres it will return the genres data for that particular song.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Veverke mentioned that it is possible to disable generation of binding redirects by setting AutoGEneratedBindingRedirects to false. Not sure if it's a new thing since this question was posted, but there is an "Skip applying binding redirects" option in Tools/Options/Nuget Packet Manager, which can be toggled. By default it is off, meaning the redirects will be applied. However if you do this, you will have to manage any necessary binding redirects manually.

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

[Joke mode on]

You can fix this by adding this:

https://github.com/donavon/undefined-is-a-function

import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.

[joke mode off]

Select current date by default in ASP.Net Calendar control

I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.

protected void Page_Load(object sender, EventArgs e)
    Calendar1.SelectedDate = DateTime.Today;
}

the previous code did NOT highlight the selection, although it set the SelectedDate to today.

However, to select and highlight the following code will work properly.

protected void Page_Load(object sender, EventArgs e)
{
    DateTime today = DateTime.Today;
    Calendar1.TodaysDate = today;
    Calendar1.SelectedDate = Calendar1.TodaysDate;
}

check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx

how to change a selections options based on another select option selected?

you can use data-tag in html5 and do this using this code:

_x000D_
_x000D_
<script>_x000D_
 $('#mainCat').on('change', function() {_x000D_
  var selected = $(this).val();_x000D_
  $("#expertCat option").each(function(item){_x000D_
   console.log(selected) ;  _x000D_
   var element =  $(this) ; _x000D_
   console.log(element.data("tag")) ; _x000D_
   if (element.data("tag") != selected){_x000D_
    element.hide() ; _x000D_
   }else{_x000D_
    element.show();_x000D_
   }_x000D_
  }) ; _x000D_
  _x000D_
  $("#expertCat").val($("#expertCat option:visible:first").val());_x000D_
  _x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<select id="mainCat">_x000D_
   <option value = '1'>navid</option>_x000D_
   <option value = '2'>javad</option>_x000D_
   <option value = '3'>mamal</option>_x000D_
  </select>_x000D_
  _x000D_
  <select id="expertCat">_x000D_
   <option  value = '1' data-tag='2'>UI</option>_x000D_
   <option  value = '2' data-tag='2'>Java Android</option>_x000D_
   <option  value = '3' data-tag='1'>Web</option>_x000D_
   <option  value = '3' data-tag='1'>Server</option>_x000D_
   <option  value = '3' data-tag='3'>Back End</option>_x000D_
   <option  value = '3' data-tag='3'>.net</option>_x000D_
  </select>
_x000D_
_x000D_
_x000D_

Total number of items defined in an enum

You can use Enum.GetNames to return an IEnumerable of values in your enum and then .Count the resulting IEnumerable.

GetNames produces much the same result as GetValues but is faster.

Bootstrap datetimepicker is not a function

I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js

try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}

Regular expression to match any character being repeated more than 10 times

={10,}

matches = that is repeated 10 or more times.

PHP - Get key name of array value

If the name's dynamic, then you must have something like

$arr[$key]

which'd mean that $key contains the value of the key.

You can use array_keys() to get ALL the keys of an array, e.g.

$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);

would give you

$x = array(0 => 'a', 1 => 'c');

Base64 encoding and decoding in oracle

do url_raw.cast_to_raw() support in oracle 6

How to detect if user select cancel InputBox VBA Excel

Following example uses InputBox method to validate user entry to unhide sheets: Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.

Sub unhidesheet()

Dim ws As Worksheet
Dim pw As String

pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then

   Exit Sub
ElseIf pw = NullString Then
   Exit Sub
ElseIf pw = 123456 Then
    For Each ws In ThisWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next
End If
End Sub

How to convert a PIL Image into a numpy array?

def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

You can transform the image into numpy by parsing the image into numpy() function after squishing out the features( unnormalization)

Using GPU from a docker container?

Recent enhancements by NVIDIA have produced a much more robust way to do this.

Essentially they have found a way to avoid the need to install the CUDA/GPU driver inside the containers and have it match the host kernel module.

Instead, drivers are on the host and the containers don't need them. It requires a modified docker-cli right now.

This is great, because now containers are much more portable.

enter image description here

A quick test on Ubuntu:

# Install nvidia-docker and nvidia-docker-plugin
wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb

# Test nvidia-smi
nvidia-docker run --rm nvidia/cuda nvidia-smi

For more details see: GPU-Enabled Docker Container and: https://github.com/NVIDIA/nvidia-docker