Programs & Examples On #Plack

Plack is a Perl module and toolkit that contains middleware, helpers and adapters to web servers. PSGI is an interface between Perl web applications and web servers.

To the power of in C?

You need pow(); function from math.h header.
syntax

#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);

Here x is base and y is exponent. result is x^y.

usage

pow(2,4);  

result is 2^4 = 16. //this is math notation only   
// In c ^ is a bitwise operator

And make sure you include math.h to avoid warning ("incompatible implicit declaration of built in function 'pow' ").

Link math library by using -lm while compiling. This is dependent on Your environment.
For example if you use Windows it's not required to do so, but it is in UNIX based systems.

Query to check index on a table

If you just need the indexed columns EXEC sp_helpindex 'TABLE_NAME'

Confused about stdin, stdout and stderr?

Using ps -aux reveals current processes, all of which are listed in /proc/ as /proc/(pid)/, by calling cat /proc/(pid)/fd/0 it prints anything that is found in the standard output of that process I think. So perhaps,

/proc/(pid)/fd/0 - Standard Output File
/proc/(pid)/fd/1 - Standard Input File
/proc/(pid)/fd/2 - Standard Error File

for examplemy terminal window

But only worked this well for /bin/bash other processes generally had nothing in 0 but many had errors written in 2

Adding Multiple Values in ArrayList at a single index

import java.util.*;
public class HelloWorld{

 public static void main(String []args){
  List<String> threadSafeList = new ArrayList<String>();
    threadSafeList.add("A");
    threadSafeList.add("D");
    threadSafeList.add("F");

Set<String> threadSafeList1 = new TreeSet<String>();
    threadSafeList1.add("B");
    threadSafeList1.add("C");
    threadSafeList1.add("E");
    threadSafeList1.addAll(threadSafeList);


 List mainList = new ArrayList();   
 mainList.addAll(Arrays.asList(threadSafeList1));
 Iterator<String> mainList1 = mainList.iterator();
 while(mainList1.hasNext()){
 System.out.printf("total : %s %n", mainList1.next());
 }
}
}

Pandas create empty DataFrame with only column names

You can create an empty DataFrame with either column names or an Index:

In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []

Or

In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Edit: Even after your amendment with the .to_html, I can't reproduce. This:

df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')

Produces:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

unique object identifier in javascript

For browsers implementing the Object.defineProperty() method, the code below generates and returns a function that you can bind to any object you own.

This approach has the advantage of not extending Object.prototype.

The code works by checking if the given object has a __objectID__ property, and by defining it as a hidden (non-enumerable) read-only property if not.

So it is safe against any attempt to change or redefine the read-only obj.__objectID__ property after it has been defined, and consistently throws a nice error instead of silently fail.

Finally, in the quite extreme case where some other code would already have defined __objectID__ on a given object, this value would simply be returned.

var getObjectID = (function () {

    var id = 0;    // Private ID counter

    return function (obj) {

         if(obj.hasOwnProperty("__objectID__")) {
             return obj.__objectID__;

         } else {

             ++id;
             Object.defineProperty(obj, "__objectID__", {

                 /*
                  * Explicitly sets these two attribute values to false,
                  * although they are false by default.
                  */
                 "configurable" : false,
                 "enumerable" :   false,

                 /* 
                  * This closure guarantees that different objects
                  * will not share the same id variable.
                  */
                 "get" : (function (__objectID__) {
                     return function () { return __objectID__; };
                  })(id),

                 "set" : function () {
                     throw new Error("Sorry, but 'obj.__objectID__' is read-only!");
                 }
             });

             return obj.__objectID__;

         }
    };

})();

Media Player called in state 0, error (-38,0)

i tested below code. working fine

public class test extends Activity implements OnErrorListener, OnPreparedListener {

private MediaPlayer player;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
        player.setOnErrorListener(this);
        player.setOnPreparedListener(this);
        player.prepareAsync();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}
@Override
public void onDestroy() {
    super.onDestroy();
    player.release();
    player = null;
}
@Override
public void onPrepared(MediaPlayer play) {
    play.start();
}
@Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
    return false;
}
}

Name [jdbc/mydb] is not bound in this Context

For those who use Tomcat with Bitronix, this will fix the problem:

The error indicates that no handler could be found for your datasource 'jdbc/mydb', so you'll need to make sure your tomcat server refers to your bitronix configuration files as needed.

In case you're using btm-config.properties and resources.properties files to configure the datasource, specify these two JVM arguments in tomcat:

(if you already used them, make sure your references are correct):

  • btm.root
  • bitronix.tm.configuration

e.g.

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Now, restart your server and check the log.

Tomcat Server not starting with in 45 seconds

I also had the issue of the Eclipse Tomcat Server timing out and tried every suggestion including:

  • increasing timeout seconds
  • deleting various .metadata files in workspace directory
  • deleting the server instance in Eclipse along with the Run Config

Nothing worked until I read a comment on a related issue and realized that I had added a breakpoint in an interceptor class after a big code change and had forgotten to toggle it off. I removed it and all other breakpoints and Tomcat started right up as it usually did.

In git how is fetch different than pull and how is merge different than rebase?

Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.

Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.

I would use git merge when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase is more appropriate. For more details be sure to check out this merge or rebase article.

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

Fix height of a table row in HTML Table

my css

TR.gray-t {background:#949494;}
h3{
    padding-top:3px;
    font:bold 12px/2px Arial;
}

my html

<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>

I decrease the 2nd size in font.

padding-top is used to fix the size in IE7.

Java BigDecimal: Round to the nearest whole value

Here's an awfully complicated solution, but it works:

public static BigDecimal roundBigDecimal(final BigDecimal input){
    return input.round(
        new MathContext(
            input.toBigInteger().toString().length(),
            RoundingMode.HALF_UP
        )
    );
}

Test Code:

List<BigDecimal> bigDecimals =
    Arrays.asList(new BigDecimal("100.12"),
        new BigDecimal("100.44"),
        new BigDecimal("100.50"),
        new BigDecimal("100.75"));
for(final BigDecimal bd : bigDecimals){
    System.out.println(roundBigDecimal(bd).toPlainString());
}

Output:

100
100
101
101

Should switch statements always contain a default clause?

If there is no default case in a switch statement, the behavior can be unpredictable if that case arises at some point of time, which was not predictable at development stage. It is a good practice to include a default case.

switch ( x ){
  case 0 : { - - - -}
  case 1 : { - - - -}
}

/* What happens if case 2 arises and there is a pointer
* initialization to be made in the cases . In such a case ,
* we can end up with a NULL dereference */

Such a practice can result in a bug like NULL dereference, memory leak as well as other types of serious bugs.

For example we assume that each condition initializes a pointer. But if default case is supposed to arise and if we don’t initialize in this case, then there is every possibility of landing up with a null pointer exception. Hence it is suggested to use a default case statement, even though it may be trivial.

Initialising an array of fixed size in python

If you are working with bytes you could use the builtin bytearray. If you are working with other integral types look at the builtin array.

Specifically understand that a list is not an array.

If, for example, you are trying to create a buffer for reading file contents into you could use bytearray as follows (there are better ways to do this but the example is valid):

with open(FILENAME, 'rb') as f:
    data = bytearray(os.path.getsize(FILENAME))
    f.readinto(data)

In this snippet the bytearray memory is preallocated with the fixed length of FILENAMEs size in bytes. This preallocation allows the use of the buffer protocol to more efficiently read the file into a mutable buffer without an array copy. There are yet better ways to do this but I believe this provides one answer to your question.

Calculate Age in MySQL (InnoDb)

You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2) function:

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

Demo

Cannot install node modules that require compilation on Windows 7 x64/VS2012

To do it without VS2010 installation, and only 2012, set the msvs_version flag:

node-gyp rebuild --msvs_version=2012

npm install <module> --msvs_version=2012

as per @Jacob comment

npm install --msvs_version=2013 if you have the 2013 version

How to determine whether an object has a given property in JavaScript

Underscore.js or Lodash

if (_.has(x, "y")) ...

:)

How to know if a Fragment is Visible?

getUserVisibleHint() comes as true only when the fragment is on the view and visible

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

Your http is being blocked by a firewall from F5 Networks called Application Security Manager (ASM). It produces messages like:

Please consult with your administrator.
Your support ID is: xxxxxxxxxxxx

So your application is passing some data that for some reason ASM detects as a threat. Give the support id to you network engineer to learn the specific reason.

