Programs & Examples On #Conditional attribute

How do I restart a service on a remote machine in Windows?

One way would be to enable telnet server on the machin you want to control services on (add/remove windows components)

Open dos prompt
Type telnet yourmachineip/name
Log on
type net start &serviceName* e.g. w3svc

This will start IIS or you can use net stop to stop a service.

Depending on your setup you need to look at a way of securing the telnet connection as I think its unencrypted.

How to generate random positive and negative numbers in Java

Generate numbers between 0 and 65535 then just subtract 32768

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

Convert a Pandas DataFrame to a dictionary

Follow these steps:

Suppose your dataframe is as follows:

>>> df
   A  B  C ID
0  1  3  2  p
1  4  3  2  q
2  4  0  9  r

1. Use set_index to set ID columns as the dataframe index.

    df.set_index("ID", drop=True, inplace=True)

2. Use the orient=index parameter to have the index as dictionary keys.

    dictionary = df.to_dict(orient="index")

The results will be as follows:

    >>> dictionary
    {'q': {'A': 4, 'B': 3, 'D': 2}, 'p': {'A': 1, 'B': 3, 'D': 2}, 'r': {'A': 4, 'B': 0, 'D': 9}}

3. If you need to have each sample as a list run the following code. Determine the column order

column_order= ["A", "B", "C"] #  Determine your preferred order of columns
d = {} #  Initialize the new dictionary as an empty dictionary
for k in dictionary:
    d[k] = [dictionary[k][column_name] for column_name in column_order]

Get counts of all tables in a schema

If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:

select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;

Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;

Or this can be done using a CssClass (recommended):

.highlight
{
  color:red;
  font-weight:bold;
}

TextBox1.CssClass = "highlight";

Or the styles can be added inline:

TextBox1.Attributes["style"] = "color:red; font-weight:bold;";

The remote host closed the connection. The error code is 0x800704CD

I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:

myContext.Response.OutputStream.Write(buffer, 0, bytesRead);

I can’t think of any way to prevent it but maybe you can properly handle this. Ex:

        try
        {
            …
            myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
            …
        }catch (HttpException ex)
        {
            if (ex.Message.StartsWith("The remote host closed the connection."))
                ;//do nothing
            else
                //handle other errors
        }            
        catch (Exception e)
        {
            //handle other errors
        }
        finally
        {//close streams etc..
        }

using c# .net libraries to check for IMAP messages from gmail servers

As the author of the above project i can say that yes it does support SSL.

I am currently working on a new version of the library that will be completely asynchronous to increase the speed with which it can interact with IMAP servers.

That code, while not complete, can be downloaded, along with the original synchronous library (which also supports SSL), from the code plex site linked to above.

sass --watch with automatic minify?

If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers. enter image description here

  1. Convert style.scss to style.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.css
    

    and output paths to refresh

    $FileNameWithoutExtension$.css
    
  2. Convert style.scss to compressed style.min.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
    

    and output paths to refresh

    $FileNameWithoutExtension$.min.css
    

Changing the git user inside Visual Studio Code

I had the same problem as Daniel, setting the commit address and unsetting the credentials helper also worked for me.

git config --global user.email '<git-commit-address>'
git config --global --unset credential.helper

Can you use a trailing comma in a JSON object?

Rather than engage in a debating club, I would apply Defensive Programming. As a developer of an app that receives json data, I'd allow the trailing comma. When developing an app that writes json, I'd use one of the clever techniques of the other answers to only add commas between items. There are bigger problems to be solved...

Free c# QR-Code generator

You can look at Open Source QR Code Library or messagingtoolkit-qrcode. I have not used either of them so I can not speak of their ease to use.

How to check whether a variable is a class or not?

class Foo: is called old style class and class X(object): is called new style class.

Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"

How to access component methods from “outside” in ReactJS?

Since React 0.12 the API is slightly changed. The valid code to initialize myChild would be the following:

var Child = React.createClass({…});
var myChild = React.render(React.createElement(Child, {}), mountNode);
myChild.someMethod();

Using Sockets to send and receive data

I assume you are using TCP sockets for the client-server interaction? One way to send different types of data to the server and have it be able to differentiate between the two is to dedicate the first byte (or more if you have more than 256 types of messages) as some kind of identifier. If the first byte is one, then it is message A, if its 2, then its message B. One easy way to send this over the socket is to use DataOutputStream/DataInputStream:

Client:

Socket socket = ...; // Create and connect the socket
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());

// Send first message
dOut.writeByte(1);
dOut.writeUTF("This is the first type of message.");
dOut.flush(); // Send off the data

// Send the second message
dOut.writeByte(2);
dOut.writeUTF("This is the second type of message.");
dOut.flush(); // Send off the data

// Send the third message
dOut.writeByte(3);
dOut.writeUTF("This is the third type of message (Part 1).");
dOut.writeUTF("This is the third type of message (Part 2).");
dOut.flush(); // Send off the data

// Send the exit message
dOut.writeByte(-1);
dOut.flush();

dOut.close();

Server:

Socket socket = ... // Set up receive socket
DataInputStream dIn = new DataInputStream(socket.getInputStream());

boolean done = false;
while(!done) {
  byte messageType = dIn.readByte();

  switch(messageType)
  {
  case 1: // Type A
    System.out.println("Message A: " + dIn.readUTF());
    break;
  case 2: // Type B
    System.out.println("Message B: " + dIn.readUTF());
    break;
  case 3: // Type C
    System.out.println("Message C [1]: " + dIn.readUTF());
    System.out.println("Message C [2]: " + dIn.readUTF());
    break;
  default:
    done = true;
  }
}

dIn.close();

Obviously, you can send all kinds of data, not just bytes and strings (UTF).

Note that writeUTF writes a modified UTF-8 format, preceded by a length indicator of an unsigned two byte encoded integer giving you 2^16 - 1 = 65535 bytes to send. This makes it possible for readUTF to find the end of the encoded string. If you decide on your own record structure then you should make sure that the end and type of the record is either known or detectable.

How to avoid Sql Query Timeout

Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).

I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).

How to run .APK file on emulator

Start an Android Emulator (make sure that all supported APIs are included when you created the emulator, we needed to have the Google APIs for instance).

Then simply email yourself a link to the .apk file, and download it directly in the emulator, and click the downloaded file to install it.

mysql command for showing current configuration variables

As an alternative you can also query the information_schema database and retrieve the data from the global_variables (and global_status of course too). This approach provides the same information, but gives you the opportunity to do more with the results, as it is a plain old query.

For example you can convert units to become more readable. The following query provides the current global setting for the innodb_log_buffer_size in bytes and megabytes:

SELECT
  variable_name,
  variable_value AS innodb_log_buffer_size_bytes,
  ROUND(variable_value / (1024*1024)) AS innodb_log_buffer_size_mb
FROM information_schema.global_variables
WHERE variable_name LIKE  'innodb_log_buffer_size';

As a result you get:

+------------------------+------------------------------+---------------------------+
| variable_name          | innodb_log_buffer_size_bytes | innodb_log_buffer_size_mb |
+------------------------+------------------------------+---------------------------+
| INNODB_LOG_BUFFER_SIZE | 268435456                    |                       256 |
+------------------------+------------------------------+---------------------------+
1 row in set (0,00 sec)

In log4j, does checking isDebugEnabled before logging improve performance?

As others have mentioned using the guard statement is only really useful if creating the string is a time consuming call. Specific examples of this are when creating the string will trigger some lazy loading.

It is worth noting that this problem can be completed avoided by using Simple Logging Facade for Java or (SLF4J) - http://www.slf4j.org/manual.html . This allows method calls such as:

logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);

This will only convert the passed in parameters to strings if debug is enabled. SLF4J as its name suggests is only a facade and the logging calls can be passed to log4j.

You could also very easily "roll your own" version of this.

Hope this helps.

SQL Server: Importing database from .mdf?

To perform this operation see the next images:

enter image description here

and next step is add *.mdf file,

very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA

enter image description here

Now remove the log file

enter image description here

Android get image path from drawable as string

If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.

    InputStream stream = getAssets().open("image.png");
    Drawable d = Drawable.createFromStream(stream, null);

bootstrap 3 wrap text content within div for horizontal alignment

Your code is working fine using bootatrap v3.3.7, but you can use word-break: break-word if it's not working at your end.

which would then look like this -

snap

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"_x000D_
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <div class="row" style="box-shadow: 0 0 30px black;">_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2005 Volkswagen Jetta 2.5 Sedan (worcester http://www.massmotorcars.com)_x000D_
                $6900</h3>_x000D_
            <p>_x000D_
                <small>2005 volkswagen jetta 2.5 for sale has 110,000 miles powere doors,power windows,has ,car drives_x000D_
                    excellent ,comes with warranty if you&#39;re ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1355/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1355">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2006 Honda Civic EX Sedan (Worcester www.massmotorcars.com) $7950</h3>_x000D_
            <p>_x000D_
                <small>2006 honda civic ex has 110,176 miles, has power doors ,power windows,sun roof,alloy wheels,runs_x000D_
                    great, cd player, 4 cylinder engen, ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1356/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1356">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
_x000D_
        </div>_x000D_
        <!--/span-->_x000D_
        <div class="col-6 col-sm-6 col-lg-4">_x000D_
            <h3 style="word-break: break-word;">2004 Honda Civic LX Sedan (worcester www.massmotorcars.com) $5900</h3>_x000D_
            <p>_x000D_
                <small>2004 honda civic lx sedan has 134,000 miles, great looking car, interior and exterior looks_x000D_
                    nice,has_x000D_
                    cd player, power windows ...</small>_x000D_
            </p>_x000D_
            <p>_x000D_
                <a class="btn btn-default" href="/search/1357/detail/" role="button">View details &raquo;</a>_x000D_
                <button type="button" class="btn bookmark" id="1357">_x000D_
                    <span class="_x000D_
                      glyphicon glyphicon-star-empty "></span>_x000D_
                </button>_x000D_
            </p>_x000D_
        </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get the current loop index when using Iterator?

Though you already had the answer, thought to add some info.

As you mentioned Collections explicitly, you can't use listIterator to get the index for all types of collections.

List interfaces - ArrayList, LinkedList, Vector and Stack.

Has both iterator() and listIterator()

Set interfaces - HashSet, LinkedHashSet, TreeSet and EnumSet.

Has only iterator()

Map interfaces - HashMap, LinkedHashMap, TreeMap and IdentityHashMap

Has no iterators, but can be iterated using through the keySet() / values() or entrySet() as keySet() and entrySet() returns Set and values() returns Collection.

So its better to use iterators() with continuous increment of a value to get the current index for any collection type.

Can you write nested functions in JavaScript?

Functions are first class objects that can be:

  • Defined within your function
  • Created just like any other variable or object at any point in your function
  • Returned from your function (which may seem obvious after the two above, but still)

To build on the example given by Kenny:

   function a(x) {
      var w = function b(y) {
        return x + y;
      }
      return w;
   };

   var returnedFunction = a(3);
   alert(returnedFunction(2));

Would alert you with 5.

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

Is there an opposite of include? for Ruby Arrays?

module Enumerable
  def does_not_include?(item)
    !include?(item)
  end
end

Ok, but seriously, the unless works fine.

Unresolved Import Issues with PyDev and Eclipse

Following, in my opinion will solve the problem

  1. Adding the init.py to your "~/Desktop/Python_Tutorials/diveintopython/py" folder
  2. Go to Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any updates made to any System PythonPath)
  3. Add in the Interpreter with the same details as before (this will refresh your Python Interpreter setting with updates made to your PythonPath)
  4. Finally since your "~/Desktop/Python_Tutorials/diveintopython/py" folder not a standard PythonPath, you will need to add it in. There are two ways to do it

a. As per what David German suggested. However this only applicable for the particular projects you are in b. Add in "~/Desktop/Python_Tutorials/diveintopython/py" into a new PythonPath under Window --> Preferences --> PyDev --> Interpreters --> Python Interpreter --> Libraries subtab --> NewFolder

Hope it helps.

How to change facebook login button with my custom image

It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.

From facebook:

size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/

Set the login iframe opacity to 0 and show a background image in the parent div

.fb_iframe_widget iframe {
    opacity: 0;
}

.fb_iframe_widget {
  background-image: url(another-button.png);
  background-repeat: no-repeat; 
}

If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.

C# error: Use of unassigned local variable

A couple of different ways to solve the problem:

Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.

static void Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return;
    } else {
       return;   
}

Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method

static int Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return 1;
    } else {
       return 2;
    }
}

Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:

static void Main(string[] args) {
  Byte maxSize;
  Queue queue = null;

  if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
     Environment.Exit(0);
  }
  queue = new Queue(){MaxSize = maxSize};

  for(Byte j = 0; j < queue.MaxSize; j++)
    queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
    Console.WriteLine(queue.Remove());
}

Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)

static void Main(String[] args) {
  if(args.Length != 0) {
     if(Byte.TryParse(args[0], out maxSize)) {
        queue = new Queue(){MaxSize = maxSize};
     } else {
        Environment.Exit(0);
        return;
     }
  } else { 
     Environment.Exit(0);
     return;
  }

  for(Byte j = 0; j < queue.MaxSize; j++)
     queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
     Console.WriteLine(queue.Remove());
}

Rolling back bad changes with svn in Eclipse

If you want to do 1 file at a time you can go to the History view for the file assuming you have an Eclipse SVN plugin installed. "Team->Show History"

In the History view, find the last good version of that file, right click and choose "Get Contents". This will replace your current version with that version's contents. Then you can commit the changes when you've fixed it all up.

Change/Get check state of CheckBox

I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.

function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.

    if(document.getElementById(from).checked==true) 
    //checks status of "from" element. change to whatever validation you prefer.
        {
            document.getElementById(to).checked=true;
             //if validation returns true, checks target checkbox
        }
    else
        {   
            document.getElementById(to).checked=false; 
             //if validation returns true, unchecks target checkbox
        }
}

HTML being something like

<input type="radio" name="bob" onclick="copycheck('from','to');" />

where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to". As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.

Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.

Hope this helps.

Python: how to print range a-z?

for one in range(97,110):
    print chr(one)

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

Setting the filter to an OpenFileDialog to allow the typical image formats?

For images, you could get the available codecs from GDI (System.Drawing) and build your list from that with a little work. This would be the most flexible way to go.

ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

Understanding colors on Android (six characters)

Going off the answer from @BlondeFurious, here is some Java code to get each hexadecimal value from 100% to 0% alpha:

for (double i = 1; i >= 0; i -= 0.01) {
    i = Math.round(i * 100) / 100.0d;
    int alpha = (int) Math.round(i * 255);
    String hex = Integer.toHexString(alpha).toUpperCase();
    if (hex.length() == 1)
        hex = "0" + hex;
    int percent = (int) (i * 100);
    System.out.println(String.format("%d%% — %s", percent, hex));
}

Output:

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

A JavaScript version is below:

_x000D_
_x000D_
var text = document.getElementById('text');_x000D_
for (var i = 1; i >= 0; i -= 0.01) {_x000D_
    i = Math.round(i * 100) / 100;_x000D_
    var alpha = Math.round(i * 255);_x000D_
    var hex = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();_x000D_
    var perc = Math.round(i * 100);_x000D_
    text.innerHTML += perc + "% — " + hex + " (" + alpha + ")</br>";_x000D_
}
_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_


You can also just Google "number to hex" where 'number' is any value between 0 and 255.

Getting Index of an item in an arraylist;

Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach : The List needs to be sorted by the element to be tested.

Start search at the middle element size()/2 eg 5000 if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500

keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)

You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.

Replacing column values in a pandas DataFrame

This is very compact:

w['female'][w['female'] == 'female']=1
w['female'][w['female'] == 'male']=0

Another good one:

w['female'] = w['female'].replace(regex='female', value=1)
w['female'] = w['female'].replace(regex='male', value=0)

Open local folder from link

Local Explorer - File Manager on web browser extention can solve for chrome

but still some encoding problems

Makefile: How to correctly include header file and its directory?

Try INC_DIR=../ ../StdCUtil.

Then, set CCFLAGS=-c -Wall $(addprefix -I,$(INC_DIR))

EDIT: Also, modify your #include to be #include <StdCUtil/split.h> so that the compiler knows to use -I rather than local path of the .cpp using the #include.

How do I run a program with a different working directory from current, from Linux shell?

If you always want it to go to /C, use an absolute path when you write the file.

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

Push item to associative array in PHP

There is a better way to do this:

If the array $arr_options contains the existing array.

$arr_new_input['name'] = [
    'type' => 'text', 
    'label' => 'First name', 
    'show' => true, 
    'required' => true
];

$arr_options += $arr_new_input;

Warning: $arr_options must exist. if $arr_options already has a ['name'] it wil be overwritten.

Hope this helps.

Stretch Image to Fit 100% of Div Height and Width

Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>

Make the current Git branch a master branch

The solutions given here (renaming the branch in 'master') don't insist on the consequences for the remote (GitHub) repo:

  • if you hadn't push anything since making that branch, you can rename it and push it without any problem.
  • if you had push master on GitHub, you will need to 'git push -f' the new branch: you can no longer push in a fast forward mode.
    -f
    --force

Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. This flag disables the check. This can cause the remote repository to lose commits; use it with care.

If others have already pulled your repo, they won't be able to pull that new master history without replacing their own master with that new GitHub master branch (or dealing with lots of merges).
There are alternatives to a git push --force for public repos.
Jefromi's answer (merging the right changes back to the original master) is one of them.

Laravel password validation rule

A Custom Laravel Validation Rule will allow developers to provide a custom message with each use case for a better UX experience.

php artisan make:rule IsValidPassword

namespace App\Rules;

use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;

class isValidPassword implements Rule
{
    /**
     * Determine if the Length Validation Rule passes.
     *
     * @var boolean
     */
    public $lengthPasses = true;