How to find a hash key containing a matching value

You could use Enumerable#select:

clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]

Note that the result will be an array of all the matching values, where each is an array of the key and value.

Numpy: Get random set of rows from 2D array

This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).

You can get a number of random indices from your array by using:

indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)

You can then use fancy indexing with your numpy array to get the samples at those indices:

A[indices]

This will get you the specified number of random samples from your data.

Reverse colormap in matplotlib

In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors. And the module matplotlib.colors provides a function ListedColormap() to generate a color map from a list. So you can reverse any color map by doing

colormap_r = ListedColormap(colormap.colors[::-1])

Android Button setOnClickListener Design

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    Button b1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
    }

}

How to enable mod_rewrite for Apache 2.2

New apache version has change in some way. If your apache version is 2.4 then you have to go to /etc/apache2/. There will be a file named apache2.conf. You have to edit that one(you should have root permission). Change directory text like this

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Now restart apache.

service apache2 reload

Hope it works.

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Pandas rename column by position?

You can do this:

df.rename(columns={ df.columns[1]: "whatever" })

What's the best way to determine which version of Oracle client I'm running?

You can use the v$session_connect_info view against the current session ID (SID from the USERENV namespace in SYS_CONTEXT).

e.g.

SELECT
  DISTINCT
  s.client_version
FROM
  v$session_connect_info s
WHERE
  s.sid = SYS_CONTEXT('USERENV', 'SID');

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

I realize the question might be rather old, but you say the backend is running on the same server. That means on a different port, probably other than the default port 80.

I've read that when you use the "connectionManagement" configuration element, you need to specify the port number if it differs from the default 80.

LINK: maxConnection setting may not work even autoConfig = false in ASP.NET

Secondly, if you choose to use the default configuration (address="*") extended with your own backend specific value, you might consider putting the specific value first! Otherwise, if a request is made, the * matches first and the default of 2 connections is taken. Just like when you use the section in web.config.

LINK: <remove> Element for connectionManagement (Network Settings)

Hope it helps someone.

Android: show/hide a view using an animation

If you only want to animate the height of a view (from say 0 to a certain number) you could implement your own animation:

final View v = getTheViewToAnimateHere();
Animation anim=new Animation(){
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        // Do relevant calculations here using the interpolatedTime that runs from 0 to 1
        v.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, (int)(30*interpolatedTime)));
    }};
anim.setDuration(500);
v.startAnimation(anim);

What is the best way to parse html in C#?

I wrote some classes for parsing HTML tags in C#. They are nice and simple if they meet your particular needs.

You can read an article about them and download the source code at http://www.blackbeltcoder.com/Articles/strings/parsing-html-tags-in-c.

There's also an article about a generic parsing helper class at http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class.

How to insert strings containing slashes with sed?

A very useful but lesser-known fact about sed is that the familiar s/foo/bar/ command can use any punctuation, not only slashes. A common alternative is s@foo@bar@, from which it becomes obvious how to solve your problem.

Why std::cout instead of simply cout?

You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.

Remove files from Git commit

Actually, I think a quicker and easier way is to use git rebase interactive mode.

git rebase -i head~1  

(or head~4, how ever far you want to go)

and then, instead of 'pick', use 'edit'. I did not realize how powerful 'edit' is.

https://www.youtube.com/watch?v=2dQosJaLN18

Hope you will find it helpful.

Get all mysql selected rows into an array

You could try:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

My guess would be to check that the mysqli extension is enabled in your PHP configuration. More info would be great (eg. OS, AMP stack, etc.).

Check in your php.ini configuration for mysqli and make sure there is no ';' in front of the extension. The one enabled on my setup is php_mysqli_libmysql.dll.

How To Auto-Format / Indent XML/HTML in Notepad++

Just install the latest notepad++ and install indent By fold. On the menu bar select Plugins -> Plugins Admin and selct indent By fold and the install. Works finest

Python decorators in classes

Declare in inner class. This solution is pretty solid and recommended.

class Test(object):
    class Decorators(object):
    @staticmethod
    def decorator(foo):
        def magic(self, *args, **kwargs) :
            print("start magic")
            foo(self, *args, **kwargs)
            print("end magic")
        return magic

    @Decorators.decorator
    def bar( self ) :
        print("normal call")

test = Test()

test.bar()

The result:

>>> test = Test()
>>> test.bar()
start magic
normal call
end magic
>>> 

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

Pass a simple string from controller to a view MVC3

To pass a string to the view as the Model, you can do:

public ActionResult Index()
{
    string myString = "This is my string";
    return View((object)myString);
}

You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:

return View("Index", myString);

.. which is a bit more verbose.

Then in your view, just type it as a string:

@model string

<p>Value: @Model</p>

Then you can manipulate Model how you want.

For accessing it from a Layout page, it might be better to create an HtmlExtension for this:

public static string GetThemePath(this HtmlHelper helper)
{
    return "/path-to-theme";
}

Then inside your layout page:

<p>Value: @Html.GetThemePath()</p>

Hopefully you can apply this to your own scenario.

Edit: explicit HtmlHelper code:

namespace <root app namespace>
{
    public static class Helpers
    {
        public static string GetThemePath(this HtmlHelper helper)
        {
            return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
        }
    }
}

Then in your view:

@{
    var path = Html.GetThemePath();
    // .. do stuff
}

Or: <p>Path: @Html.GetThemePath()</p>

Edit 2:

As discussed, the Helper will work if you add a @using statement to the top of your view, with the namespace pointing to the one that your helper is in.

How to change Oracle default data pump directory to import dumpfile?

You can use the following command to update the DATA PUMP DIRECTORY path,

create or replace directory DATA_PUMP_DIR as '/u01/app/oracle/admin/MYDB/dpdump/';

For me data path correction was required as I have restored the my database from production to test environment.

Same command can be used to create a new DATA PUMP DIRECTORY name and path.

JQUERY ajax passing value from MVC View to Controller

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

How to edit Docker container files from the host?

I use sftp plugin from my IDE.

  1. Install ssh server for your container and allow root access.
  2. Run your docker container with -p localport:22
  3. Install from your IDE a sftp plugin

Example using sublime sftp plugin: https://www.youtube.com/watch?v=HMfjt_YMru0

Meaning of 'const' last in a function declaration of a class?

The const qualifier means that the methods can be called on any value of foobar. The difference comes when you consider calling a non-const method on a const object. Consider if your foobar type had the following extra method declaration:

class foobar {
  ...
  const char* bar();
}

The method bar() is non-const and can only be accessed from non-const values.

void func1(const foobar& fb1, foobar& fb2) {
  const char* v1 = fb1.bar();  // won't compile
  const char* v2 = fb2.bar();  // works
}

The idea behind const though is to mark methods which will not alter the internal state of the class. This is a powerful concept but is not actually enforceable in C++. It's more of a promise than a guarantee. And one that is often broken and easily broken.

foobar& fbNonConst = const_cast<foobar&>(fb1);

SQLAlchemy ORDER BY DESCENDING?

One other thing you might do is:

.order_by("name desc")

This will result in: ORDER BY name desc. The disadvantage here is the explicit column name used in order by.

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Webpack how to build production code and how to use it

Just learning this myself. I will answer the second question:

  1. How to use these files? Currently I am using webpack-dev-server to run the application.

Instead of using webpack-dev-server, you can just run an "express". use npm install "express" and create a server.js in the project's root dir, something like this:

var path = require("path");
var express = require("express");

var DIST_DIR = path.join(__dirname, "build");
var PORT = 3000;
var app = express();

//Serving the files on the dist folder
app.use(express.static(DIST_DIR));

//Send index.html when the user access the web
app.get("*", function (req, res) {
  res.sendFile(path.join(DIST_DIR, "index.html"));
});

app.listen(PORT);

Then, in the package.json, add a script:

"start": "node server.js"

Finally, run the app: npm run start to start the server

A detailed example can be seen at: https://alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/ (the example code is not compatible with the latest packages, but it will work with small tweaks)

Convert double to float in Java

Converting from double to float will be a narrowing conversion. From the doc:

A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

So it is not a good idea. If you still want it you can do it like:

double d = 3.0;
float f = (float) d;

Display JSON as HTML

Here's a light-weight solution, doing only what OP asked, including highlighting but nothing else: How can I pretty-print JSON using JavaScript?

How to apply a CSS class on hover to dynamically generated submit buttons?

The most efficient selector you can use is an attribute selector.

 input[name="btnPage"]:hover {/*your css here*/}