    /**
     * Determine if the Uppercase Validation Rule passes.
     *
     * @var boolean
     */
    public $uppercasePasses = true;

    /**
     * Determine if the Numeric Validation Rule passes.
     *
     * @var boolean
     */
    public $numericPasses = true;

    /**
     * Determine if the Special Character Validation Rule passes.
     *
     * @var boolean
     */
    public $specialCharacterPasses = true;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->lengthPasses = (Str::length($value) >= 10);
        $this->uppercasePasses = (Str::lower($value) !== $value);
        $this->numericPasses = ((bool) preg_match('/[0-9]/', $value));
        $this->specialCharacterPasses = ((bool) preg_match('/[^A-Za-z0-9]/', $value));

        return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        switch (true) {
            case ! $this->uppercasePasses
                && $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character.';

            case ! $this->numericPasses
                && $this->uppercasePasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one number.';

            case ! $this->specialCharacterPasses
                && $this->uppercasePasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one number.';

            case ! $this->uppercasePasses
                && ! $this->specialCharacterPasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && ! $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character, one number, and one special character.';

            default:
                return 'The :attribute must be at least 10 characters.';
        }
    }
}

Then on your request validation:

$request->validate([
    'email'    => 'required|string|email:filter',
    'password' => [
        'required',
        'confirmed',
        'string',
        new isValidPassword(),
    ],
]);

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Catch KeyError in Python

I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)

Difference between Encapsulation and Abstraction

This image sums pretty well the difference between both:

enter image description here

Source here

Prevent form redirect OR refresh on submit?

It looks like you're missing a return false.

Connect Bluestacks to Android Studio

world !

No need to do execute batch command. With the current version, just run BLUESTACKS before ANDROID STUDIO

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source

Lost connection to MySQL server during query?

I was running into the same problem. Because of some other issues I had tried to add a cnx.close() line to my other functions. Instead, I removed all these extraneous closes and setup my class like this:

class DBase:

config = {
      'user': 'root',
      'password': '',
      'host': '127.0.0.1',
      'database': 'bio',
      'raise_on_warnings': True,
      'use_pure': False,
      }

def __init__(self):
    import mysql.connector
    self.cnx = mysql.connector.connect(**self.config)
    self.cur = self.cnx.cursor(buffered=True)
    print(self.cnx)
def __enter__(self):
    return DBase()

def __exit__(self, exc_type, exc_val, exc_tb):
    self.cnx.commit()
    if self.cnx:
        self.cnx.close()

Any function that is called within this class is connects, commits, and closes.

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

Implement a simple factory pattern with Spring 3 annotations

I suppose you to use org.springframework.beans.factory.config.ServiceLocatorFactoryBean. It will much simplify your code. Except MyServiceAdapter u can only create interface MyServiceAdapter with method MyService getMyService and with alies to register your classes

Code

bean id="printStrategyFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
        <property name="YourInterface" value="factory.MyServiceAdapter" />
    </bean>

    <alias name="myServiceOne" alias="one" />
    <alias name="myServiceTwo" alias="two" />

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Representing Directory & File Structure in Markdown Syntax

You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre> tag to preserve the plain text formatting.

select rows in sql with latest date for each ID repeated multiple times

You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:

SELECT * 
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)

Here we give the yourtable table an alias of t1 and then use that alias in the subquery grabbing the max(date) from the same table yourtable for that id.

C# static class constructor

You can use static constructor to initialization static variable. Static constructor will be entry point for your class

public class MyClass
{

    static MyClass()
    {

        //write your initialization code here
    }

}

Integrating Dropzone.js into existing HTML form with other fields

Here's another way to do it: add a div in your form with a classname dropzone, and implement dropzone programmatically.

HTML :

<div id="dZUpload" class="dropzone">
      <div class="dz-default dz-message"></div>
</div>

JQuery:

$(document).ready(function () {
    Dropzone.autoDiscover = false;
    $("#dZUpload").dropzone({
        url: "hn_SimpeFileUploader.ashx",
        addRemoveLinks: true,
        success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
        }
    });
});

Note : Disabling autoDiscover, otherwise Dropzone will try to attach twice

Blog Article : Dropzone js + Asp.net: Easy way to upload Bulk images

Convert Json Array to normal Java list

I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
    for (Long s : list) {
        System.out.println(s);
    }
}

Works also with array of strings

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

Is the sizeof(some pointer) always equal to four?

if you are compiling for a 64-bit machine, then it may be 8.

Get nodes where child node contains an attribute

//book[title[@lang='it']]

is actually equivalent to

 //book[title/@lang = 'it']

I tried it using vtd-xml, both expressions spit out the same result... what xpath processing engine did you use? I guess it has conformance issue Below is the code

import com.ximpleware.*;
public class test1 {
  public static void main(String[] s) throws Exception{
      VTDGen vg = new VTDGen();
      if (vg.parseFile("c:/books.xml", true)){
          VTDNav vn = vg.getNav();
          AutoPilot ap = new AutoPilot(vn);
          ap.selectXPath("//book[title[@lang='it']]");
                  //ap.selectXPath("//book[title/@lang='it']");

          int i;
          while((i=ap.evalXPath())!=-1){
              System.out.println("index ==>"+i);
          }
          /*if (vn.endsWith(i, "< test")){
             System.out.println(" good ");  
          }else
              System.out.println(" bad ");*/

      }
  }
}

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

What is the meaning of "Failed building wheel for X" in pip install?

On Ubuntu 18.04, I ran into this issue because the apt package for wheel does not include the wheel command. I think pip tries to import the wheel python package, and if that succeeds assumes that the wheel command is also available. Ubuntu breaks that assumption.

The apt python3 code package is named python3-wheel. This is installed automatically because python3-pip recommends it.

The apt python3 wheel command package is named python-wheel-common. Installing this too fixes the "failed building wheel" errors for me.

Gradle project refresh failed after Android Studio update

Most people do not read the comments so to summarize (Thanks to @Industrial-antidepressant and @wrecker):

As suggested in a bug ticket you should try the following:

  1. Close Android Studio
  2. go to android-studio/plugins/gradle/lib
  3. Delete (or better move them somewhere to have a backup) all gradle-*-1.8 files
  4. Start Android Studio again and rebuild/refresh.

It should work. Make sure to star the above bug ticket to get informed.

Little tip: Try the new compile setting Settings -> Compiler -> Gradle and activate the third in-process build for a speed up. Depending on your project setting you might want to select the first one as well. With that my project build time reduced to 2-4 seconds (before 20+ seconds).

Detecting negative numbers

I assume that the main idea is to find if number is negative and display it in correct format.

For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.

$profitLoss = 25000 - 55000;

$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY); 
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)

Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had Microsoft Access Database Engine 2010 Redistributable already installed on my machine but was still receiving the Microsoft ACE OLEDB Provider error.

Then I recalled that I had upgraded to Office 2016 recently, so, may be I should try reinstalling Microsoft Access Database Engine 2010 Redistributable. And that fixed the problem on my machine.

So, if you have upgraded to different version of MS Office or even repaired/reinstalled your MS Office then try reinstalling Microsoft Access Database Engine 2010 Redistributable before wasting time with finding other fixes. Good luck!

python: unhashable type error

As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper() (which implies drug is a string).

But that's not your error, as your function medications_minimum3() doesn't even use the second argument (something you should fix).

TypeError: unhashable type: 'list' usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1 -- are you sure that row[11] is of the right type? Sounds to me it might be a list.

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

What are the use cases for selecting CHAR over VARCHAR in SQL?

If you're working with me and you're working with Oracle, I would probably make you use varchar in almost every circumstance. The assumption that char uses less processing power than varchar may be true...for now...but database engines get better over time and this sort of general rule has the making of a future "myth".

Another thing: I have never seen a performance problem because someone decided to go with varchar. You will make much better use of your time writing good code (fewer calls to the database) and efficient SQL (how do indexes work, how does the optimizer make decisions, why is exists faster than in usually...).

Final thought: I have seen all sorts of problems with use of CHAR, people looking for '' when they should be looking for ' ', or people looking for 'FOO' when they should be looking for 'FOO (bunch of spaces here)', or people not trimming the trailing blanks, or bugs with Powerbuilder adding up to 2000 blanks to the value it returns from an Oracle procedure.

Changing variable names with Python for loops

It looks like you want to use a list instead:

group=[]
for i in range(3):
     group[i]=self.getGroup(selected, header+i)

JPA Native Query select and cast object

When your native query is based on joins, in that case you can get the result as list of objects and process it.

one simple example.

@Autowired
EntityManager em;

    String nativeQuery = "select name,age from users where id=?";   
    Query query = em.createNativeQuery(nativeQuery);
    query.setParameter(1,id);

    List<Object[]> list = query.getResultList();

    for(Object[] q1 : list){

        String name = q1[0].toString();
        //..
        //do something more on 
     }

Table fixed header and scrollable body

For whatever it's worth now: I did post a solution to a sister-thread Table scroll with HTML and CSS which

  • takes two tables (one for only header, one for all - layouted by the browser)
  • after layouting, adjust the upper (header-only) table to the widths of the lower one
  • hide (visibility, not display) the header of the lower table and make the lower table scrollable w/in a div

The solution is agnostic to any styles / frameworks used - so maybe it's useful here as well...

A long description is in Table scroll with HTML and CSS / the code is also in this pen: https://codepen.io/sebredhh/pen/QmJvKy

How does Java resolve a relative path in new File()?

The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.

Relative paths are ones that start without a drive specifier. So in linux they don't start with a /, in windows they don't start with a C:\, etc. These always start from your working directory.

Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.

JavaScript split String with white space

Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)

So:

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

Output:

["my", " ", "car", " ", "is", " ", "red"]

This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.

How to get previous page url using jquery

var from = document.referrer;
console.log(from);

document.referrer won't be always available.

How to add dividers and spaces between items in RecyclerView?

If anyone is looking to only add, say, 10dp spacing between items, you can do so by setting a drawable to DividerItemDecoration:

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(
    recyclerView.getContext(),
    layoutManager.getOrientation()
);

dividerItemDecoration.setDrawable(
    ContextCompat.getDrawable(getContext(), R.drawable.divider_10dp)
); 

Where divider_10dpis a drawable resource containing:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size android:height="10dp"/>
    <solid android:color="@android:color/transparent"/>
</shape>

Multiline text in JLabel

You can do it by putting HTML in the code, so:

JFrame frame = new JFrame();
frame.setLayout(new GridLayout());
JLabel label = new JLabel("<html>First line<br>Second line</html>");
frame.add(label);
frame.pack();
frame.setVisible(true);

git discard all changes and pull from upstream

while on branch master: git reset --hard origin/master

then do some clean up with git gc (more about this in the man pages)

Update: You will also probably need to do a git fetch origin (or git fetch origin master if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)

db.addUser({user:'admin',pwd:'<password>',roles:["root"]})

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

Install python 2.6 in CentOS

# yum groupinstall "Development tools"
# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel

Download and install Python 3.3.0

# wget http://python.org/ftp/python/3.3.0/Python-3.3.0.tar.bz2
# tar xf Python-3.3.0.tar.bz2
# cd Python-3.3.0
# ./configure --prefix=/usr/local
# make && make altinstall

Download and install Distribute for Python 3.3

# wget http://pypi.python.org/packages/source/d/distribute/distribute-0.6.35.tar.gz
# tar xf distribute-0.6.35.tar.gz
# cd distribute-0.6.35
# python3.3 setup.py install

Install and use virtualenv for Python 3.3

# easy_install-3.3 virtualenv
# virtualenv-3.3 --distribute otherproject

New python executable in otherproject/bin/python3.3
Also creating executable in otherproject/bin/python
Installing distribute...................done.
Installing pip................done.

# source otherproject/bin/activate
# python --version
Python 3.3.0

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

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

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

How to find the path of Flutter SDK

To find the Flutter SDK path [ used Windows10 ]

  1. In your Android Studio home page on the bottom right click on Configure
  2. Then Click on SDK Manager
  3. Then on System Settings
  4. Then on AndroidSDK

You will see the path at the top

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Grant SELECT on multiple tables oracle

my suggestion is...create role in oracle using

create role <role_name>;

then assign privileges to that role using

grant select on <table_name> to <role_name>;

then assign that group of privileges via that role to any user by using

grant  <role_name> to <user_name>...;

List all indexes on ElasticSearch server?

The simplest way to get a list of only indexes is to use the answer above, with the 'h=index' parameter:

curl -XGET "localhost:9200/_cat/indices?h=index"

How do I create an .exe for a Java program?

I used exe4j to package all java jars into one final .exe file, which user can use it as normal windows application.

Send email with PHP from html form on submit with the same script

EDIT (#1)

If I understand correctly, you wish to have everything in one page and execute it from the same page.

You can use the following code to send mail from a single page, for example index.php or contact.php

The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.

It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.

Copy the entire code below into one file.

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html> 

Original answer


I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.

Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.

The PHP handler will also send a copy of the message to the person who filled in the form.

You can use two forward slashes // in front of a line of code if you're not going to use it.

For example: // $subject2 = "Copy of your form submission"; will not execute.

HTML FORM:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP handler (mail_handler.php)

(Uses info from HTML form and sends the Email)

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $subject = "Form submission";
    $subject2 = "Copy of your form submission";
    $message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    // You cannot use header and echo together. It's one or the other.
    }
?>

To send as HTML:

If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.

Read the manual on mail() to learn how to send emails as HTML:


Footnotes:

  • In regards to HTML5

You have to specify the URL of the service that will handle the submitted data, using the action attribute.

As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.

Therefore, action="" will not work in HTML5.

The proper syntax would be:

  • action="handler.xxx" or
  • action="http://www.example.com/handler.xxx".

Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.


Consult the following Q&A on Stack if sending mail fails:

How to hide the title bar for an Activity in XML with existing custom theme

This is how the complete code looks like. Note the import of android.view.Window.

package com.hoshan.tarik.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
    }
}

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

After following the instructions in the other answers, I needed to strip the version from the map file for this to work for me.

Example: Rename

jquery-1.9.1.min.map

to

jquery.min.map

How do I add a newline to command output in PowerShell?

The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.

Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append

Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

From ND to 1D arrays

For list of array with different size use following:

import numpy as np

# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]

# stack them
b = np.hstack(a)

print(b)

Output:

[1 2 3 4 5 6 7 8]

Restart container within pod

Both pod and container are ephemeral, try to use the following command to stop the specific container and the k8s cluster will restart a new container.

kubectl exec -it [POD_NAME] -c [CONTAINER_NAME] -- /bin/sh -c "kill 1"

This will send a SIGTERM signal to process 1, which is the main process running in the container. All other processes will be children of process 1, and will be terminated after process 1 exits. See the kill manpage for other signals you can send.

What should be the values of GOPATH and GOROOT?

As mentioned above:

The GOPATH environment variable specifies the location of your workspace.

For Windows, this worked for me (in Ms-dos window):

set GOPATH=D:\my_folder_for_go_code\

This creates a GOPATH variable that Ms-dos recognizes when used as follows:

cd %GOPATH%

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

What are the aspect ratios for all Android phone and tablet devices?

The Sony Tablet P is old, but it can switch between 32:15 and 32:30 for each app in landscape mode, and vice-versa in portrait mode, so that's a minimum range to aim for

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

My.ini from the file #password and #bind-address="127.0.0.1" are commented change the password to root and uncomment bind-address="127.0.0.1" and from the file cds.php change the

mysql_connect("localhost", "root", ""); to
mysql_connect("localhost", "root", "root");

Stop the Mysql services and try login again it got logged in.

Get content of a DIV using JavaScript

function add_more() {

var text_count = document.getElementById('text_count').value;
var div_cmp = document.getElementById('div_cmp');
var values = div_cmp.innnerHTML;
var count = parseInt(text_count);
divContent = '';

for (i = 1; i <= count; i++) {

    var cmp_text = document.getElementById('cmp_name_' + i).value;
    var cmp_textarea = document.getElementById('cmp_remark_' + i).value;
    divContent += '<div id="div_cmp_' + i + '">' +
        '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + i + '" value="' + cmp_text + '" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + i + '">' + cmp_textarea + '</textarea>' +
        '</div>';
}

var newCount = count + 1;

if (document.getElementById('div_cmp_' + newCount) == null) {
    var newText = '<div id="div_cmp_' + newCount + '">' +
        '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '"  ></textarea>' +
        '</div>';
    //content = div_cmp.innerHTML;
    div_cmp.innerHTML = divContent + newText;
} else {
    document.getElementById('div_cmp_' + newCount).innerHTML = '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '"  ></textarea>';
}

document.getElementById('text_count').value = newCount;

}

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

How do I run a program with commandline arguments using GDB within a Bash script?

gdb has --init-command <somefile> where somefile has a list of gdb commands to run, I use this to have //GDB comments in my code, then `

echo "file ./a.out" > run
grep -nrIH "//GDB"|
    sed "s/\(^[^:]\+:[^:]\+\):.*$/\1/g" |
    awk '{print "b" " " $1}'|
    grep -v $(echo $0|sed "s/.*\///g") >> run
gdb --init-command ./run -ex=r

as a script, which puts the command to load the debug symbols, and then generates a list of break commands to put a break point for each //GDB comment, and starts it running

add maven repository to build.gradle

You have to add repositories to your build file. For maven repositories you have to prefix repository name with maven{}

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

String strip() for JavaScript?

If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.

check if variable empty

here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also

<?php
    $val = 0;
    //evaluates to true because $var is empty
    if (empty($val)) {
        echo '$val is either 0, empty, or not set at all';
    }
    //evaluates to true because $VAR IS SET
    if (isset($val)) {
        echo '$val is set even though it is empty';
    }
    ?>

Find location of a removable SD card