Here's a live demo: http://tinkerbin.com/3G6B93Cb

Android Studio drawable folders

In Android Studio 1.2.1.1

Just copy the image and paste the image into the app > res > drawable folder and it will shows you "Choose Destination Directory" popup screen as shown below screen

enter image description here

Now you can select option whatever resolution you want to place and if you want to view the those image into the folders then simply right click on the drawable folder > select copy paths option and open it. It will help you.

How to check the value given is a positive or negative integer?

Starting from the base that the received value is a number and not a string, what about use Math.abs()? This JavaScript native function returns the absolute value of a number:

Math.abs(-1) // 1

So you can use it this way:

var a = -1;
if(a == Math.abs(a)){
    // false 
}

var b = 1;   
if(b == Math.abs(b)){
    // true
}

Override hosts variable of Ansible playbook from the command line

I changed mine to default to no host and have a check to catch it. That way the user or cron is forced to provide a single host or group etc. I like the logic from the comment from @wallydrag. The empty_group contains no hosts in the inventory.

- hosts: "{{ variable_host | default('empty_group') }}"

Then add the check in tasks:

   tasks:
   - name: Fail script if required variable_host parameter is missing
     fail:
       msg: "You have to add the --extra-vars='variable_host='"
     when: (variable_host is not defined) or (variable_host == "")

Actual meaning of 'shell=True' in subprocess

The benefit of not calling via the shell is that you are not invoking a 'mystery program.' On POSIX, the environment variable SHELL controls which binary is invoked as the "shell." On Windows, there is no bourne shell descendent, only cmd.exe.

So invoking the shell invokes a program of the user's choosing and is platform-dependent. Generally speaking, avoid invocations via the shell.

Invoking via the shell does allow you to expand environment variables and file globs according to the shell's usual mechanism. On POSIX systems, the shell expands file globs to a list of files. On Windows, a file glob (e.g., "*.*") is not expanded by the shell, anyway (but environment variables on a command line are expanded by cmd.exe).

If you think you want environment variable expansions and file globs, research the ILS attacks of 1992-ish on network services which performed subprogram invocations via the shell. Examples include the various sendmail backdoors involving ILS.

In summary, use shell=False.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

Since this is the most active message for this type of error, I wanted to mention my solution (after spending hours to fix this).

On Ubuntu 18.04, using Chrome 70 and Chromedriver 2.44, and Python3 I kept getting the same DevToolsActivePort error, even when I disabled all options listed above. The chromedriver log file as well as ps showed that the chromedriver I set in chrome_options.binary_location was running, but it always gave DevToolsActivePort error. When I removed chrome_options.binary_location='....' and add it to webdriver creation, I get it working fine. webdriver.Chrome('/path to ... /chromedriver',chrome_options=chrome_options)

Thanks everybody for your comments that make me understand and resolve the issue.

Where do I find old versions of Android NDK?

http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

I successfully opened gstreamer SDK tutorials in Eclipse.

All I needed is to use an older version of ndk. specificly 9d.

(10c and 10d does not work, 10b - works just for tutorial-1 )

9d does work for all tutorials ! and you can:

  1. Download it from: http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

  2. Extract it.

  3. set it in eclipse->window->preferences->Android->NDK->NDK location.

  4. build - (ctrl+b).

Removing carriage return and new-line from the end of a string in c#

This is what I got to work for me.

s.Replace("\r","").Replace("\n","")

Using reCAPTCHA on localhost

To your domains list of google recaptcha website add - https://www.google.com/recaptcha/admin/site/{siteid}/settings

LOCALHOST
if above doesn't work try adding 127.0.0.1 too

How to call a shell script from python code?

Subprocess is good but some people may like scriptine better. Scriptine has more high-level set of methods like shell.call(args), path.rename(new_name) and path.move(src,dst). Scriptine is based on subprocess and others.

Two drawbacks of scriptine:

  • Current documentation level would be more comprehensive even though it is sufficient.
  • Unlike subprocess, scriptine package is currently not installed by default.

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

Select rows having 2 columns equal value

For question 1:

SELECT DISTINCT a.*
  FROM [Table] a
  INNER JOIN
  [Table] b
  ON
  a.C1 <> b.C1 AND a.C2 = b.C2 AND a.C3 = b.C3 AND a.C4 = b.C4

Using an inner join is much more efficient than a subquery because it requires fewer operations, and maintains the use of indexes when comparing the values, allowing the SQL server to better optimize the query before its run. Using appropriate indexes with this query can bring your query down to only n * log(n) rows to compare.

Using a subquery with your where clause or only doing a standard join where C1 does not equal C2 results in a table that has roughly 2 to the power of n rows to compare, where n is the number of rows in the table.

So by using proper indexing with an Inner Join, which only returns records which met the join criteria, we're able to drastically improve the performance. Also note that we return DISTINCT a.*, because this will only return the columns for table a where the join criteria was met. Returning * would return the columns for both a and b where the criteria was met, and not including DISTINCT would result in a duplicate of each row for each time that row row matched another row more than once.

A similar approach could also be performed using CROSS APPLY, which still uses a subquery, but makes use of indexes more efficiently.

An implementation with the keyword USING instead of ON could also work, but the syntax is more complicated to make work because your want to match on rows where C1 does not match, so you would need an additional where clause to filter out matching each row with itself. Also, USING is not compatible/allowed in conjunction with table values in all implementations of SQL, so it's best to stick with ON.

Similarly, for question 2:

SELECT DISTINCT a.*
  FROM [Table] a
  INNER JOIN
  [Table] b
  ON
  a.C1 <> b.C1 AND a.C4 = b.C4

This is essentially the same query as for 1, but because it only wants to know which rows match for C4, we only compare on the rows for C4.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

Insert NULL value into INT column

Just use the insert query and put the NULL keyword without quotes. That will work-

INSERT INTO `myDatabase`.`myTable` (`myColumn`) VALUES (NULL);

Getting date format m-d-Y H:i:s.u from milliseconds

I'm use

echo date("Y-m-d H:i:s.").gettimeofday()["usec"];

output: 2017-09-05 17:04:57.555036

MySQL Select all columns from one table and some from another table

select a.* , b.Aa , b.Ab, b.Ac from table1 a left join table2 b on a.id=b.id

this should select all columns from table 1 and only the listed columns from table 2 joined by id.

Rock, Paper, Scissors Game Java

Why not check for what the user entered and then ask the user to enter correct input again?

eg:

//Get player's play from input-- note that this is 
// stored as a string 
System.out.println("Enter your play: "); 
response = scan.next();
if(response=="R"||response=="P"||response=="S"){
  personPlay = response;
}else{
  System.out.println("Invaild Input")
}

for the other modifications, please check my total code at pastebin

how to kill hadoop jobs

Run list to show all the jobs, then use the jobID/applicationID in the appropriate command.

Kill mapred jobs:

mapred job -list
mapred job -kill <jobId>

Kill yarn jobs:

yarn application -list
yarn application -kill <ApplicationId>

How to run python script in webpage

using flask library in Python you can achieve that. remember to store your HTML page to a folder named "templates" inside where you are running your python script.

so your folder would look like

  1. templates (folder which would contain your HTML file)
  2. your python script

this is a small example of your python script. This simply checks for plagiarism.

from flask import Flask
from flask import request
from flask import render_template
import stringComparison

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("my-form.html") # this should be the name of your html file

@app.route('/', methods=['POST'])
def my_form_post():
    text1 = request.form['text1']
    text2 = request.form['text2']
    plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
    if plagiarismPercent > 50 :
        return "<h1>Plagiarism Detected !</h1>"
    else :
        return "<h1>No Plagiarism Detected !</h1>"

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

This a small template of HTML file that is used

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Enter the texts to be compared</h1>
    <form action="." method="POST">
        <input type="text" name="text1">
        <input type="text" name="text2">
        <input type="submit" name="my-form" value="Check !">
    </form>
</body>
</html>

This is a small little way through which you can achieve a simple task of comparing two string and which can be easily changed to suit your requirements

How to print a dictionary line by line in Python?

You could use the json module for this. The dumps function in this module converts a JSON object into a properly formatted string which you can then print.

import json

cars = {'A':{'speed':70, 'color':2},
        'B':{'speed':60, 'color':3}}

print(json.dumps(cars, indent = 4))

The output looks like

{
    "A": {
        "color": 2,
        "speed": 70
    },
    "B": {
        "color": 3,
        "speed": 60
    }
}

The documentation also specifies a bunch of useful options for this method.

Could not load file or assembly for Oracle.DataAccess in .NET

I was facing the same issue for a couple of days then I figure out that the Oracle.DataAccess is available in the references list of the project, but in the bin folder is missing. So I removed it from the references list and readded again.

git rm - fatal: pathspec did not match any files

A very simple answer is.

Step 1:

Firstly add your untracked files to which you want to delete:

using git add . or git add <filename>.

Step 2:

Then delete them easily using command git rm -f <filename> here rm=remove and -f=forcely.

How to stretch in width a WPF user control to its window?

You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!

EDIT: This is the code I tested it with:

SOUserAnswerTest.xaml:

<UserControl x:Class="WpfApplication1.SOAnswerTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="LeftSideMenu" Width="100"/>
            <ColumnDefinition Name="Middle" Width="*"/>
            <ColumnDefinition Name="RightSideMenu" Width="90"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0">a</TextBlock>
        <TextBlock Grid.Column="1">b</TextBlock>
        <TextBlock Grid.Column="2">c</TextBlock>
    </Grid>
</UserControl>

Window1.xaml:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="415">
    <Grid>

        <local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
    </Grid>
</Window>

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

#1214 - The used table type doesn't support FULLTEXT indexes

Only MyISAM allows for FULLTEXT, as seen here.

Try this:

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

how to get all markers on google-maps-v3

I'm assuming you have multiple markers that you wish to display on a google map.

The solution is two parts, one to create and populate an array containing all the details of the markers, then a second to loop through all entries in the array to create each marker.

Not know what environment you're using, it's a little difficult to provide specific help.

My best advice is to take a look at this article & accepted answer to understand the principals of creating a map with multiple markers: Display multiple markers on a map with their own info windows

How do I find the number of arguments passed to a Bash script?

to add the original reference:

You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $# is read-only.

When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

see Bash Reference Manual in section 3.4.2 Special Parameters:

  • "The shell treats several parameters specially. These parameters may only be referenced"

  • and in this section for keyword $# "Expands to the number of positional parameters in decimal."

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

The best way I have found to get a feel for things like this is to try them out:

import java.io.File;
public class PathTesting {
    public static void main(String [] args) {
        File f = new File("test/.././file.txt");
        System.out.println(f.getPath());
        System.out.println(f.getAbsolutePath());
        try {
            System.out.println(f.getCanonicalPath());
        }
        catch(Exception e) {}
    }
}

Your output will be something like:

test\..\.\file.txt
C:\projects\sandbox\trunk\test\..\.\file.txt
C:\projects\sandbox\trunk\file.txt

So, getPath() gives you the path based on the File object, which may or may not be relative; getAbsolutePath() gives you an absolute path to the file; and getCanonicalPath() gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.

When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths. Just one example.

How to automatically allow blocked content in IE?

I believe this will only appear when running the page locally in this particular case, i.e. you should not see this when loading the apge from a web server.

However if you have permission to do so, you could turn off the prompt for Internet Explorer by following Tools (menu) → Internet OptionsSecurity (tab) → Custom Level (button) → and Disable Automatic prompting for ActiveX controls.

This will of course, only affect your browser.

Change the URL in the browser without loading the new page using JavaScript

There is a Yahoo YUI component (Browser History Manager) which can handle this: http://developer.yahoo.com/yui/history/

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

How to stretch the background image to fill a div

You can add:

#div2{
    background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
    background-size: 100% 100%;
    height:180px;
    width:200px;
    border: 1px solid red;
}

You can read more about it here: css3 background-size

How to convert milliseconds to seconds with precision

I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.

double time_seconds = time_milliseconds / 1000.0;   // add the decimal
System.out.println(time_milliseconds);              // Now this should give you the right value.

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

jquery UI dialog: how to initialize without a title bar?

If you have multiple dialog, you can use this:

$("#the_dialog").dialog({
        open: function(event, ui) { 
            //hide titlebar.
            $(this).parent().children('.ui-dialog-titlebar').hide();
        }
    });

Insert into C# with SQLCommand

Use AddWithValue(), but be aware of the possibility of the wrong implicit type conversion.
like this:

cmd.Parameters.AddWithValue("@param1", klantId);
    cmd.Parameters.AddWithValue("@param2", klantNaam);
    cmd.Parameters.AddWithValue("@param3", klantVoornaam);

How to add "active" class to wp_nav_menu() current menu item (simple way)

To also highlight the menu item when one of the child pages is active, also check for the other class (current-page-ancestor) like below:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    }
    return $classes;
}

How to copy text programmatically in my Android app?

@FlySwat already gave the correct answer, I am just sharing the complete answer:

Use ClipboardManager.setPrimaryClip (http://developer.android.com/reference/android/content/ClipboardManager.html) method:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip); 

Where label is a User-visible label for the clip data and text is the actual text in the clip. According to official docs.

It is important to use this import:

import android.content.ClipboardManager;

How do I access Configuration in any class in ASP.NET Core?

There is also an option to make configuration static in startup.cs so that what you can access it anywhere with ease, static variables are convenient huh!

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

internal static IConfiguration Configuration { get; private set; }

This makes configuration accessible anywhere using Startup.Configuration.GetSection... What can go wrong?

How to instantiate a javascript class in another js file?

Make sure the dom is loaded before you run your code in file2... If you're using jQuery:

$(function(){
  var customer=customer();
  var name=customer.getName();
});

Then it doesn't matter what order the files are in, the code won't run until all of the files are loaded.

stopPropagation vs. stopImmediatePropagation

event.stopPropagation will prevent handlers on parent elements from running.
Calling event.stopImmediatePropagation will also prevent other handlers on the same element from running.

Using setImageDrawable dynamically to set image in an ImageView

btnImg.SetImageDrawable(GetDrawable(Resource.Drawable.button_round_green));

API 23 Android 6.0

How to substring in jquery

Using .split(). (Second version uses .slice() and .join() on the Array.)

var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer

Using .replace().

var result = name.replace('name','');

Using .slice() on a String.

var result = name.slice( 4 );

Check if multiple strings exist in another string

Just some more info on how to get all list elements availlable in String

a = ['a', 'b', 'c']
str = "a123" 
list(filter(lambda x:  x in str, a))

How to count number of files in each directory?

Easy way to recursively find files of a given type. In this case, .jpg files for all folders in current directory:

find . -name *.jpg -print | wc -l

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

for iOS 8 and above

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Performance of Java matrix math libraries?

I just compared Apache Commons Math with jlapack.

Test: singular value decomposition of a random 1024x1024 matrix.

Machine: Intel(R) Core(TM)2 Duo CPU E6750 @ 2.66GHz, linux x64

Octave code: A=rand(1024); tic;[U,S,V]=svd(A);toc

results                                execution time
---------------------------------------------------------
Octave                                 36.34 sec

JDK 1.7u2 64bit
    jlapack dgesvd                     37.78 sec
    apache commons math SVD            42.24 sec


JDK 1.6u30 64bit
    jlapack dgesvd                     48.68 sec
    apache commons math SVD            50.59 sec

Native routines
Lapack* invoked from C:                37.64 sec
Intel MKL                               6.89 sec(!)

My conclusion is that jlapack called from JDK 1.7 is very close to the native binary performance of lapack. I used the lapack binary library coming with linux distro and invoked the dgesvd routine to get the U,S and VT matrices as well. All tests were done using double precision on exactly the same matrix each run (except Octave).

Disclaimer - I'm not an expert in linear algebra, not affiliated to any of the libraries above and this is not a rigorous benchmark. It's a 'home-made' test, as I was interested comparing the performance increase of JDK 1.7 to 1.6 as well as commons math SVD to jlapack.

Using variables inside a bash heredoc

In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]

If you change your first example to use <<EOF instead of << "EOF" you'll find that it works.

In your second example, the shell invokes sudo only with the parameter cat, and the redirection applies to the output of sudo cat as the original user. It'll work if you try:

sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT

data.frame rows to a list

The by_row function from the purrrlyr package will do this for you.

This example demonstrates

myfn <- function(row) {
  #row is a tibble with one row, and the same number of columns as the original df
  l <- as.list(row)
  return(l)
}

list_of_lists <- purrrlyr::by_row(df, myfn, .labels=FALSE)$.out

By default, the returned value from myfn is put into a new list column in the df called .out. The $.out at the end of the above statement immediately selects this column, returning a list of lists.