You can try to use the support library function called of ContextCompat.getExternalFilesDirs() :

      final File[] appsDir=ContextCompat.getExternalFilesDirs(getActivity(),null);
      final ArrayList<File> extRootPaths=new ArrayList<>();
      for(final File file : appsDir)
        extRootPaths.add(file.getParentFile().getParentFile().getParentFile().getParentFile());

The first one is the primary external storage, and the rest are supposed to be real SD-cards paths.

The reason for the multiple ".getParentFile()" is to go up another folder, since the original path is

.../Android/data/YOUR_APP_PACKAGE_NAME/files/

EDIT: here's a more comprehensive way I've created, to get the sd-cards paths:

  /**
   * returns a list of all available sd cards paths, or null if not found.
   *
   * @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
   */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static List<String> getSdCardPaths(final Context context, final boolean includePrimaryExternalStorage)
    {
    final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
    if(externalCacheDirs==null||externalCacheDirs.length==0)
      return null;
    if(externalCacheDirs.length==1)
      {
      if(externalCacheDirs[0]==null)
        return null;
      final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
      if(!Environment.MEDIA_MOUNTED.equals(storageState))
        return null;
      if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
        return null;
      }
    final List<String> result=new ArrayList<>();
    if(includePrimaryExternalStorage||externalCacheDirs.length==1)
      result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
    for(int i=1;i<externalCacheDirs.length;++i)
      {
      final File file=externalCacheDirs[i];
      if(file==null)
        continue;
      final String storageState=EnvironmentCompat.getStorageState(file);
      if(Environment.MEDIA_MOUNTED.equals(storageState))
        result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
      }
    if(result.isEmpty())
      return null;
    return result;
    }

  /** Given any file/folder inside an sd card, this will return the path of the sd card */
  private static String getRootOfInnerSdCardFolder(File file)
    {
    if(file==null)
      return null;
    final long totalSpace=file.getTotalSpace();
    while(true)
      {
      final File parentFile=file.getParentFile();
      if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
        return file.getAbsolutePath();
      file=parentFile;
      }
    }

Get encoding of a file in Windows

EncodingChecker

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

How do I view an older version of an SVN file?

I believe the best way to view revisions is to use a program/app that makes it easy for you. I like to use trac : http://trac.edgewall.org/wiki/TracSubversion

It provides a great svn browser and makes it really easy to go back through your revisions.

It may be a little overkill to set this up for one specific revision you want to check, but it could be useful if you're going to do this a lot in the future.

format a number with commas and decimals in C# (asp.net MVC3)

Try with

ToString("#,##0.###")

Produces:

1234.55678 => 1,234.556

1234 => 1,234

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

in my case (RHEL7 and MariaDB) this works.

sudo systemctl restart mariadb

How to install Android SDK Build Tools on the command line?

As stated in other responses, the build tools requires the --all flag to be installed. You also better use a -t filter flag to avoid installing ALL the packages but there is no way to filter all the build tools.

There are already features requests for these two points in AOSP bug tracker. Feel free to vote for them, this might make them happen some day:

Why is the Java main method static?

The main method of the program has the reserved word static which means it is allowed to be used in the static context. A context relates to the use of computer memory during the running of the program. When the virtual machine loads a program, it creates the static context for it, allocating computer memory to store the program and its data, etc.. A dynamic context is certain kind of allocation of memory which is made later, during the running of the program. The program would not be able to start if the main method was not allowed to run in the static context.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

I think using transaction.commitAllowingStateLoss(); is not best solution. This exception will be thrown when activity's configuration changed and fragment onSavedInstanceState() is called and thereafter your async callback method tries to commit fragment.

Simple solution could be check whether activity is changing configuration or not

e.g. check isChangingConfigurations()

i.e.

if(!isChangingConfigurations()) { //commit transaction. }

Checkout this link as well

Take the content of a list and append it to another list

Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

Count unique values using pandas groupby

I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:

df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)

How to fire AJAX request Periodically?

I tried the below code,

    function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously. Its better to call setTimeout(executeQuery, 5000); outside executeQuery() in a separate function as below,

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  updateCall();
}

function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}

$(document).ready(function() {
  executeQuery();
});

This worked exactly as intended.

How to add a reference programmatically

Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!

Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278

Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
    Dim rw As Long, ref
    With ThisWorkbook.Sheets(1)
        .Cells.Clear
        rw = 1
        .Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
        For Each ref In ThisWorkbook.VBProject.References
            rw = rw + 1
            .Range("A" & rw & ":D" & rw) = Array(ref.Description, _
                   "v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
        Next ref
        .Range("A:D").Columns.AutoFit
    End With
End Sub

Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.

Sub ListReferencePaths() 
 'Macro purpose:  To determine full path and Globally Unique Identifier (GUID)
 'to each referenced library.  Select the reference in the Tools\References
 'window, then run this code to get the information on the reference's library

On Error Resume Next 
Dim i As Long 

Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID" 

For i = 1 To ThisWorkbook.VBProject.References.Count 
  With ThisWorkbook.VBProject.References(i) 
    Debug.Print .Name & " | " & .FullPath  & " | " & .GUID 
  End With 
Next i 
On Error GoTo 0 
End Sub 

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

How to download file in swift?

Here's an example that shows how to do sync & async.

import Foundation

class HttpDownloader {

    class func loadFileSync(url: NSURL, completion:(path:String, error:NSError!) -> Void) {
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
        let destinationUrl = documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!)
        if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
            println("file already exists [\(destinationUrl.path!)]")
            completion(path: destinationUrl.path!, error:nil)
        } else if let dataFromURL = NSData(contentsOfURL: url){
            if dataFromURL.writeToURL(destinationUrl, atomically: true) {
                println("file saved [\(destinationUrl.path!)]")
                completion(path: destinationUrl.path!, error:nil)
            } else {
                println("error saving file")
                let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                completion(path: destinationUrl.path!, error:error)
            }
        } else {
            let error = NSError(domain:"Error downloading file", code:1002, userInfo:nil)
            completion(path: destinationUrl.path!, error:error)
        }
    }

    class func loadFileAsync(url: NSURL, completion:(path:String, error:NSError!) -> Void) {
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL
        let destinationUrl = documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!)
        if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
            println("file already exists [\(destinationUrl.path!)]")
            completion(path: destinationUrl.path!, error:nil)
        } else {
            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "GET"
            let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
                if (error == nil) {
                    if let response = response as? NSHTTPURLResponse {
                        println("response=\(response)")
                        if response.statusCode == 200 {
                            if data.writeToURL(destinationUrl, atomically: true) {
                                println("file saved [\(destinationUrl.path!)]")
                                completion(path: destinationUrl.path!, error:error)
                            } else {
                                println("error saving file")
                                let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                                completion(path: destinationUrl.path!, error:error)
                            }
                        }
                    }
                }
                else {
                    println("Failure: \(error.localizedDescription)");
                    completion(path: destinationUrl.path!, error:error)
                }
            })
            task.resume()
        }
    }
}

Here's how to use it in your code:

let url = NSURL(string: "http://www.mywebsite.com/myfile.pdf") 
HttpDownloader.loadFileAsync(url, completion:{(path:String, error:NSError!) in
                println("pdf downloaded to: \(path)")
            })

Boxplot show the value of mean

You can use the output value from stat_summary()

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) 
+ geom_boxplot() 
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, 
               vjust=-0.7, aes( label=round(..y.., digits=1)))

calculating number of days between 2 columns of dates in data frame

Without your seeing your data (you can use the output of dput(head(survey)) to show us) this is a shot in the dark:

survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
                  as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
       date   tx_start date_diff
1 2012/07/26 2012/01/01  207 days
2 2012/07/25 2012/01/01  206 days

How to get root view controller?

Swift way to do it, you can call this from anywhere, it returns optional so watch out about that:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups
var topMostVC: UIViewController? {
    var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    while let pVC = presentedVC?.presentedViewController {
        presentedVC = pVC
    }

    if presentedVC == nil {
        print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
    }
    return presentedVC
}

Its included as a standard function in:

https://github.com/goktugyil/EZSwiftExtensions

How to clamp an integer to some range?

Whatever happened to my beloved readable Python language? :-)

Seriously, just make it a function:

def addInRange(val, add, minval, maxval):
    newval = val + add
    if newval < minval: return minval
    if newval > maxval: return maxval
    return newval

then just call it with something like:

val = addInRange(val, 7, 0, 42)

Or a simpler, more flexible, solution where you do the calculation yourself:

def restrict(val, minval, maxval):
    if val < minval: return minval
    if val > maxval: return maxval
    return val

x = restrict(x+10, 0, 42)

If you wanted to, you could even make the min/max a list so it looks more "mathematically pure":

x = restrict(val+7, [0, 42])

How to drop all tables in a SQL Server database?

For me, the easiest way:

--First delete all constraints

DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';