How to SELECT a dropdown list item by value programmatically

This is a simple way to select an option from a dropdownlist based on a string val

private void SetDDLs(DropDownList d,string val)
    {
        ListItem li;
        for (int i = 0; i < d.Items.Count; i++)
        {
            li = d.Items[i];
            if (li.Value == val)
            {
                d.SelectedIndex = i;
                break;
            }
        }
    }

VIM Disable Automatic Newline At End Of File

I think I've found a better solution than the accepted answer. The alternative solutions weren't working for me and I didn't want to have to work in binary mode all the time. Fortunately this seems to get the job done and I haven't encountered any nasty side-effects yet: preserve missing end-of-line at end of text files. I just added the whole thing to my ~/.vimrc.

Stop all active ajax requests in jQuery

Here's how to hook this up on any click (useful if your page is placing many AJAX calls and you're trying to navigate away).

$ ->
    $.xhrPool = [];

$(document).ajaxSend (e, jqXHR, options) ->
    $.xhrPool.push(jqXHR)

$(document).ajaxComplete (e, jqXHR, options) ->
    $.xhrPool = $.grep($.xhrPool, (x) -> return x != jqXHR);

$(document).delegate 'a', 'click', ->
    while (request = $.xhrPool.pop())
      request.abort()

Disable all table constraints in Oracle

It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.

It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.

BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name
   AND c.status = 'ENABLED'
   AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
   ORDER BY c.constraint_type DESC)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
  END LOOP;
END;
/

Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.

BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name
   AND c.status = 'DISABLED'
   ORDER BY c.constraint_type)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
  END LOOP;
END;
/

How to convert List to Json in Java

Try this:

public void test(){
// net.sf.json.JSONObject, net.sf.json.JSONArray    

List objList = new ArrayList();
objList.add("obj1");
objList.add("obj2");
objList.add("obj3");
HashMap objMap = new HashMap();
objMap.put("key1", "value1");
objMap.put("key2", "value2");
objMap.put("key3", "value3");
System.out.println("JSONArray :: "+(JSONArray)JSONSerializer.toJSON(objList));
System.out.println("JSONObject :: "+(JSONObject)JSONSerializer.toJSON(objMap));
}

you can find API here.

How to Display Selected Item in Bootstrap Button Dropdown Title

Further modified based on answer from @Kyle as $.text() returns exact string, so the caret tag is printed literally, than as a markup, just in case someone would like to keep the caret intact in dropdown.

$(".dropdown-menu li").click(function(){
  $(this).parents(".btn-group").find('.btn').html(
  $(this).text()+" <span class=\"caret\"></span>"
  );
});

Calculating percentile of dataset column

table_ages <- subset(infert, select=c("age"))
summary(table_ages)
#            age       
#  Min.   :21.00  
#  1st Qu.:28.00  
#  Median :31.00  
#  Mean   :31.50  
#  3rd Qu.:35.25  
#  Max.   :44.00  

This is probably what they're looking for. summary(...) applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.

Note that

summary(infert$age)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#   21.00   28.00   31.00   31.50   35.25   44.00 

The numbers are the same but the format is different. This is because table_ages is a data frame with one column (ages), whereas infert$age is a numeric vector. Try typing summary(infert).

Where does Android emulator store SQLite database?

according to Android docs, Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To access files, there is a tab in android studio called "Device File Explorer" bottom-right side of developing window which you can access your emulator file system. Just follow

/data/data/package_name/databases

good luck.

Android device File explorer

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

What is the purpose of the : (colon) GNU Bash builtin?

Two more uses not mentioned in other answers:

Logging

Take this example script:

set -x
: Logging message here
example_command

The first line, set -x, makes the shell print out the command before running it. It's quite a useful construct. The downside is that the usual echo Log message type of statement now prints the message twice. The colon method gets round that. Note that you'll still have to escape special characters just like you would for echo.

Cron job titles

I've seen it being used in cron jobs, like this:

45 10 * * * : Backup for database ; /opt/backup.sh

This is a cron job that runs the script /opt/backup.sh every day at 10:45. The advantage of this technique is that it makes for better looking email subjects when the /opt/backup.sh prints some output.

What is PHPSESSID?

PHP uses one of two methods to keep track of sessions. If cookies are enabled, like in your case, it uses them.

If cookies are disabled, it uses the URL. Although this can be done securely, it's harder and it often, well, isn't. See, e.g., session fixation.

Search for it, you will get lots of SEO advice. The conventional wisdom is that you should use the cookies, but php will keep track of the session either way.

Remove the title bar in Windows Forms

 Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None

surface plots in matplotlib

You can read data direct from some file and plot

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from sys import argv

x,y,z = np.loadtxt('your_file', unpack=True)

fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('teste.pdf')
plt.show()

If necessary you can pass vmin and vmax to define the colorbar range, e.g.

surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1, vmin=0, vmax=2000)

surface

Bonus Section

I was wondering how to do some interactive plots, in this case with artificial data

from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import Image

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d

def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

def plot(i):

    fig = plt.figure()
    ax = plt.axes(projection='3d')

    theta = 2 * np.pi * np.random.random(1000)
    r = i * np.random.random(1000)
    x = np.ravel(r * np.sin(theta))
    y = np.ravel(r * np.cos(theta))
    z = f(x, y)

    ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
    fig.tight_layout()

interactive_plot = interactive(plot, i=(2, 10))
interactive_plot

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

What is the purpose of nameof?

The ASP.NET Core MVC project uses nameof in the AccountController.cs and ManageController.cs with the RedirectToAction method to reference an action in the controller.

Example:

return RedirectToAction(nameof(HomeController.Index), "Home");

This translates to:

return RedirectToAction("Index", "Home");

and takes takes the user to the 'Index' action in the 'Home' controller, i.e. /Home/Index.

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

A good alternative is SqlCmd, since it does include headers, but it has the downside of adding space padding around the data for human readability. You can combine SqlCmd with the GnuWin32 sed (stream editing) utility to cleanup the results. Here's an example that worked for me, though I can't guarantee that it's bulletproof.

First, export the data:

sqlcmd -S Server -i C:\Temp\Query.sql -o C:\Temp\Results.txt -s"    "

The -s" " is a tab character in double quotes. I found that you have to run this command via a batch file, otherwise the Windows command prompt will treat the tab as an automatic completion command and will substitute a filename in place of the tab.

If Query.sql contains:

SELECT name, object_id, type_desc, create_date
FROM MSDB.sys.views
WHERE name LIKE 'sysmail%'

then you'll see something like this in Results.txt

name                                          object_id   type_desc           create_date            
-------------------------------------------   ----------- ------------------- -----------------------
sysmail_allitems                               2001442204 VIEW                2012-07-20 17:38:27.820
sysmail_sentitems                              2017442261 VIEW                2012-07-20 17:38:27.837
sysmail_unsentitems                            2033442318 VIEW                2012-07-20 17:38:27.850
sysmail_faileditems                            2049442375 VIEW                2012-07-20 17:38:27.860
sysmail_mailattachments                        2097442546 VIEW                2012-07-20 17:38:27.933
sysmail_event_log                              2129442660 VIEW                2012-07-20 17:38:28.040

(6 rows affected)

Next, parse the text using sed:

sed -r "s/ +\t/\t/g" C:\Temp\Results.txt | sed -r "s/\t +/\t/g" | sed -r "s/(^ +| +$)//g" | sed 2d | sed $d | sed "/^$/d" > C:\Temp\Results_New.txt

Note that the 2d command means to delete the second line, the $d command means to delete the last line, and "/^$/d" deletes any blank lines.

The cleaned up file looks like this (though I replaced the tabs with | so they could be visualized here):

name|object_id|type_desc|create_date
sysmail_allitems|2001442204|VIEW|2012-07-20 17:38:27.820
sysmail_sentitems|2017442261|VIEW|2012-07-20 17:38:27.837
sysmail_unsentitems|2033442318|VIEW|2012-07-20 17:38:27.850
sysmail_faileditems|2049442375|VIEW|2012-07-20 17:38:27.860
sysmail_mailattachments|2097442546|VIEW|2012-07-20 17:38:27.933
sysmail_event_log|2129442660|VIEW|2012-07-20 17:38:28.040

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Killing a process created with Python's subprocess.Popen()

process.terminate() doesn't work when using shell=True. This answer will help you.

Apache2: 'AH01630: client denied by server configuration'

Ensure that any user-specific configs are included!

If none of the other answers on this page for you work, here's what I ran into after hours of floundering around.

I used user-specific configurations, with Sites specified as my UserDir in /private/etc/apache2/extra/httpd-userdir.conf. However, I was forbidden access to the endpoint http://localhost/~jwork/.

I could see in /var/log/apache2/error_log that access to /Users/jwork/Sites/ was being blocked. However, I was permitted to access the DocumentRoot, via http://localhost/. This suggested that I didn't have rights to view the ~jwork user. But as far as I could tell by ps aux | egrep '(apache|httpd)' and lsof -i :80, Apache was running for the jwork user, so something was clearly not write with my user configuration.

Given a user named jwork, here was my config file:

/private/etc/apache2/users/jwork.conf

<Directory "/Users/jwork/Sites/">
    Require all granted
</Directory>

This config is perfectly valid. However, I found that my user config wasn't being included:

/private/etc/apache2/extra/httpd-userdir.conf

## Note how it's commented out by default.
## Just remove the comment to enable your user conf.
#Include /private/etc/apache2/users/*.conf

Note that this is the default path to the userdir conf file, but as you'll see below, it's configurable in httpd.conf. Ensure that the following lines are enabled:

/private/etc/apache2/httpd.conf

Include /private/etc/apache2/extra/httpd-userdir.conf

# ...

LoadModule userdir_module libexec/apache2/mod_userdir.so

function is not defined error in Python

Yes, but in what file is pyth_test's definition declared in? Is it also located before it's called?

Edit:

To put it into perspective, create a file called test.py with the following contents:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

Now run the following command:

python test.py

You should see the output you desire. Now if you are in an interactive session, it should go like this:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

I hope this explains how the declaration works.


To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

Now if you run:

python program.py

It will print out 3. Now to explain what went wrong, let's modify our program this way:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now let's see what happens:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.

Now then, if we run the interactive python session:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

The same process applies. Now, package importing isn't all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!

Volatile vs Static in Java

volatile variable value access will be direct from main memory. It should be used only in multi-threading environment. static variable will be loaded one time. If its used in single thread environment, even if the copy of the variable will be updated and there will be no harm accessing it as there is only one thread.

Now if static variable is used in multi-threading environment then there will be issues if one expects desired result from it. As each thread has their own copy then any increment or decrement on static variable from one thread may not reflect in another thread.

if one expects desired results from static variable then use volatile with static in multi-threading then everything will be resolved.

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

UITableView.automaticDimension can be set via Interface Builder:

Xcode > Storyboard > Size Inspector

Table View Cell > Row Height > Automatic

Size Inspector

How do I make a text go onto the next line if it overflows?

In order to use word-wrap: break-word, you need to set a width (in px). For example:

div {
    width: 250px;
    word-wrap: break-word;
}

word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.

What do I do when my program crashes with exception 0xc0000005 at address 0?

Exception code 0xc0000005 is an Access Violation. An AV at fault offset 0x00000000 means that something in your service's code is accessing a nil pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.

How can I find the length of a number?

Yes you need to convert to string in order to find the length.For example

var x=100;// type of x is number
var x=100+"";// now the type of x is string
document.write(x.length);//which would output 3.

How to set border on jPanel?

BorderLayout(int Gap, int Gap) or GridLayout(int Gap, int Gap, int Gap, int Gap)

why paint Border() inside paintComponent( ...)

    Border line, raisedbevel, loweredbevel, title, empty;
    line = BorderFactory.createLineBorder(Color.black);
    raisedbevel = BorderFactory.createRaisedBevelBorder();
    loweredbevel = BorderFactory.createLoweredBevelBorder();
    title = BorderFactory.createTitledBorder("");
    empty = BorderFactory.createEmptyBorder(4, 4, 4, 4);
    Border compound = BorderFactory.createCompoundBorder(empty, xxx);
    Color crl = (Color.blue);
    Border compound1 = BorderFactory.createCompoundBorder(empty, xxx);

How do I find the value of $CATALINA_HOME?

Just as a addition. You can find the Catalina Paths in

->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS

In the VM Arguments the Paths are listed and changeable

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

Call asynchronous method in constructor?

A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.

new Action( async() => await InitializeThingsAsync())();

Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.

A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init or onload or navigated overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.

how to install apk application from my pc to my mobile android

To install an APK on your mobile, you can either:

  1. Use ADB from the Android SDK, and do the following command: adb install filename.apk. Note, you'll need to enable USB debugging for this to work.
  2. Transfer the file to your device, then open it with a file manager, such as Linda File Manager.

Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.

As for getting USB to work, I suggest consulting the Android StackExchange for advice.

JavaFX - create custom button with image

There are a few different ways to accomplish this, I'll outline my favourites.

Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.

My preferred method is to define a graphic for the button in css:

.toggle-button {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}

.toggle-button:selected {
  -fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

OR use the attached css to define a background image.

// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
  -fx-background-repeat: no-repeat;
  -fx-background-position: center;
}

.toggle-button:selected {
  -fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}

I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.

And some sample code:

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImage extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle = new ToggleButton();
    toggle.getStylesheets().add(this.getClass().getResource(
      "imagetogglebutton.css"
    ).toExternalForm());
    toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

Some advantages of doing this are:

  1. You get the default toggle button behavior and don't have to re-implement it yourself by adding your own focus styling, mouse and key handlers etc.
  2. If your app gets ported to different platform such as a mobile device, it will work out of the box responding to touch events rather than mouse events, etc.
  3. Your styling is separated from your application logic so it is easier to restyle your application.

An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;

public class ToggleButtonImageViaGraphic extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    final ToggleButton toggle      = new ToggleButton();
    final Image        unselected  = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
    );
    final Image        selected    = new Image(
      "http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
    );
    final ImageView    toggleImage = new ImageView();
    toggle.setGraphic(toggleImage);
    toggleImage.imageProperty().bind(Bindings
      .when(toggle.selectedProperty())
        .then(selected)
        .otherwise(unselected)
    );

    stage.setScene(new Scene(
      StackPaneBuilder.create()
        .children(toggle)
        .style("-fx-padding:10; -fx-background-color: cornsilk;")
        .build()
    ));
    stage.show();
  }
}

The code based approach has the advantage that you don't have to use css if you are unfamilar with it.

For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

How to convert a Java String to an ASCII byte array?

I found the solution. Actually Base64 class is not available in Android. Link is given below for more information.

byte[] byteArray;                                                  
     byteArray= json.getBytes(StandardCharsets.US_ASCII);
    String encoded=Base64.encodeBytes(byteArray);
    userLogin(encoded);

Here is the link for Base64 class: http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

React component initialize state from props

You can use componentWillReceiveProps.

constructor(props) {
    super(props);
    this.state = {
      productdatail: ''
    };
}

componentWillReceiveProps(nextProps){
    this.setState({ productdatail: nextProps.productdetailProps })
}

how to get request path with express req object

For version 4.x you can now use the req.baseUrl in addition to req.path to get the full path. For example, the OP would now do something like:

//auth required or redirect
app.use('/account', function(req, res, next) {
  console.log(req.baseUrl + req.path);  // => /account

  if(!req.session.user) {
    res.redirect('/login?ref=' + encodeURIComponent(req.baseUrl + req.path));  // => /login?ref=%2Faccount
  } else {
    next();
  }
});

Foreign key constraints: When to use ON UPDATE and ON DELETE

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

How long is the SHA256 hash?

A sha256 is 256 bits long -- as its name indicates.

Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not varying at all.

And the demo :

$hash = hash('sha256', 'hello, world!');
var_dump($hash);

Will give you :

$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"

i.e. a string with 64 characters.

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

@class vs. #import

Another advantage: Quick compilation

If you include a header file, any change in it causes the current file also to compile but this is not the case if the class name is included as @class name. Of course you will need to include the header in source file

Parse v. TryParse

If the string can not be converted to an integer, then

  • int.Parse() will throw an exception
  • int.TryParse() will return false (but not throw an exception)

python modify item in list, save back in list

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
    ListOfStrings[idx] = "bar"

How to run multiple .BAT files within a .BAT file

Use:

call msbuild.bat
call unit-tests.bat
call deploy.bat

When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.

document.getElementById().value and document.getElementById().checked not working for IE

For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:

HTML:

<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">

Javascript:

var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;

For more details

please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/

JQuery .on() method with multiple event handlers to one selector

Try with the following code:

$("textarea[id^='options_'],input[id^='options_']").on('keyup onmouseout keydown keypress blur change', 
  function() {

  }
);