SELECT @sql = @sql + N'
ALTER TABLE ' + QUOTENAME(s.name) + N'.'
+ QUOTENAME(t.name) + N' DROP CONSTRAINT '
+ QUOTENAME(c.name) + ';'
FROM sys.objects AS c
INNER JOIN sys.tables AS t
ON c.parent_object_id = t.[object_id]
INNER JOIN sys.schemas AS s 
ON t.[schema_id] = s.[schema_id]
WHERE c.[type] IN ('D','C','F','PK','UQ')
ORDER BY c.[type];

EXEC sys.sp_executesql @sql;

-- Then drop all tables

exec sp_MSforeachtable 'DROP TABLE ?'

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

How to find NSDocumentDirectory in Swift?

Usually I prefer to use this extension:

Swift 3.x and Swift 4.0:

extension FileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
}

Swift 2.x:

extension NSFileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
}

How to install a previous exact version of a NPM package?

you can update your npm package by using this command:

npm install <package_name>@<version_number>

example: npm install [email protected]

Convert string to number and add one

Parse the Id as it would be string and then add.

e.g.

$('.load_more').live("click",function() { //When user clicks
    var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
    alert(newcurrentpageTemp);
    dosomething();
});

Best way to test for a variable's existence in PHP; isset() is clearly broken

Object properties can be checked for existence by property_exists

Example from a unit test:

function testPropertiesExist()
{
    $sl =& $this->system_log;
    $props = array('log_id',
                   'type',
                   'message',
                   'username',
                   'ip_address',
                   'date_added');

    foreach($props as $prop) {
        $this->assertTrue(property_exists($sl, $prop),
                           "Property <{$prop}> exists");
    }
}

Count the number occurrences of a character in a string

str.count(a) is the best solution to count a single character in a string. But if you need to count more characters you would have to read the whole string as many times as characters you want to count.

A better approach for this job would be:

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict(int)

for char in text:
    chars[char] += 1

So you'll have a dict that returns the number of occurrences of every letter in the string and 0 if it isn't present.

>>>chars['a']
4
>>>chars['x']
0

For a case insensitive counter you could override the mutator and accessor methods by subclassing defaultdict (base class' ones are read-only):

class CICounter(defaultdict):
    def __getitem__(self, k):
        return super().__getitem__(k.lower())

    def __setitem__(self, k, v):
        super().__setitem__(k.lower(), v)


chars = CICounter(int)

for char in text:
    chars[char] += 1

>>>chars['a']
4
>>>chars['M']
2
>>>chars['x']
0

How to avoid "Permission denied" when using pip with virtualenv

In my case, I was using mkvirtualenv, but didn't tell it I was going to be using python3. I got this error:

mkvirtualenv hug
pip3 install hug -U

....
error: could not create '/usr/lib/python3.4/site-packages': Permission denied

It worked after specifying python3:

mkvirtualenv --python=/usr/bin/python3 hug
pip3 install hug -U

C#: Dynamic runtime cast

The opensource framework Dynamitey has a static method that does late binding using DLR including cast conversion among others.

dynamic Cast(object obj, Type castTo){
    return Dynamic.InvokeConvert(obj, castTo, explict:true);
}

The advantage of this over a Cast<T> called using reflection, is that this will also work for any IDynamicMetaObjectProvider that has dynamic conversion operators, ie. TryConvert on DynamicObject.

converting a base 64 string to an image and saving it

In my case it works only with two line of code. Test the below C# code:

String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.

add a string prefix to each value in a string column using Pandas

Another solution with .loc:

df = pd.DataFrame({'col': ['a', 0]})
df.loc[df.index, 'col'] = 'string' + df['col'].astype(str)

This is not as quick as solutions above (>1ms per loop slower) but may be useful in case you need conditional change, like:

mask = (df['col'] == 0)
df.loc[mask, 'col'] = 'string' + df['col'].astype(str)

Python: read all text file lines in loop

There are situations where you can't use the (quite convincing) with... for... structure. In that case, do the following:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break

This will work because the the readline() leaves a trailing newline character, where as EOF is just an empty string.

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

Kubernetes Pod fails with CrashLoopBackOff

The issue caused by the docker container which exits as soon as the "start" process finishes. i added a command that runs forever and it worked. This issue mentioned here

Is it possible to create static classes in PHP (like in C#)?

In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.

So in my humble opinion this is a more complete example based on Greg's one:

<?php

class Hello
{
    /**
     * Construct won't be called inside this class and is uncallable from
     * the outside. This prevents instantiating this class.
     * This is by purpose, because we want a static class.
     */
    private function __construct() {}
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>

css width: calc(100% -100px); alternative using jquery

100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

Different color for each bar in a bar chart; ChartJS

If you take a look at the library "ChartNew" which builds upon Chart.js you can do this by passing the values in as an array like so:

var data = {
    labels: ["Batman", "Iron Man", "Captain America", "Robin"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: ["rgba(220,220,220,0.5)", "navy", "red", "orange"],
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [2000, 1500, 1750, 50]
        }
    ]
};

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

Saving changes after table edit in SQL Server Management Studio

Many changes you can make very easily and visually in the table editor in SQL Server Management Studio actually require SSMS to drop the table in the background and re-create it from scratch. Even simple things like reordering the columns cannot be expressed in standard SQL DDL statement - all SSMS can do is drop and recreate the table.

This operation can be a) very time consuming on a large table, or b) might even fail for various reasons (like FK constraints and stuff). Therefore, SSMS in SQL Server 2008 introduced that new option the other answers have already identified.

It might seem counter-intuitive at first to prevent such changes - and it's certainly a nuisance on a dev server. But on a production server, this option and its default value of preventing such changes becomes a potential life-saver!

Read/Write String from/to a File in Android

the first thing we need is the permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

so in an asyncTask Kotlin class, we treat the creation of the file

    import android.os.AsyncTask
    import android.os.Environment
    import android.util.Log
    import java.io.*
    class WriteFile: AsyncTask<String, Int, String>() {
        private val mFolder = "/MainFolder"
        lateinit var folder: File
        internal var writeThis = "string to cacheApp.txt"
        internal var cacheApptxt = "cacheApp.txt"
        override fun doInBackground(vararg writethis: String): String? {
            val received = writethis[0]
            if(received.isNotEmpty()){
                writeThis = received
            }
            folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
            if(!folder.exists()){
                folder.mkdir()
                val readME = File(folder, cacheApptxt)
                val file = File(readME.path)
                val out: BufferedWriter
                try {
                    out = BufferedWriter(FileWriter(file, true), 1024)
                    out.write(writeThis)
                    out.newLine()
                    out.close()
                    Log.d("Output_Success", folder.path)
                } catch (e: Exception) {
                    Log.d("Output_Exception", "$e")
                }
            }
            return folder.path

    }

        override fun onPostExecute(result: String) {
            super.onPostExecute(result)

            if(result.isNotEmpty()){
                //implement an interface or do something
                Log.d("onPostExecuteSuccess", result)
            }else{
                Log.d("onPostExecuteFailure", result)
            }
        }

    }

Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat

    class ReadandWrite {
        private val mREAD = 9
        private val mWRITE = 10
        private var readAndWrite: Boolean = false
        fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
            if (Build.VERSION.SDK_INT < 23) {
                readAndWrite = true
            } else {
                val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
                val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                if (mRead != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
                } else {
                    readAndWrite = true
                }

                if (mWrite != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
                } else {
                    readAndWrite = true
                }
            }
            return readAndWrite
        }
    }

then in an activity, execute the call.

  var pathToFileCreated = ""
    val anRW = ReadandWrite().readAndwriteStorage(this,this)
    if(anRW){
        pathToFileCreated =  WriteFile().execute("onTaskComplete").get()
        Log.d("pathToFileCreated",pathToFileCreated)
    }

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

Selenium and xPath - locating a link by containing text

I think the problem is here:

[contains(text()='Some text')]

To break this down,

  1. The [] are a conditional that operates on each individual node in that node set -- each span node in your case. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  2. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  3. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order.

You should try to change this to

[text()[contains(.,'Some text')]]

  1. The outer [] are a conditional that operates on each individual node in that node set text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.

  2. The inner [] are a conditional that operates on each node in that node set.

  3. contains is a function that operates on a string. Here it is passed an individual text node (.).

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

Uninstall all installed gems, in OSX?

If you are using Rubygems version 2.1.0 or later, you can try: gem uninstall --all.

Is Visual Studio Community a 30 day trial?

I had this problem. Signing in or pressing the "Check for an updated license" link did not work for me. My solution was to restart Visual Studio, try again (sign in and check for license). Restart Visual Studio, try again. I had to do this several times and then it worked! (I also tried pressing the "File" menu that is available for a short period of time before the annoying request window appears again.) Maybe you just don't get connected to the server or the server itself doesn't update its database fast enough.

How to select records without duplicate on just one field in SQL?

Try this one

SELECT country_id, country_title 
FROM (SELECT country_id, country_title,
CASE
WHEN country_title=LAG(country_title, 1, 0) OVER(ORDER BY country_title) THEN 1
ELSE 0
END AS "Duplicates"
FROM tbl_countries)
WHERE "Duplicates"=0;

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

How to get the size of a JavaScript object?

Here's a slightly more compact solution to the problem:

const typeSizes = {
  "undefined": () => 0,
  "boolean": () => 4,
  "number": () => 8,
  "string": item => 2 * item.length,
  "object": item => !item ? 0 : Object
    .keys(item)
    .reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};

const sizeOf = value => typeSizes[typeof value](value);

Is there a way to use two CSS3 box shadows on one element?

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

Tools for making latex tables in R

I have a few tricks and work arounds to interesting 'features' of xtable and Latex that I'll share here.

Trick #1: Removing Duplicates in Columns and Trick #2: Using Booktabs

First, load packages and define my clean function

<<label=first, include=FALSE, echo=FALSE>>= 
    library(xtable)
    library(plyr)

    cleanf <- function(x){     
        oldx <- c(FALSE, x[-1]==x[-length(x)])  
        # is the value equal to the previous?    
        res <- x
        res[oldx] <- NA
        return(res)} 

Now generate some fake data

data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
            colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
            size=rnorm(100,mean=500, sd=150),
            age=rlnorm(100, meanlog=3, sdlog=0.5))

    #generate a table
    datatable<-ddply(data, .(animal, colour), function(df) {
                return(data.frame(size=mean(df$size), age=mean(df$age)))
            })

Now we can generate a table, and use the clean function to remove duplicate entries in the label columns.

cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@ 

this is a normal xtable