URL string format for connecting to Oracle database with JDBC

The correct format for url can be one of the following formats:

jdbc:oracle:thin:@<hostName>:<portNumber>:<sid>;  (if you have sid)
jdbc:oracle:thin:@//<hostName>:<portNumber>/serviceName; (if you have oracle service name)

And don't put any space there. Try to use 1521 as port number. sid (database name) must be the same as the one which is in environment variables (if you are using windows).

Configure WAMP server to send email

You need a SMTP server to send your mail. If you have one available which does not require SMTP authentification (maybe your ISP's?) just edit the 'SMTP' ([mail function]) setting in your php.ini file.

If this is no option because your SMTP server requires authentification you won't be able to use the internal mail() function and have to use some 3rd party class which supports smtp auth. e.g. http://pear.php.net/package/Mail/

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

--The following may give you more of what you're looking for:

create Procedure spShowRelationShips 
( 
    @Table varchar(250) = null,
    @RelatedTable varchar(250) = null
)
as
begin
    if @Table is null and @RelatedTable is null
        select  object_name(k.constraint_object_id) ForeginKeyName, 
                object_name(k.Parent_Object_id) TableName, 
                object_name(k.referenced_object_id) RelatedTable, 
                c.Name RelatedColumnName,  
                object_name(rc.object_id) + '.' + rc.name RelatedKeyField
        from sys.foreign_key_columns k
        left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
        left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
        order by 2,3

    if @Table is not null and @RelatedTable is null
        select  object_name(k.constraint_object_id) ForeginKeyName, 
                object_name(k.Parent_Object_id) TableName, 
                object_name(k.referenced_object_id) RelatedTable, 
                c.Name RelatedColumnName,  
                object_name(rc.object_id) + '.' + rc.name RelatedKeyField
        from sys.foreign_key_columns k
        left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
        left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
        where object_name(k.Parent_Object_id) =@Table
        order by 2,3

    if @Table is null and @RelatedTable is not null
        select  object_name(k.constraint_object_id) ForeginKeyName, 
                object_name(k.Parent_Object_id) TableName, 
                object_name(k.referenced_object_id) RelatedTable, 
                c.Name RelatedColumnName,  
                object_name(rc.object_id) + '.' + rc.name RelatedKeyField
        from sys.foreign_key_columns k
        left join sys.columns c on object_name(c.object_id) = object_name(k.Parent_Object_id) and c.column_id = k.parent_column_id
        left join sys.columns rc on object_name(rc.object_id) = object_name(k.referenced_object_id) and rc.column_id = k.referenced_column_id
        where object_name(k.referenced_object_id) =@RelatedTable
        order by 2,3



end

Stick button to right side of div

Use position property

style="position: absolute;right:0;top:0"

The difference between "require(x)" and "import x"

The major difference between require and import, is that require will automatically scan node_modules to find modules, but import, which comes from ES6, won't.

Most people use babel to compile import and export, which makes import act the same as require.

The future version of Node.js might support import itself (actually, the experimental version already does), and judging by Node.js' notes, import won't support node_modules, it base on ES6, and must specify the path of the module.

So I would suggest you not use import with babel, but this feature is not yet confirmed, it might support node_modules in the future, who would know?


For reference, below is an example of how babel can convert ES6's import syntax to CommonJS's require syntax.

Say the fileapp_es6.js contains this import:

import format from 'date-fns/format';

This is a directive to import the format function from the node package date-fns.

The related package.json file could contain something like this:

"scripts": {
    "start": "node app.js",
    "build-server-file": "babel app_es6.js --out-file app.js",
    "webpack": "webpack"
}

The related .babelrc file could be something like this:

{
    "presets": [
        [
            "env",
            {
                "targets":
                {
                    "node": "current"
                }
            }
        ]
    ]
}

This build-server-file script defined in the package.json file is a directive for babel to parse the app_es6.js file and output the file app.js.

After running the build-server-file script, if you open app.js and look for the date-fns import, you will see it has been converted into this:

var _format = require("date-fns/format");

var _format2 = _interopRequireDefault(_format);

Most of that file is gobbledygook to most humans, however computers understand it.


Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns and then open node_modules/date-fns/get_year/index.js you can see it contains:

var parse = require('../parse/index.js')

function getYear (dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return year
}

module.exports = getYear

Using the babel process above, your app_es6.js file could then contain:

import getYear from 'date-fns/get_year';

// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014

And babel would convert the imports to:

var _get_year = require("date-fns/get_year");

var _get_year2 = _interopRequireDefault(_get_year);

And handle all references to the function accordingly.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.

If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.

The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.

Reloading/refreshing Kendo Grid

You can use

$('#GridName').data('kendoGrid').dataSource.read(); <!--  first reload data source -->

$('#GridName').data('kendoGrid').refresh(); <!--  refresh current UI -->

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

(Laravel 5.2) I find the simplest way is just to add one code line to monitor the sql queries:

\DB::listen(function($sql) {var_dump($sql); });

Floating Point Exception C++ Why and what is it?

Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

Encrypt & Decrypt using PyCrypto AES 256

https://stackoverflow.com/a/21928790/11402877

compatible utf-8 encoding

def _pad(self, s):
    s = s.encode()
    res = s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs).encode()
    return res

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I normally use this statement:

ALTER TABLE `table_name`
  CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);

But, I think SET will work too, never have tried it. :)

Adding subscribers to a list using Mailchimp's API v3

Based on the List Members Instance docs, the easiest way is to use a PUT request which according to the docs either "adds a new list member or updates the member if the email already exists on the list".

Furthermore apikey is definitely not part of the json schema and there's no point in including it in your json request.

Also, as noted in @TooMuchPete's comment, you can use CURLOPT_USERPWD for basic http auth as illustrated in below.

I'm using the following function to add and update list members. You may need to include a slightly different set of merge_fields depending on your list parameters.

$data = [
    'email'     => '[email protected]',
    'status'    => 'subscribed',
    'firstname' => 'john',
    'lastname'  => 'doe'
];

syncMailchimp($data);

function syncMailchimp($data) {
    $apiKey = 'your api key';
    $listId = 'your list id';

    $memberId = md5(strtolower($data['email']));
    $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
    $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;

    $json = json_encode([
        'email_address' => $data['email'],
        'status'        => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
        'merge_fields'  => [
            'FNAME'     => $data['firstname'],
            'LNAME'     => $data['lastname']
        ]
    ]);

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                                                                                                                 

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode;
}

Force Java timezone as GMT/UTC

Use system property:

-Duser.timezone=UTC

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

In Visual Studio 2010 you will find the keyboard command to resolve namespaces in a command called View.ShowSmartTag. Mine was also mapped to Shift + Alt + F10 which is a lot of hassle - so I usually remap that promptly.

On Pete commenting on ReSharper - yes, for anyone with the budget, ReSharper makes life an absolute pleasure. The fact that it is intelligent enough to resolve dependencies outside the current references, and add them both as usings and references will not only save you countless hours, but also make you forget where all framework classes reside ;-) That is how easy it makes development life... Then we have not even started on ReSharper refactorings yet.

DevExpress' CodeRush offers no assistance on this regard; or nothing that is obvious to me - and DevExpress under non-expert mode is quite forthcoming in what it wants to do for you :-)

Last comment - this IDE feature of resolving dependencies is so mature and refined in the Java IDE world that the bulk of the Internet samples don't even show the imports (using) any more.

This said, Microsoft now finally has something to offer on this regard, but it is also clear to me that Microsoft development (for many of us) has now come full circle - the focus went from source, to visual designers right back to focus being on source again - meaning that the time you spend in a source code view / whether it is C#, VB or XAML is on the up and the amount of dragging and dropping onto 'forms' is on the down. With this basic assumption, it is simple to say that Microsoft should start concentrating on making the editor smarter, keyboard shortcuts easier, and code/error checking and evaluation better - the days of a dumb editor leaving you to google a class to find out in which library it resides are gone (or should be in any case) for most of us.

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

Correlation between two vectors?

Try xcorr, it's a built-in function in MATLAB for cross-correlation:

c = xcorr(A_1, A_2);

However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef command instead.

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

How do I turn a String into a InputStreamReader in java?

Same question as @Dan - why not StringReader ?

If it has to be InputStreamReader, then:

String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

How can I check if my python object is a number?

Test if your variable is an instance of numbers.Number:

>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]

This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC).

However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.

This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.

Socket send and receive byte array

Try this, it's working for me.

Sender:

byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

dOut.writeInt(message.length); // write length of the message
dOut.write(message);           // write the message


Receiver:

Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());

int length = dIn.readInt();                    // read length of incoming message
if(length>0) {
    byte[] message = new byte[length];
    dIn.readFully(message, 0, message.length); // read the message
}

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

How to find which version of TensorFlow is installed in my system?

For python 3.6.2:

import tensorflow as tf

print(tf.version.VERSION)

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./to_mysql.sh myfile.mdb > myfile.sql

(which btw contains more than 1 table)

Laravel blade check empty foreach

Check the documentation for the best result:

@forelse($status->replies as $reply)
    <p>{{ $reply->body }}</p>
@empty
    <p>No replies</p>
@endforelse

Add jars to a Spark Job - spark-submit

While we submit spark jobs using spark-submit utility, there is an option --jars . Using this option, we can pass jar file to spark applications.

What is console.log in jQuery?

jQuery and console.log are unrelated entities, although useful when used together.

If you use a browser's built-in dev tools, console.log will log information about the object being passed to the log function.

If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:

if (window.console) console.log('foo');

The shortcut form of this might be seen instead:

window.console&&console.log('foo');

There are other useful debugging functions as well, such as debug, dir and error. Firebug's wiki lists the available functions in the console api.

How To: Best way to draw table in console app (C#)

I have a project on GitHub that you can use

https://github.com/BrunoVT1992/ConsoleTable

You can use it like this:

var table = new Table();

table.SetHeaders("Name", "Date", "Number");

for (int i = 0; i <= 10; i++)
{
    if (i % 2 == 0)
        table.AddRow($"name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), i.ToString());
    else
        table.AddRow($"long name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), (i * 5000).ToString());
}

Console.WriteLine(table.ToString());

It will give this result:

enter image description here

HTML Table different number of columns in different rows

Colspan:

<table>
   <tr>
      <td> Row 1 Col 1</td>
      <td> Row 1 Col 2</td>
</tr>
<tr>
      <td colspan=2> Row 2 Long Col</td>
</tr>
</table>

Get img src with PHP

$imgTag = <<< LOB
<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />
<img border="0" src="/images/not_match_image.jpg" alt="Image" width="100" height="100" />
LOB;

preg_match('%<img.*?src=["\'](.*?)["\'].*?/>%i', $imgTag, $matches);
$imgSrc = $matches[1];

DEMO


NOTE: You should use an HTML Parser like DOMDocument and NOT a regex.

How to set radio button checked as default in radiogroup?

In the XML file set the android:checkedButton field in your RadioGroup, with the id of your default RadioButton:

<RadioGroup
    ....
    android:checkedButton="@+id/button_1">

    <RadioButton
        android:id="@+id/button_1"
        ...../>

    <RadioButton
        android:id="@+id/button_2"
        ...../>

    <RadioButton
        android:id="@+id/button_3"
        ...../>
</RadioGroup>

How many socket connections can a web server handle?

This question is a fairly difficult one. There is no real software limitation on the number of active connections a machine can have, though some OS's are more limited than others. The problem becomes one of resources. For example, let's say a single machine wants to support 64,000 simultaneous connections. If the server uses 1MB of RAM per connection, it would need 64GB of RAM. If each client needs to read a file, the disk or storage array access load becomes much larger than those devices can handle. If a server needs to fork one process per connection then the OS will spend the majority of its time context switching or starving processes for CPU time.

The C10K problem page has a very good discussion of this issue.

How to store arrays in MySQL?

The reason that there are no arrays in SQL, is because most people don't really need it. Relational databases (SQL is exactly that) work using relations, and most of the time, it is best if you assign one row of a table to each "bit of information". For example, where you may think "I'd like a list of stuff here", instead make a new table, linking the row in one table with the row in another table.[1] That way, you can represent M:N relationships. Another advantage is that those links will not clutter the row containing the linked item. And the database can index those rows. Arrays typically aren't indexed.

If you don't need relational databases, you can use e.g. a key-value store.

Read about database normalization, please. The golden rule is "[Every] non-key [attribute] must provide a fact about the key, the whole key, and nothing but the key.". An array does too much. It has multiple facts and it stores the order (which is not related to the relation itself). And the performance is poor (see above).

Imagine that you have a person table and you have a table with phone calls by people. Now you could make each person row have a list of his phone calls. But every person has many other relationships to many other things. Does that mean my person table should contain an array for every single thing he is connected to? No, that is not an attribute of the person itself.

[1]: It is okay if the linking table only has two columns (the primary keys from each table)! If the relationship itself has additional attributes though, they should be represented in this table as columns.

How to show PIL Image in ipython notebook

You can open an image using the Image class from the package PIL and display it with plt.imshow directly.

# First import libraries.
from PIL import Image
import matplotlib.pyplot as plt

# The folliwing line is useful in Jupyter notebook
%matplotlib inline

# Open your file image using the path
img = Image.open(<path_to_image>)

# Since plt knows how to handle instance of the Image class, just input your loaded image to imshow method
plt.imshow(img)

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

Simple answer

If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080

If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.

How do I start a process from C#?

Use the Process class. The MSDN documentation has an example how to use it.

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

makefile:4: *** missing separator. Stop

The key point was "HARD TAB" 1. Check whether you used TAB instead of whitespace 2. Check your .vimrc for "set tabstop=X"

Wireshark localhost traffic capture

For some reason, none of previous answers worked in my case, so I'll post something that did the trick. There is a little jewel called RawCap that can capture localhost traffic on Windows. Advantages:

  • only 17 kB!
  • no external libraries needed
  • extremely simple to use (just start it, choose the loopback interface and destination file and that's all)

After the traffic has been captured, you can open it and examine in Wireshark normally. The only disadvantage that I found is that you cannot set filters, i.e. you have to capture all localhost traffic which can be heavy. There is also one bug regarding Windows XP SP 3.

Few more advices:

Java: How To Call Non Static Method From Main Method?

You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.

How to install the Raspberry Pi cross compiler on my Linux host machine?

The initial question has been posted quite some time ago and in the meantime Debian has made huge headway in the area of multiarch support.

Multiarch is a great achievement for cross compilation!

In a nutshell the following steps are required to leverage multiarch for Raspbian Jessie cross compilation:

  • On your Ubuntu host install Debian Jessie amd64 within a chroot or a LXC container.
  • Enable the foreign architecture armhf.
  • Install the cross compiler from the emdebian tools repository.
  • Tweak the cross compiler (it would generate code for ARMv7-A by default) by writing a custom gcc specs file.
  • Install armhf libraries (libstdc++ etc.) from the Raspbian repository.
  • Build your source code.

Since this is a lot of work I have automated the above setup. You can read about it here:

Cross Compiling for Raspbian

jQuery ajax success callback function definition

You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )

Print all day-dates between two dates

Essentially the same as Gringo Suave's answer, but with a generator:

from datetime import datetime, timedelta


def datetime_range(start=None, end=None):
    span = end - start
    for i in xrange(span.days + 1):
        yield start + timedelta(days=i)

Then you can use it as follows:

In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out: 
[datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 1, 2, 0, 0),
 datetime.datetime(2014, 1, 3, 0, 0),
 datetime.datetime(2014, 1, 4, 0, 0),
 datetime.datetime(2014, 1, 5, 0, 0)]

Or like this:

In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
   ...:     print date
   ...:     
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00

What characters are valid for JavaScript variable names?

Javascript Variables

You can start a variable with any letter, $, or _ character. As long as it doesn't start with a number, you can include numbers as well.

Start: [a-z], $, _

Contain: [a-z], [0-9], $, _

jQuery

You can use _ for your library so that it will stand side-by-side with jQuery. However, there is a configuration you can set so that jQuery will not use $. It will instead use jQuery. To do this, simply set:

jQuery.noConflict();

This page explains how to do this.

Why doesn't java.io.File have a close method?

The javadoc of the File class describes the class as:

An abstract representation of file and directory pathnames.

File is only a representation of a pathname, with a few methods concerning the filesystem (like exists()) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.

(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile, causing much confusion with its inconsistent naming.)

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

According to Google Developers article, you can:

Run .php file in Windows Command Prompt (cmd)

you can for example: set your environment variable path with php.exe folder e.g c:\program files\php

create a script file in d:\ with filename as a.php

open cmd: go to d: drive using d: command

type following command

php -f a.php

you will see the output