<<label=normal, results=tex, echo=FALSE>>=
print(
    xtable(
        datatable
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

this is a normal xtable where a custom function has turned duplicates to NA

<<label=cleandata, results=tex, echo=FALSE>>=
print(
    xtable(
        cleandata
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

This table uses the booktab package (and needs a \usepackage{booktabs} in the headers)

\begin{table}[!h] 
        \centering
        \caption{table using booktabs.}
        \label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>= 
            mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
            foo<-0:(length(mat$animal))
            bar<-foo[!is.na(mat$animal)]
            print(mat, 
                  sanitize.text.function = function(x){x},
                  floating=FALSE,
                  include.rownames=FALSE,
                  hline.after=NULL, 
                  add.to.row=list(pos=list(-1,bar,nrow(mat)), 
                  command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
  #could extend this with \cmidrule to have a partial line over
  #a sub category column and \addlinespace to add space before a total row
@ 

How do I change the background color with JavaScript?

But you would want to configure the body color before the <body> element exists. That way it has the right color from the get go.

<script>
    var myColor = "#AAAAAA";
    document.write('\
        <style>\
            body{\
                background-color: '+myColor+';\
            }\
        </style>\
    ');
</script>

This you can put in the <head> of the document or in your js file.

Here is a nice color to play with.

var myColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

Best way to do nested case statement logic in SQL Server

Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression

select  datediff(dd,Invdate,'2009/01/31')+1 as DaysOld, 
    case when datediff(dd,Invdate,'2009/01/31')+1 >150 then 6 else
        case when datediff(dd,Invdate,'2009/01/31')+1 >120 then 5 else 
            case when datediff(dd,Invdate,'2009/01/31')+1 >90 then 4 else 
                case when datediff(dd,Invdate,'2009/01/31')+1 >60 then 3 else 
                    case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 2 else 
                        case when datediff(dd,Invdate,'2009/01/31')+1 >30 then 1 end 
                    end
                end
            end
        end
    end as Bucket
from rm20090131atb

Just make sure you have an end statement for every case statement

When does Git refresh the list of remote branches?

If you are using Eclipse,

  1. Open "Git Repositories"
  2. Find your Repository.
  3. Open up "Branches" then "Remote Tracking".

Git

They should all be in there. Right click and "checkout."

Measuring text height to be drawn on Canvas ( Android )

There are different ways to measure the height depending on what you need.

getTextBounds

If you are doing something like precisely centering a small amount of fixed text, you probably want getTextBounds. You can get the bounding rectangle like this

Rect bounds = new Rect();
mTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
int height = bounds.height();

As you can see for the following images, different strings will give different heights (shown in red).

enter image description here

These differing heights could be a disadvantage in some situations when you just need a constant height no matter what the text is. See the next section.

Paint.FontMetrics

You can calculate the hight of the font from the font metrics. The height is always the same because it is obtained from the font, not any particular text string.

Paint.FontMetrics fm = mTextPaint.getFontMetrics();
float height = fm.descent - fm.ascent;

The baseline is the line that the text sits on. The descent is generally the furthest a character will go below the line and the ascent is generally the furthest a character will go above the line. To get the height you have to subtract ascent because it is a negative value. (The baseline is y=0 and y descreases up the screen.)

Look at the following image. The heights for both of the strings are 234.375.

enter image description here

If you want the line height rather than just the text height, you could do the following:

float height = fm.bottom - fm.top + fm.leading; // 265.4297

These are the bottom and top of the line. The leading (interline spacing) is usually zero, but you should add it anyway.

The images above come from this project. You can play around with it to see how Font Metrics work.

StaticLayout

For measuring the height of multi-line text you should use a StaticLayout. I talked about it in some detail in this answer, but the basic way to get this height is like this:

String text = "This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.";

TextPaint myTextPaint = new TextPaint();
myTextPaint.setAntiAlias(true);
myTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
myTextPaint.setColor(0xFF000000);

int width = 200;
Layout.Alignment alignment = Layout.Alignment.ALIGN_NORMAL;
float spacingMultiplier = 1;
float spacingAddition = 0;
boolean includePadding = false;

StaticLayout myStaticLayout = new StaticLayout(text, myTextPaint, width, alignment, spacingMultiplier, spacingAddition, includePadding);

float height = myStaticLayout.getHeight(); 

Why is "throws Exception" necessary when calling a function?

Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.

For example:

class throwseg1 {
    void show() throws Exception {
        throw new Exception();
    }
}

Should be written as:

class throwseg1 {
    void show() {
        try {
            throw new Exception();
        } catch(Exception e) {
            // code to handle the exception
        }
    }
}

This way you can get rid of the "throws Exception" declaration in the method declaration.

Maximum and Minimum values for ints

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don't need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.

What is key=lambda

Lambda can be any function. So if you had a function

def compare_person(a):
         return a.age

You could sort a list of Person (each of which having an age attribute) like this:

sorted(personArray, key=compare_person)

This way, the list would be sorted by age in ascending order.

The parameter is called lambda because python has a nifty lambda keywords for defining such functions on the fly. Instead of defining a function compare_person and passing that to sorted, you can also write:

sorted(personArray, key=lambda a: a.age)

which does the same thing.

How to add some non-standard font to a website?

I've found that the easiest way to have non-standard fonts on a website is to use sIFR

It does involve the use of a Flash object that contains the font, but it degrades nicely to standard text / font if Flash is not installed.

The style is set in your CSS, and JavaScript sets up the Flash replacement for your text.

Edit: (I still recommend using images for non-standard fonts as sIFR adds time to a project and can require maintenance).

Cannot open include file: 'unistd.h': No such file or directory

If you're using ZLib in your project, then you need to find :

#if 1

in zconf.h and replace(uncomment) it with :

#if HAVE_UNISTD_H /* ...the rest of the line

If it isn't ZLib I guess you should find some alternative way to do this. GL.

How to fill the whole canvas with specific color?

You know what, there is an entire library for canvas graphics. It is called p5.js You can add it with just a single line in your head element and an additional sketch.js file.

Do this to your html and body tags first:

<html style="margin:0 ; padding:0">
<body style="margin:0 ; padding:0">

Add this to your head:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script type="text/javascript" src="sketch.js"></script>

The sketch.js file

function setup() {
    createCanvas(windowWidth, windowHeight);
    background(r, g, b);
}

Determining Referer in PHP

What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.

So if you are generating a FB callback then it would look something like this:

$token = uniqid(mt_rand(), TRUE);
$_SESSION['token'] = $token;
$url = "http://example.com/index.php?token={$token}";

Then the index.php will look like this:

if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token'])
{
    show_404();
} 

//Continue with the rest of code

I do know of secure sites that do the equivalent of this for all their secure pages.

Posting JSON Data to ASP.NET MVC

The simplest way of doing this

I urge you to read this blog post that directly addresses your problem.

Using custom model binders isn't really wise as Phil Haack pointed out (his blog post is linked in the upper blog post as well).

Basically you have three options:

  1. Write a JsonValueProviderFactory and use a client side library like json2.js to communicate wit JSON directly.

  2. Write a JQueryValueProviderFactory that understands the jQuery JSON object transformation that happens in $.ajax or

  3. Use the very simple and quick jQuery plugin outlined in the blog post, that prepares any JSON object (even arrays that will be bound to IList<T> and dates that will correctly parse on the server side as DateTime instances) that will be understood by Asp.net MVC default model binder.

Of all three, the last one is the simplest and doesn't interfere with Asp.net MVC inner workings thus lowering possible bug surface. Using this technique outlined in the blog post will correctly data bind your strong type action parameters and validate them as well. So it is basically a win win situation.

Array of an unknown length in C#

Arrays must be assigned a length. To allow for any number of elements, use the List class.

For example:

List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3

Java output formatting for Strings

     @Override
     public String toString() {
          return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
     }

Get yesterday's date using Date

You can do following:

private Date getMeYesterday(){
     return new Date(System.currentTimeMillis()-24*60*60*1000);
}

Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:

private Date getPreviousWeekDate(){
     return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}

Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:

private Date getMeTomorrow(){
     return new Date(System.currentTimeMillis()+24*60*60*1000);
}

Adding <script> to WordPress in <head> element

In your theme's functions.php:

function my_custom_js() {
    echo '<script type="text/javascript" src="myscript.js"></script>';
}
// Add hook for admin <head></head>
add_action( 'admin_head', 'my_custom_js' );
// Add hook for front-end <head></head>
add_action( 'wp_head', 'my_custom_js' );

Switch to another Git tag

As of Git v2.23.0 (August 2019), git switch is preferred over git checkout when you’re simply switching branches/tags. I’m guessing they did this since git checkout had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch, and git restore, to separate those concerns. I would predict at some point in the future, git checkout will be deprecated.

To switch to a normal branch, use git switch <branch-name>. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>, where <commitish> is the tag name or commit number.

The --detach option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>.

How to change the default browser to debug with in Visual Studio 2008?

To permanently make Visual Studio open a project in IE without changing the default browser you can do the following:

Project Properties -> Web -> Start Action

Start external program: C:\Program Files\Internet Explorer\iexplore.exe Command line arguments: Enter the url of the path to your start page ie http:\localhost\myproject\default.aspx

This won't allow you to debug client side script in Visual Studio though.

How do I serialize a C# anonymous type to a JSON string?

You can try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContract's, Any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.

Basic Example

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 

Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.

Android: How to turn screen on and off programmatically?

I have tried all above solution but none worked for me. so I googled and found below solutions. I tried and it worked.

https://www.tutorialspoint.com/how-to-turn-android-device-screen-on-and-off-programmatically

if there is any suggestion then please give

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.addEventListener( 'click', function(){
  // delete the column here
} );

Laravel 5 route not defined, while it is?

I'm using Laravel 5.7 and tried all of the above answers but nothing seemed to be hitting the spot.

For me, it was a rather simple fix by removing the cache files created by Laravel.
It seemed that my changes were not being reflected, and therefore my application wasn't seeing the routes.

A bit overkill, but I decided to reset all my cache at the same time using the following commands:

php artisan route:clear
php artisan view:clear
php artisan cache:clear

The main one here is the first command which will delete the bootstrap/cache/routes.php file.
The second command will remove the cached files for the views that are stored in the storage/framework/cache folder.
Finally, the last command will clear the application cache.

error: Unable to find vcvarsall.bat

calling import setuptools will monkey patch distutils to force compatibility with Visual Studio. Calling vcvars32.bat manually will setup the virtual environment and prevent other common errors the compiler will throw. For VS 2017 the file is located at

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"

Here is the setup script I use to quickly compile .pyx files to .pyd: (Note: it uses the 3rd party module send2trash

# cython_setup.py
import sys, os, time, platform, subprocess
from setuptools import setup, find_packages
from Cython.Build import cythonize
from traceback import format_exc

# USAGE:
#
#   from cython_setup import run
#   run(pyx_path)

# vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"

# NOTE: to use visual studio 2017 you must have setuptools version 34+
vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars32.bat"


def _build_ext():
    try:
        pyx_path = sys.argv.pop(-1)
        pyx_path = os.path.abspath(pyx_path)
        if not os.path.exists(pyx_path):
            raise FileNotFoundError(f"{pyx_path} does not exist")
        project_name = sys.argv.pop(-1)
        os.chdir(os.path.abspath(os.path.dirname(pyx_path)))

        print("cwd: %s" % os.getcwd())
        print(os.path.abspath("build"))
        setup(
            name=project_name,
            # cmdclass = {'build_ext': build_ext},
            packages=find_packages(),
            # ext_modules=cythonize(extensions)
            ext_modules=cythonize(pyx_path,
                                  compiler_directives={'language_level': 3, 'infer_types': True, 'binding': False},
                                  annotate=True),
            # include_dirs = [numpy.get_include()]
            build_dir=os.path.abspath("build")
        )
    except:
        input(format_exc())


def retry(func):
    def wrapper(*args, **kw):
        tries = 0
        while True:
            try:
                return func(*args, **kw)
            except Exception:
                tries += 1
                if tries > 4:
                    raise
                time.sleep(0.4)

    return wrapper


@retry
def cleanup(pyx_path):
    from send2trash import send2trash
    c_file = os.path.splitext(pyx_path)[0] + ".c"
    if os.path.exists(c_file):
        os.remove(c_file)

    if os.path.exists("build"):
        send2trash("build")


def move_pyd_files(pyx_path):
    pyx_dir = os.path.dirname(pyx_path)
    build_dir = os.path.join(pyx_dir, "build")
    if not os.path.exists(build_dir):
        raise RuntimeError(f"build_dir {build_dir} did not exist....")
    found_pyd = False
    for top, dirs, nondirs in os.walk(build_dir):
        for name in nondirs:
            if name.lower().endswith(".pyd") or name.lower().endswith(".so"):
                found_pyd = True
                old_path = os.path.join(top, name)
                new_path = os.path.join(pyx_dir, name)
                if os.path.exists(new_path):
                    print(f"removing {new_path}")
                    os.remove(new_path)
                print(f"file created at {new_path}")
                os.rename(old_path, new_path)
    if not found_pyd:
        raise RuntimeError("Never found .pyd file to move")

def run(pyx_path):
    """
    :param pyx_path:
    :type pyx_path:
    :return: this function creates the batch file, which in turn calls this module, which calls cythonize, once done
    the batch script deletes itself... I'm sure theres a less convoluted way of doing this, but it works
    :rtype:
    """
    try:
        project_name = os.path.splitext(os.path.basename(pyx_path))[0]
        run_script(project_name, os.path.abspath(pyx_path))
    except:
        input(format_exc())


def run_script(project_name, pyx_path):
    dirname = os.path.dirname(pyx_path)
    # ------------------------------
    os.chdir(dirname)
    if os.path.exists(vcvars):
        #  raise RuntimeError(
        # f"Could not find vcvars32.bat at {vcvars}\nis Visual Studio Installed?\nIs setuptools version > 34?")
        subprocess.check_call(f'call "{vcvars}"', shell=True)

    cmd = "python" if platform.system() == "Windows" else "python3"
    subprocess.check_call(f'{cmd} "{__file__}" build_ext "{project_name}" "{pyx_path}"', shell=True)
    move_pyd_files(pyx_path)
    cleanup(pyx_path)


if len(sys.argv) > 2:
    _build_ext()

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

web.xml is missing and <failOnMissingWebXml> is set to true

Select your project and select the "Deployment Descriptor" option and then choose "Generate Deployment Descriptor stub"

Powershell script to check if service is started, if not then start it

[Array] $servers = "Server1","server2";
$service='YOUR SERVICE'

foreach($server in $servers)

{
    $srvc = Get-WmiObject -query "SELECT * FROM win32_service  WHERE   name LIKE '$service' " -computername $server  ;
    $res=Write-Output $srvc | Format-Table -AutoSize $server, $fmtMode, $fmtState, $fmtStatus ;  
   $srvc.startservice() 
   $res
}

Failed to allocate memory: 8

Referring to Android: failed to allocate memory and its first comment under accepted answer, changing "1024" to "1024MB" helped me. Pathetic, but works.

How can I change NULL to 0 when getting a single value from a SQL function?

Most database servers have a COALESCE function, which will return the first argument that is non-null, so the following should do what you want:

SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

Since there seems to be a lot of discussion about

COALESCE/ISNULL will still return NULL if no rows match, try this query you can copy-and-paste into SQL Server directly as-is:

SELECT coalesce(SUM(column_id),0) AS TotalPrice 
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)

Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0.

How to test if a string is basically an integer in quotes using Ruby

Expanding on @rado's answer above one could also use a ternary statement to force the return of true or false booleans without the use of double bangs. Granted, the double logical negation version is more terse, but probably harder to read for newcomers (like me).

class String
  def is_i?
     self =~ /\A[-+]?[0-9]+\z/ ? true : false
  end
end

Getting URL hash location, and using it in jQuery

I'm using this to address the security implications noted in @CMS's answer.

// example 1: www.example.com/index.html#foo

// load correct subpage from URL hash if it exists
$(window).on('load', function () {
    var hash = window.location.hash;
    if (hash) {
        hash = hash.replace('#',''); // strip the # at the beginning of the string
        hash = hash.replace(/([^a-z0-9]+)/gi, '-'); // strip all non-alphanumeric characters
        hash = '#' + hash; // hash now equals #foo with example 1

        // do stuff with hash
        $( 'ul' + hash + ':first' ).show();
        // etc...
    }
});