Programs & Examples On #Sigkill

On POSIX-compliant platforms, SIGKILL is the signal sent to a process to cause it to terminate immediately. The symbolic constant for SIGKILL is defined in the header file signal.h. Symbolic signal names are used because signal numbers can vary across platforms, however on the vast majority of systems, SIGKILL is signal #9.

How to gracefully handle the SIGKILL signal in Java

There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.

By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.

To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.

What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.

I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.

How do I use a regex in a shell script?

To complement the existing helpful answers:

Using Bash's own regex-matching operator, =~, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:

set -- '12-34-5678' # set $1 to sample value

kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match

Note, however, that the caveat re using flavor-specific regex constructs such as \d equally applies: While =~ supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.

To remain portable (in the context of Bash), stick to the POSIX ERE specification.

Note that =~ even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]} array variable.

Further notes:

  • $kREGEX_DATE is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).

  • While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \.

    • E.g., on Linux, where \< is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes does.
  • I've changed variable name REGEX_DATE to kREGEX_DATE (k signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.

How can I read user input from the console?

I think there are some compiler errors.

  • Writeline should be WriteLine (capital 'L')
  • missing semicolon at the end of a line

        double a, b;
        Console.WriteLine("istenen sayiyi sonuna .00 koyarak yaz");
        a = double.Parse(Console.ReadLine());
        b = a * Math.PI; // Missing colon!
        Console.WriteLine("Sonuç " + b);
    

How to check if field is null or empty in MySQL?

Either use

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 
from tablename

or

SELECT case when field1 IS NULL or field1 = ''
            then 'empty'
            else field1
       end as field1 
from tablename

If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.

How to find substring inside a string (or how to grep a variable)?

expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:

if expr match "$LIST" "$SOURCE"; then

But I'm not really clear what SOURCE is supposed to represent.

It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?

How to set DialogFragment's width and height?

Set the Parent layout of Custom dialogue layout to RelativeLayout, get common width and height automatically .

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

Get controller and action name from within controller?

Might be useful. I needed the action in the constructor of the controller, and it appears at this point of the MVC lifecycle, this hasn't initialized, and ControllerContext = null. Instead of delving into the MVC lifecycle and finding the appropriate function name to override, I just found the action in the RequestContext.RouteData.

But in order to do so, as with any HttpContext related uses in the constructor, you have to specify the full namespace, because this.HttpContext also hasn't been initialized. Luckily, it appears System.Web.HttpContext.Current is static.

// controller constructor
public MyController() {
    // grab action from RequestContext
    string action = System.Web.HttpContext.Current.Request.RequestContext.RouteData.GetRequiredString("action");

    // grab session (another example of using System.Web.HttpContext static reference)
    string sessionTest = System.Web.HttpContext.Current.Session["test"] as string
}

NOTE: likely not the most supported way to access all properties in HttpContext, but for RequestContext and Session it appears to work fine in my application.

How to deal with a slow SecureRandom generator?

I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a seed, then dies. The method which you call for randoms will join to that thread if it is alive so the first call only blocks if it occurs very early in program execution.

IntelliJ how to zoom in / out

Update: This answer is old. Intellij has since added actions to adjust font size. Check out Wilker's answer for assigning the new actions to keymaps.

Try Ctrl+Mouse Wheel which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

Searching for UUIDs in text with regex

In python re, you can span from numberic to upper case alpha. So..

import re
test = "01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK"
re.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars
## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']
re.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars
## ['01234ABCDEF', '01234', 'ABCDEF']
re.compile(r'[0-F]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-f]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']

That makes the simplest Python UUID regex:

re_uuid = re.compile("[0-F]{8}-([0-F]{4}-){3}[0-F]{12}", re.I)

I'll leave it as an exercise to the reader to use timeit to compare the performance of these.

Enjoy. Keep it Pythonic™!

NOTE: Those spans will also match :;<=>?@' so, if you suspect that could give you false positives, don't take the shortcut. (Thank you Oliver Aubert for pointing that out in the comments.)

How to run specific test cases in GoogleTest

Finally I got some answer, ::test::GTEST_FLAG(list_tests) = true; //From your program, not w.r.t console.

If you would like to use --gtest_filter =*; /* =*, =xyz*... etc*/ // You need to use them in Console.

So, my requirement is to use them from the program not from the console.

Updated:-

Finally I got the answer for updating the same in from the program.

 ::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
      InitGoogleTest(&argc, argv);
RUN_ALL_TEST();

So, Thanks for all the answers.

You people are great.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

I faced the problem with my Jenkins. When I have renewed the certificate I started facing this error.

stderr fatal: unable to access server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt

So I have added my new certificate in the following file:

/etc/ssl/certs/ca-certificates.crt

The content of that file looks like this:

-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----

Just append your certificate in the bottom:

-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----

Python pip install module is not found. How to link python to pip location?

Make sure to check the python version you are working on if it is 2 then only pip install works If it is 3. something then make sure to use pip3 install

How can I use jQuery to make an input readonly?

Perhaps it's meaningful to also add that

$('#fieldName').prop('readonly',false);

can be used as a toggle option..

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

  1. restart the genymotion
  2. run react-native run-android
  3. the problem was solved

Handling warning for possible multiple enumeration of IEnumerable

If your data is always going to be repeatable, perhaps don't worry about it. However, you can unroll it too - this is especially useful if the incoming data could be large (for example, reading from disk/network):

if(objects == null) throw new ArgumentException();
using(var iter = objects.GetEnumerator()) {
    if(!iter.MoveNext()) throw new ArgumentException();

    var firstObject = iter.Current;
    var list = DoSomeThing(firstObject);  

    while(iter.MoveNext()) {
        list.Add(DoSomeThingElse(iter.Current));
    }
    return list;
}

Note I changed the semantic of DoSomethingElse a bit, but this is mainly to show unrolled usage. You could re-wrap the iterator, for example. You could make it an iterator block too, which could be nice; then there is no list - and you would yield return the items as you get them, rather than add to a list to be returned.

What is the best way to delete a component with CLI

I am not sure if it is the best way, but it worked for me.

  • First, I deleted the component folder.
  • Then, I cleared app.module.ts, app.component.ts & app.component.html of the imports and declarations related to the component I wanted to delete.
  • Similarly, I cleared main.ts.

I just saved and refreshed the app and it worked.

How can I make a countdown with NSTimer?

XCode 10 with Swift 4.2

import UIKit

class ViewController: UIViewController {

   var timer = Timer()
   var totalSecond = 10

   override func viewDidLoad() {
       super.viewDidLoad()
       startTimer()
   }


   func startTimer() {
       timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
   }

   @objc func updateTime() {

        print(timeFormatted(totalSecond))

        if totalSecond != 0 {
           totalSecond -= 1
        } else {
           endTimer()
        }
    }

    func endTimer() {
        timer.invalidate()
    }

    func timeFormatted(_ totalSeconds: Int) -> String {
        let seconds: Int = totalSeconds % 60
        return String(format: "0:%02d", seconds)
    }

}

Number of regex matches

#An example for counting matched groups
import re

pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"

res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4  
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String

Inserting one list into another list in java?

An object is only once in memory. Your first addition to list just adds the object references.

anotherList.addAll will also just add the references. So still only 100 objects in memory.

If you change list by adding/removing elements, anotherList won't be changed. But if you change any object in list, then it's content will be also changed, when accessing it from anotherList, because the same reference is being pointed to from both lists.

Printing list elements on separated lines in Python

sys.path returns the list of paths

ref

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

import sys
dirs=sys.path
for path in dirs:
   print(path)

or you can print only first path by

print(dir[0])

Sending private messages to user

If you want to send the message to a predetermined person, such as yourself, you can set it so that the channel it would be messaging to would be their (your) own userID. So for instance, if you're using the discord bot tutorials from Digital Trends, where it says "to: ", you would continue with their (or your) userID. For instance, with how that specific code is set up, you could do "to: userID", and it would message that person. Or, if you want the bot to message you any time someone uses a specific command, you could do "to: '12345678890'", the numbers being a filler for the actual userID. Hope this helps!

jQuery DataTable overflow and text-wrapping issues

I faced the same problem of text wrapping, solved it by changing the css of table class in DT_bootstrap.css. I introduced last two css lines table-layout and word-break.

   table.table {
    clear: both;
    margin-bottom: 6px !important;
    max-width: none !important;
    table-layout: fixed;
    word-break: break-all;
   } 

insert data into database using servlet and jsp in eclipse

Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

fyi, this can happen if you are using the html type="number" attribute on your input tag. Entering a non-number will clear it before your script knows what's going on.

How to force C# .net app to run only one instance in Windows?

This is what I use in my application:

static void Main()
{
  bool mutexCreated = false;
  System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );

  if( !mutexCreated )
  {
    if( MessageBox.Show(
      "slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
      "slimKEYS already running",
      MessageBoxButtons.YesNo,
      MessageBoxIcon.Question ) != DialogResult.Yes )
    {
      mutex.Close();
      return;
    }
  }

  // The usual stuff with Application.Run()

  mutex.Close();
}

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

Check the items in forEach

    <c:forEach items="${pools}" var="pool"> 

        ${pool.name}

    </c:forEach>

Some times items="${pools}" has an extra space or it acts like string, retyping it should solve the issue.

Move cursor to end of file in vim

Go to Top - Double g

Go to Bottom - Shift + g

'nuget' is not recognized but other nuget commands working

Retrieve nuget.exe from https://www.nuget.org/downloads. Copy it to a local folder and add that folder to the PATH environment variable.

This is will make nuget available globally, from any project.

deny directory listing with htaccess

Options -Indexes should work to prevent directory listings.

If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.

ngrok command not found

In shorts,ngrok should be in same directory in which you are running ngrok command.

How to fix 'android.os.NetworkOnMainThreadException'?

Do the network actions on another thread

For Example:

new Thread(new Runnable(){
    @Override
    public void run() {
        // Do network action in this function
    }
}).start();

And add this to AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

How do I do a not equal in Django queryset filtering?

This will give your desired result.

from django.db.models import Q
results = Model.objects.exclude(Q(a=True) & ~Q(x=5))

for not equal you can use ~ on an equal query. obviously, Q can be used to reach the equal query.

How to center content in a bootstrap column?

No need to complicate things. With Bootstrap 4, you can simply align items horizontally inside a column using the margin auto class my-auto

         <div class="col-md-6 my-auto">
           <h3>Lorem ipsum.</h3>
         </div>

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

Getting last month's date in php

public function getLastMonth() {
    $now = new DateTime();
    $lastMonth = $now->sub(new DateInterval('P1M'));
    return $lastMonth->format('Ym');
}

Javascript Append Child AFTER Element

You can use:

if (parentGuest.nextSibling) {
  parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);
}
else {
  parentGuest.parentNode.appendChild(childGuest);
}

But as Pavel pointed out, the referenceElement can be null/undefined, and if so, insertBefore behaves just like appendChild. So the following is equivalent to the above:

parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling);

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

Concluding from above answers, Here is the exact difference between full/strictly, complete and perfect binary trees

  1. Full/Strictly binary tree :- Every node except the leaf nodes have two children

  2. Complete binary tree :- Every level except the last level is completely filled and all the nodes are left justified.

  3. Perfect binary tree :- Every node except the leaf nodes have two children and every level (last level too) is completely filled.

UITableView, Separator color where to set?

Try + (instancetype)appearance of UITableView:

Objective-C:

[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"

Swift 3.0:

UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"

Note: Change will reflect to all tables used in application.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

Firstly, I would try a non-secure websocket connection. So remove one of the s's from the connection address:

conn = new WebSocket('ws://localhost:8080');

If that doesn't work, then the next thing I would check is your server's firewall settings. You need to open port 8080 both in TCP_IN and TCP_OUT.

Converting JavaScript object with numeric keys into array

Try this:

var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
    newArr.push([obj.value]);
});

View more than one project/solution in Visual Studio

After a long research and different experiments the easiest way "FOR MAC USERS" is to create a script:

open -a "Visual Studio" \
"path to first sln" \
"path to second sln" \
...

:D

How to allow only integers in a textbox?

Another solution is to use a RangeValidator where you set Type="Integer" like this:

<asp:RangeValidator runat="server"
    id="valrNumberOfPreviousOwners"
    ControlToValidate="txtNumberOfPreviousOwners"
    Type="Integer"
    MinimumValue="0"
    MaximumValue="999"
    CssClass="input-error"
    ErrorMessage="Please enter a positive integer."
    Display="Dynamic">
</asp:RangeValidator>

You can set reasonable values for the MinimumValue and MaximumValue attributes too.

How do I call one constructor from another in Java?

Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.

Example:

Class Test {
    Test() {
        this(10); // calls the constructor with integer args, Test(int a)
    }
    Test(int a) {
        this(10.5); // call the constructor with double arg, Test(double a)
    }
    Test(double a) {
        System.out.println("I am a double arg constructor");
    }
}

This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.

What's the difference between Docker Compose vs. Dockerfile

In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.

Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db and no longer by its IP.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Douglas Crockford, the author of jslint has written (and spoken) about this issue many times. There's a section on this page of his website which covers this:

for Statement

A for class of statements should have the following form:

for (initialization; condition; update) {
    statements
}

for (variable in object) {
    if (filter) {
        statements
    } 
}

The first form should be used with arrays and with loops of a predeterminable number of iterations.

The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
    if (object.hasOwnProperty(variable)) {
        statements
    } 
}

Crockford also has a video series on YUI theater where he talks about this. Crockford's series of videos/talks about javascript are a must see if you're even slightly serious about javascript.

Random character generator with a range of (A..Z, 0..9) and punctuation

Using some simple command line (bash scripting):

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 30 | xargs
t315,qeqaszwz6kxv?761rf.cj/7gc

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 1 | xargs
f
  • cat /dev/urandom: get a random stream of char from the kernel
  • tr: keep only char char we want
  • head: take only the first n chars
  • xargs: just for adding a '\n' char

Counting number of lines, words, and characters in a text file

try

    int words = 0;
    int lines = 0;
    int chars = 0;
    while(in.hasNextLine())  {
        lines++;
        String line = in.nextLine();
        chars += line.length();
        words += new StringTokenizer(line, " ,").countTokens();
    }

How to get the selected radio button value using js

Since you want to get it using plain javascript, you can use the following code

var val = '';
if(document.getElementById('radio1').checked) {
  val = document.getElementById('radio1').value
}else if(document.getElementById('radio2').checked) {
  val = document.getElementById('radio2').value
}

How to convert a multipart file to File?

MultipartFile.transferTo(File) is nice, but don't forget to clean the temp file after all.

// ask JVM to ask operating system to create temp file
File tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_POSTFIX);

// ask JVM to delete it upon JVM exit if you forgot / can't delete due exception
tempFile.deleteOnExit();

// transfer MultipartFile to File
multipartFile.transferTo(tempFile);

// do business logic here
result = businessLogic(tempFile);

// tidy up
tempFile.delete();

Check out Razzlero's comment about File.deleteOnExit() executed upon JVM exit (which may be extremely rare) details below.

How can I read a large text file line by line using Java?

What you can do is scan the entire text using Scanner and go through the text line by line. Of course you should import the following:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public static void readText throws FileNotFoundException {
    Scanner scan = new Scanner(new File("samplefilename.txt"));
    while(scan.hasNextLine()){
        String line = scan.nextLine();
        //Here you can manipulate the string the way you want
    }
}

Scanner basically scans all the text. The while loop is used to traverse through the entire text.

The .hasNextLine() function is a boolean that returns true if there are still more lines in the text. The .nextLine() function gives you an entire line as a String which you can then use the way you want. Try System.out.println(line) to print the text.

Side Note: .txt is the file type text.

Alternative to itoa() for converting integer to string C++?

In C++11 you can use std::to_string:

#include <string>

std::string s = std::to_string(5);

If you're working with prior to C++11, you could use C++ streams:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

How do I pick randomly from an array?

Random Number of Random Items from an Array

def random_items(array)
  array.sample(1 + rand(array.count))
end

Examples of possible results:

my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))

=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]

How can I clear the terminal in Visual Studio Code?

Go to

  1. File >Preferences >Keyboard shortcuts.
  2. Search for "Terminal: clear"
  3. By default no keyboard shortcut is assigned.
  4. Just click on the Plus (+)icon in the banner and give the preferred shortcut of your choice to clear the terminal.
  5. I prefer to use ctrl+k as that shortcut is not assigned with any command.

How can I conditionally require form inputs with AngularJS?

For Angular2

<input type='email' 
    [(ngModel)]='contact.email'
    [required]='!contact.phone' >

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

I ended up using a normal hyperlink along with Url.Action, as in:

<a href='<%= Url.Action("Show", new { controller = "Browse", id = node.Id }) %>'
  data-nodeId='<%= node.Id %>'>
  <%: node.Name %>
</a>

It's uglier, but you've got a little more control over the a tag, which is sometimes useful in heavily AJAXified sites.

HTH

XAMPP Port 80 in use by "Unable to open process" with PID 4

I had the following error message Port 80 in use by "Unable to open process" with PID 4! Apache WILL NOT start without the configured ports free! You need to uninstall/disable/reconfigure the blocking application or reconfigure Apache and the Control Panel to listen on a different port Starting Check-Timer Control Panel Ready

opened the httpd.conf and changed the listen port from 80 to 1234 in both places

Listen 12.34.56.78:1234

Listen 1234

Then go to Config for the xampp control panel and go to service and port setting and changed the port from 80 to 1234

That worked.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

How to Execute SQL Server Stored Procedure in SQL Developer?

I know this is the old one. But this may help others.

I have added SP calling function between BEGIN/END. Here is a working script.

ALTER Proc [dbo].[DepartmentAddOrEdit]
@Id int,
@Code varchar(100),
@Name varchar(100),
@IsActive bit ,
@LocationId int,
@CreatedBy int,
@UpdatedBy int
AS
    IF(@Id = 0)

    BEGIN
    INSERT INTO Department (Code,Name,IsActive,LocationId,CreatedBy,UpdatedBy,CreatedAt)
        VALUES(@Code,@Name,@IsActive,@LocationId,@CreatedBy,@UpdatedBy,CURRENT_TIMESTAMP)

    EXEC dbo.LogAdd @CreatedBy,'DEPARTMENT',@Name
    END

    ELSE

    UPDATE Department SET
        Code = @Code,
        Name = @Name,
        IsActive = @IsActive,
        LocationId = @LocationId,
        CreatedBy = @CreatedBy,
        UpdatedBy = @UpdatedBy,
        UpdatedAt =  CURRENT_TIMESTAMP 
    where Id = @Id 

How to remove old and unused Docker images

There is sparrow plugin docker-remove-dangling-images you can use to clean up stopped containers and unused (dangling) images:

$ sparrow plg run docker-remove-dangling-images

It works both for Linux and Windows OS.

Pretty printing XML with javascript

here is another function to format xml

function formatXml(xml){
    var out = "";
    var tab = "    ";
    var indent = 0;
    var inClosingTag=false;
    var dent=function(no){
        out += "\n";
        for(var i=0; i < no; i++)
            out+=tab;
    }


    for (var i=0; i < xml.length; i++) {
        var c = xml.charAt(i);
        if(c=='<'){
            // handle </
            if(xml.charAt(i+1) == '/'){
                inClosingTag = true;
                dent(--indent);
            }
            out+=c;
        }else if(c=='>'){
            out+=c;
            // handle />
            if(xml.charAt(i-1) == '/'){
                out+="\n";
                //dent(--indent)
            }else{
              if(!inClosingTag)
                dent(++indent);
              else{
                out+="\n";
                inClosingTag=false;
              }
            }
        }else{
          out+=c;
        }
    }
    return out;
}

Ansible - Save registered variable to file

More readable way of achieving this (not a fan of single line ansible tasks)

- local_action: 
    module: copy 
    content: "{{ foo_result }}"
    dest: /path/to/destination/file

How to enable DataGridView sorting when user clicks on the column header?

put this line in your windows form (on load or better in a public method like "binddata" ):

//
// bind the data and make the grid sortable 
//
this.datagridview1.MakeSortable( myenumerablecollection ); 

Put this code in a file called DataGridViewExtensions.cs (or similar)

// MakeSortable extension. 
// this will make any enumerable collection sortable on a datagrid view.  

//
// BEGIN MAKESORTABLE - Mark A. Lloyd
//
// Enables sort on all cols of a DatagridView 

//



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    public static class DataGridViewExtensions
    {
    public static void MakeSortable<T>(
        this DataGridView dataGridView, 
        IEnumerable<T> dataSource,
        SortOrder defaultSort = SortOrder.Ascending, 
        SortOrder initialSort = SortOrder.None)
    {
        var sortProviderDictionary = new Dictionary<int, Func<SortOrder, IEnumerable<T>>>();
        var previousSortOrderDictionary = new Dictionary<int, SortOrder>();
        var itemType = typeof(T);
        dataGridView.DataSource = dataSource;
        foreach (DataGridViewColumn c in dataGridView.Columns)
        {
            object Provider(T info) => itemType.GetProperty(c.Name)?.GetValue(info);
            sortProviderDictionary[c.Index] = so => so != defaultSort ? 
                dataSource.OrderByDescending<T, object>(Provider) : 
                dataSource.OrderBy<T,object>(Provider);
            previousSortOrderDictionary[c.Index] = initialSort;
        }

        async Task DoSort(int index)
        {

            switch (previousSortOrderDictionary[index])
            {
                case SortOrder.Ascending:
                    previousSortOrderDictionary[index] = SortOrder.Descending;
                    break;
                case SortOrder.None:
                case SortOrder.Descending:
                    previousSortOrderDictionary[index] = SortOrder.Ascending;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            IEnumerable<T> sorted = null;
            dataGridView.Cursor = Cursors.WaitCursor;
            dataGridView.Enabled = false;
            await Task.Run(() => sorted = sortProviderDictionary[index](previousSortOrderDictionary[index]).ToList());
            dataGridView.DataSource = sorted;
            dataGridView.Enabled = true;
            dataGridView.Cursor = Cursors.Default;

        }

        dataGridView.ColumnHeaderMouseClick+= (object sender, DataGridViewCellMouseEventArgs e) => DoSort(index: e.ColumnIndex);
    }
}

useState set method not reflecting change immediately

I just finished a rewrite with useReducer, following @kentcdobs article (ref below) which really gave me a solid result that suffers not one bit from these closure problems.

see: https://kentcdodds.com/blog/how-to-use-react-context-effectively

I condensed his readable boilerplate to my preferred level of DRYness -- reading his sandbox implementation will show you how it actually works.

Enjoy, I know I am !!

import React from 'react'

// ref: https://kentcdodds.com/blog/how-to-use-react-context-effectively

const ApplicationDispatch = React.createContext()
const ApplicationContext = React.createContext()

function stateReducer(state, action) {
  if (state.hasOwnProperty(action.type)) {
    return { ...state, [action.type]: state[action.type] = action.newValue };
  }
  throw new Error(`Unhandled action type: ${action.type}`);
}

const initialState = {
  keyCode: '',
  testCode: '',
  testMode: false,
  phoneNumber: '',
  resultCode: null,
  mobileInfo: '',
  configName: '',
  appConfig: {},
};

function DispatchProvider({ children }) {
  const [state, dispatch] = React.useReducer(stateReducer, initialState);
  return (
    <ApplicationDispatch.Provider value={dispatch}>
      <ApplicationContext.Provider value={state}>
        {children}
      </ApplicationContext.Provider>
    </ApplicationDispatch.Provider>
  )
}

function useDispatchable(stateName) {
  const context = React.useContext(ApplicationContext);
  const dispatch = React.useContext(ApplicationDispatch);
  return [context[stateName], newValue => dispatch({ type: stateName, newValue })];
}

function useKeyCode() { return useDispatchable('keyCode'); }
function useTestCode() { return useDispatchable('testCode'); }
function useTestMode() { return useDispatchable('testMode'); }
function usePhoneNumber() { return useDispatchable('phoneNumber'); }
function useResultCode() { return useDispatchable('resultCode'); }
function useMobileInfo() { return useDispatchable('mobileInfo'); }
function useConfigName() { return useDispatchable('configName'); }
function useAppConfig() { return useDispatchable('appConfig'); }

export {
  DispatchProvider,
  useKeyCode,
  useTestCode,
  useTestMode,
  usePhoneNumber,
  useResultCode,
  useMobileInfo,
  useConfigName,
  useAppConfig,
}

with a usage similar to this:

import { useHistory } from "react-router-dom";

// https://react-bootstrap.github.io/components/alerts
import { Container, Row } from 'react-bootstrap';

import { useAppConfig, useKeyCode, usePhoneNumber } from '../../ApplicationDispatchProvider';

import { ControlSet } from '../../components/control-set';
import { keypadClass } from '../../utils/style-utils';
import { MaskedEntry } from '../../components/masked-entry';
import { Messaging } from '../../components/messaging';
import { SimpleKeypad, HandleKeyPress, ALT_ID } from '../../components/simple-keypad';

export const AltIdPage = () => {
  const history = useHistory();
  const [keyCode, setKeyCode] = useKeyCode();
  const [phoneNumber, setPhoneNumber] = usePhoneNumber();
  const [appConfig, setAppConfig] = useAppConfig();

  const keyPressed = btn => {
    const maxLen = appConfig.phoneNumberEntry.entryLen;
    const newValue = HandleKeyPress(btn, phoneNumber).slice(0, maxLen);
    setPhoneNumber(newValue);
  }

  const doSubmit = () => {
    history.push('s');
  }

  const disableBtns = phoneNumber.length < appConfig.phoneNumberEntry.entryLen;

  return (
    <Container fluid className="text-center">
      <Row>
        <Messaging {...{ msgColors: appConfig.pageColors, msgLines: appConfig.entryMsgs.altIdMsgs }} />
      </Row>
      <Row>
        <MaskedEntry {...{ ...appConfig.phoneNumberEntry, entryColors: appConfig.pageColors, entryLine: phoneNumber }} />
      </Row>
      <Row>
        <SimpleKeypad {...{ keyboardName: ALT_ID, themeName: appConfig.keyTheme, keyPressed, styleClass: keypadClass }} />
      </Row>
      <Row>
        <ControlSet {...{ btnColors: appConfig.buttonColors, disabled: disableBtns, btns: [{ text: 'Submit', click: doSubmit }] }} />
      </Row>
    </Container>
  );
};

AltIdPage.propTypes = {};

Now everything persists smoothly everywhere across all my pages

Nice!

Thanks Kent!

How to access parameters in a Parameterized Build?

I think the variable is available directly, rather than through env, when using Workflow plugin. Try:

node()
{
    print "DEBUG: parameter foo = ${foo}"
}

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

JavaScript operator similar to SQL "like"

No.

You want to use: .indexOf("foo") and then check the index. If it's >= 0, it contains that string.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For those arriving here after updating phpunit to version 6 or greater released on 2017-02-03 (e.g. with composer), you may be getting this error because phpunit code is now namespaced (check changelog).

You will need to refactor things like \PHPUnit_Framework_TestCase to \PHPUnit\Framework\TestCase

How to get the first item from an associative PHP array?

Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:

$arr = array(1,2);
current($arr); // 1
next($arr);    // 2
current($arr); // 2
reset($arr);   // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.

The way to do this without changing the pointer:

$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));

The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

jQuery selector to get form by name

    // this will give all the forms on the page.

    $('form')

   // If you know the name of form then.

    $('form[name="myFormName"]')

  //  If you don't know know the name but the position (starts with 0)

    $('form:eq(1)')  // 2nd form will be fetched.

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

Append text to file from command line without using io redirection

If you just want to tack something on by hand, then the sed answer will work for you. If instead the text is in file(s) (say file1.txt and file2.txt):

Using Perl:

perl -e 'open(OUT, ">>", "outfile.txt"); print OUT while (<>);' file*.txt

N.B. while the >> may look like an indication of redirection, it is just the file open mode, in this case "append".

javascript get x and y coordinates on mouse click

Like this.

_x000D_
_x000D_
function printMousePos(event) {_x000D_
  document.body.textContent =_x000D_
    "clientX: " + event.clientX +_x000D_
    " - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
_x000D_
_x000D_

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

How to pass command line arguments to a shell alias?

Just to reiterate what has been posted for other shells, in Bash the following works:

alias blah='function _blah(){ echo "First: $1"; echo "Second: $2"; };_blah'

Running the following:

blah one two

Gives the output below:

First: one
Second: two

Setting POST variable without using form

You can do it using jQuery. Example:

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script>
    $.ajax({
        url : "next.php",
        type: "POST",
        data : "name=Denniss",
        success: function(data)
        {
            //data - response from server
            $('#response_div').html(data);
        }
    });
</script>

how to execute php code within javascript

Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work

How do you create a UIImage View Programmatically - Swift

This answer is update to Swift 3.

This is how you can add an image view programmatically where you can control the constraints.

Class ViewController: UIViewController {

    let someImageView: UIImageView = {
       let theImageView = UIImageView()
       theImageView.image = UIImage(named: "yourImage.png")
       theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
       return theImageView
    }()

    override func viewDidLoad() {
       super.viewDidLoad()

       view.addSubview(someImageView) //This add it the view controller without constraints
       someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
    }

    // do not forget the `.isActive = true` after every constraint
    func someImageViewConstraints() {
        someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
        someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
        someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
    }

}

Ruby Array find_first object?

Either I don't understand your question, or Enumerable#find is the thing you were looking for.

How to wait for a number of threads to complete?

As Martin K suggested java.util.concurrent.CountDownLatch seems to be a better solution for this. Just adding an example for the same

     public class CountDownLatchDemo
{

    public static void main (String[] args)
    {
        int noOfThreads = 5;
        // Declare the count down latch based on the number of threads you need
        // to wait on
        final CountDownLatch executionCompleted = new CountDownLatch(noOfThreads);
        for (int i = 0; i < noOfThreads; i++)
        {
            new Thread()
            {

                @Override
                public void run ()
                {

                    System.out.println("I am executed by :" + Thread.currentThread().getName());
                    try
                    {
                        // Dummy sleep
                        Thread.sleep(3000);
                        // One thread has completed its job
                        executionCompleted.countDown();
                    }
                    catch (InterruptedException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }.start();
        }

        try
        {
            // Wait till the count down latch opens.In the given case till five
            // times countDown method is invoked
            executionCompleted.await();
            System.out.println("All over");
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

}

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I too had to face the same problem. This worked for me. Right click and run as admin than run usual command to install. But first run update command to update the pip

python -m pip install --upgrade pip

You must enable the openssl extension to download files via https

You need to enable "extension=php_openssl.dll" in both files (php and apache). my pc files path are these :

  1. C:\wamp\bin\php\php5.3.13\php.ini

  2. C:\wamp\bin\apache\apache2.2.22\bin\php.ini

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

IN HTML 5 action="" IS NOT SUPPORTED SO DON'T DO THIS. BAD PRACTICE.

If instead you completely negate action altogether it will submit to the same page by default, I believe this is the best practice:

<form>This will submit to the current page</form>

If you are sumbitting the form using php you may want to consider the following. read more about it here.

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Alternatively you could use # bear in mind though that this will act like an anchor and scroll to the top of the page.

<form action="#">

What should main() return in C and C++?

Return 0 on success and non-zero for error. This is the standard used by UNIX and DOS scripting to find out what happened with your program.

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

How do I get the size of a java.sql.ResultSet?

theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet theResult=theStatement.executeQuery(query); 

//Get the size of the data returned
theResult.last();     
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();       
theResult.beforeFirst();

MySQL select where column is not empty

To check if field is NULL use IS NULL, IS NOT NULL operators.

MySql reference http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

Use curly braces to initialize a Set in Python

You need to do empty_set = set() to initialize an empty set. {} is an empty dict.

Using Bootstrap Tooltip with AngularJS

Because of the tooltip function, you have to tell angularJS that you are using jQuery.

This is your directive:

myApp.directive('tooltip', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('mouseenter', function () {
                jQuery.noConflict();
                (function ($) {
                    $(element[0]).tooltip('show');
                })(jQuery);
            });
        }
    };
});

and this is how to use the directive :


<a href="#" title="ToolTip!" data-toggle="tooltip" tooltip></a>

UIScrollView scroll to bottom programmatically

In swift:

   if self.mainScroll.contentSize.height > self.mainScroll.bounds.size.height {
        let bottomOffset = CGPointMake(0, self.mainScroll.contentSize.height - self.mainScroll.bounds.size.height);
        self.mainScroll.setContentOffset(bottomOffset, animated: true)
    }

Auto expand a textarea using jQuery

If you dont want a plugin there is a very simple solution

$("textarea").keyup(function(e) {
    while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
        $(this).height($(this).height()+1);
    };
});

See it working in a jsFiddle I used to answer another textarea question here.

To answer the question of doing it in reverse or making it smaller as text is removed: jsFiddle

And if you do want a plugin

@Jason has designed one here

how to read a long multiline string line by line in python

by splitting with newlines.

for line in wallop_of_a_string_with_many_lines.split('\n'):
  #do_something..

if you iterate over a string, you are iterating char by char in that string, not by line.

>>>string = 'abc'
>>>for line in string:
    print line

a
b
c

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

Best way to detect when a user leaves a web page?

One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.

Of course this won't work if the user simply closes the browser window or types in a new URL.

To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).

How do I center text horizontally and vertically in a TextView?

Here is solution.

<TextView  
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:gravity="center"
       android:text="**Your String Value**" />

JavaScript onclick redirect

Doing this fixed my issue

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value;
        window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
    }
</script>

I changed .value(); to .value; taking out the ()

I did not change anything in my text field or submit button

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

Works like a charm.

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

How to redirect and append both stdout and stderr to a file with Bash?

Try this

You_command 1>output.log  2>&1

Your usage of &>x.file does work in bash4. sorry for that : (

Here comes some additional tips.

0, 1, 2...9 are file descriptors in bash.

0 stands for stdin, 1 stands for stdout, 2 stands for stderror. 3~9 is spare for any other temporary usage.

Any file descriptor can be redirected to other file descriptor or file by using operator > or >>(append).

Usage: <file_descriptor> > <filename | &file_descriptor>

Please reference to http://www.tldp.org/LDP/abs/html/io-redirection.html

Byte Array to Hex String

Using str.format:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1

or using format

>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1

Note: In the format statements, the 02 means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101) would be formatted to "111" instead of "010101"

or using bytearray with binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'

Here is a benchmark of above methods in Python 3.6.1:

from timeit import timeit
import binascii

number = 10000

def using_str_format() -> str:
    return "".join("{:02x}".format(x) for x in test_obj)

def using_format() -> str:
    return "".join(format(x, "02x") for x in test_obj)

def using_hexlify() -> str:
    return binascii.hexlify(bytearray(test_obj)).decode('ascii')

def do_test():
    print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
    if using_str_format() != using_format() != using_hexlify():
        raise RuntimeError("Results are not the same")

    print("Using str.format       -> " + str(timeit(using_str_format, number=number)))
    print("Using format           -> " + str(timeit(using_format, number=number)))
    print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))

test_obj = bytes([i for i in range(255)])
do_test()

test_obj = bytearray([i for i in range(255)])
do_test()

Result:

Testing with 255-byte bytes:
Using str.format       -> 1.459474583090427
Using format           -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format       -> 1.443447684109402
Using format           -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684

Methods using format do provide additional formatting options, as example separating numbers with spaces " ".join, commas ", ".join, upper-case printing "{:02X}".format(x)/format(x, "02X"), etc., but at a cost of great performance impact.

How can I open a Shell inside a Vim Window?

Well it depends on your OS - actually I did not test it on MS Windows - but Conque is one of the best plugins out there.

Actually, it can be better, but works.

How to auto generate migrations with Sequelize CLI from Sequelize models?

Another solution is to put data definition into a separate file.

The idea is to write data common for both model and migration into a separate file, then require it in both the migration and the model. Then in the model we can add validations, while the migration is already good to go.

In order to not clutter this post with tons of code i wrote a GitHub gist.

See it here: https://gist.github.com/igorvolnyi/f7989fc64006941a7d7a1a9d5e61be47

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

Can you write virtual functions / methods in Java?

In Java, all public (non-private) variables & functions are Virtual by default. Moreover variables & functions using keyword final are not virtual.

Using Python's ftplib to get a directory listing, portably

There's no standard for the layout of the LIST response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls and Windows Server DIR formats. There's a lot of variety out there, though.

Fall back to the nlst method (returning the result of the NLST command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.

Drop all tables command

While it is true that there is no DROP ALL TABLES command you can use the following set of commands.

Note: These commands have the potential to corrupt your database, so make sure you have a backup

PRAGMA writable_schema = 1;
delete from sqlite_master where type in ('table', 'index', 'trigger');
PRAGMA writable_schema = 0;

you then want to recover the deleted space with

VACUUM;

and a good test to make sure everything is ok

PRAGMA INTEGRITY_CHECK;

How to stop java process gracefully?

Ok, after all the possibilities I have chosen to work with "Java Monitoring and Management"
Overview is here
That allows you to control one application from another one in relatively easy way. You can call the controlling application from a script to stop controlled application gracefully before killing it.

Here is the simplified code:

Controlled application:
run it with the folowing VM parameters:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

//ThreadMonitorMBean.java
public interface ThreadMonitorMBean
{
String getName();
void start();
void stop();
boolean isRunning();
}

// ThreadMonitor.java
public class ThreadMonitor implements ThreadMonitorMBean
{
private Thread m_thrd = null;

public ThreadMonitor(Thread thrd)
{
    m_thrd = thrd;
}

@Override
public String getName()
{
    return "JMX Controlled App";
}

@Override
public void start()
{
    // TODO: start application here
    System.out.println("remote start called");
}

@Override
public void stop()
{
    // TODO: stop application here
    System.out.println("remote stop called");

    m_thrd.interrupt();
}

public boolean isRunning()
{
    return Thread.currentThread().isAlive();
}

public static void main(String[] args)
{
    try
    {
        System.out.println("JMX started");

        ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread());

        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        ObjectName name = new ObjectName("com.example:type=ThreadMonitor");

        server.registerMBean(monitor, name);

        while(!Thread.interrupted())
        {
            // loop until interrupted
            System.out.println(".");
            try 
            {
                Thread.sleep(1000);
            } 
            catch(InterruptedException ex) 
            {
                Thread.currentThread().interrupt();
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        // TODO: some final clean up could be here also
        System.out.println("JMX stopped");
    }
}
}

Controlling application:
run it with the stop or start as the command line argument

public class ThreadMonitorConsole
{

public static void main(String[] args)
{
    try
    {   
        // connecting to JMX
        System.out.println("Connect to JMX service.");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // Construct proxy for the the MBean object
        ObjectName mbeanName = new ObjectName("com.example:type=ThreadMonitor");
        ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true);

        System.out.println("Connected to: "+mbeanProxy.getName()+", the app is "+(mbeanProxy.isRunning() ? "" : "not ")+"running");

        // parse command line arguments
        if(args[0].equalsIgnoreCase("start"))
        {
            System.out.println("Invoke \"start\" method");
            mbeanProxy.start();
        }
        else if(args[0].equalsIgnoreCase("stop"))
        {
            System.out.println("Invoke \"stop\" method");
            mbeanProxy.stop();
        }

        // clean up and exit
        jmxc.close();
        System.out.println("Done.");    
    }
    catch(Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}


That's it. :-)

How to launch Windows Scheduler by command-line?

I'm using Windows 2003 on the server. I'm in action with "SCHTASKS.EXE"

    SCHTASKS /parameter [arguments]

    Description:
        Enables an administrator to create, delete, query, change, run and
        end scheduled tasks on a local or remote system. Replaces AT.exe.

    Parameter List:
        /Create         Creates a new scheduled task.

        /Delete         Deletes the scheduled task(s).

        /Query          Displays all scheduled tasks.

        /Change         Changes the properties of scheduled task.

        /Run            Runs the scheduled task immediately.

        /End            Stops the currently running scheduled task.

        /?              Displays this help message.

    Examples:
        SCHTASKS
        SCHTASKS /?
        SCHTASKS /Run /?
        SCHTASKS /End /?
        SCHTASKS /Create /?
        SCHTASKS /Delete /?
        SCHTASKS /Query  /?
        SCHTASKS /Change /?

    +-------------------------------------+
    ¦ Executed Wed 02/29/2012 10:48:36.65 ¦
    +-------------------------------------+

It's quite interesting and makes me feel so powerful. :)

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

For my case, the culprit was the semicolon and double quotes in the password for prod DB. Our IT team use some tool to generate passwords, so it generated one with the semicolon and double quotes Connectionstring looks like

<add key="BusDatabaseConnectionString" value="Data Source=myserver;Initial Catalog=testdb;User Id=Listener;Password=BlaBla"';[]qrk/>

Got the password changed and it worked.

Replace last occurrence of a string in a string

Use the "$" on a reg expression to match the end of the string

$string = 'The quick brown fox jumps over the lazy fox';
echo preg_replace('/fox$/', 'dog', $string);

//output
'The quick brown fox jumps over the lazy dog'

URL encoding in Android

Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:

for (int i = 0; i < urlAsString.length(); i++) {
    if (urlAsString.charAt(i) > 255) {
        urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
    }
}
encodedURL = urlAsString;

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

  1. running code before Compilation : use controller
  2. running code after Compilation : use Link

Angular convention : write business logic in controller and DOM manipulation in link.

Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives

<animal>
<panther>
<leopard></leopard>
</panther> 
</animal>

and you want to access animal from inside of "leopard" directive.

http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication

Calculating a directory's size using Python?

Chris' answer is good but could be made more idiomatic by using a set to check for seen directories, which also avoids using an exception for control flow:

def directory_size(path):
    total_size = 0
    seen = set()

    for dirpath, dirnames, filenames in os.walk(path):
        for f in filenames:
            fp = os.path.join(dirpath, f)

            try:
                stat = os.stat(fp)
            except OSError:
                continue

            if stat.st_ino in seen:
                continue

            seen.add(stat.st_ino)

            total_size += stat.st_size

    return total_size  # size in bytes

Count with IF condition in MySQL query

Replace this line:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments

With this one:

coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments

Command to delete all pods in all kubernetes namespaces

You just need sed to do this:

kubectl get pods --no-headers=true --all-namespaces |sed -r 's/(\S+)\s+(\S+).*/kubectl --namespace \1 delete pod \2/e'

Explains:

  1. use command kubectl get pods --all-namespaces to get the list of all pods in all namespaces.
  2. use --no-headers=true option to hide the headers.
  3. use s command of sed to fetch the first two words, which represent namespace and pod's name respectively, then assemble the delete command using them.
  4. the final delete command is just like: kubectl --namespace kube-system delete pod heapster-eq3yw.
  5. use the e modifier of s command to execute the command assembled above, which will do the actual delete works.

To avoid delete pods in kube-system namespace, just need to add grep -v kube-system to exclude kube-system namespace before the sed command.

Why can't I push to this bare repository?

This related question's answer provided the solution for me... it was just a dumb mistake:

Remember to commit first!

https://stackoverflow.com/a/7572252

If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.

Visual Studio - How to change a project's folder name and solution name without breaking the solution

I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.

Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.

java.io.FileNotFoundException: the system cannot find the file specified

Put the word.txt directly as a child of the project root folder and a peer of src

Project_Root
    src
    word.txt

Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.

Why it works:

When you use File or any of the other FileXxx variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:

When you run from the command line

C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1

the working directory is C:\EclipseWorkspace\ProjectRoot\bin. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.

Similarly, if this was your project structure ProjectRoot\src\word.txt, then the path "src/word.txt" would be valid.

Why it May not Work

For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not bin\word.txt

Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.

That being said, you need to determine if the file is to be an (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src or in some directory below, then the default build should put it into the class path.

You can access classpath resource in a number of ways. You can make use of the Class class, which has getResourceXxx method, from which you use to obtain classpath resources.

For example, if you changed your project structure to ProjectRoot\src\resources\word.txt, you could use this:

InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

getResourceAsStream returns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URL if that's what you need. getResource() will return an URL

For Maven users, where the directory structure is like src/main/resources, the contents of the resources folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")

Add/remove class with jquery based on vertical scroll?

Add some transition effect to it if you like:

http://jsbin.com/boreme/17/edit?html,css,js

.clearHeader {
  height:50px;
  background:lightblue;
  position:fixed;
  top:0;
  left:0;
  width:100%;

  -webkit-transition: background 2s; /* For Safari 3.1 to 6.0 */
  transition: background 2s;
}

.clearHeader.darkHeader {
 background:#000;
}

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

Using Python to execute a command on every file in a folder

AVI to MPG (pick your extensions):

files = os.listdir('/input')
for sourceVideo in files:
    if sourceVideo[-4:] != ".avi"
        continue
    destinationVideo = sourceVideo[:-4] + ".mpg"
    cmdLine = ['mencoder', sourceVideo, '-ovc', 'copy', '-oac', 'copy', '-ss',
        '00:02:54', '-endpos', '00:00:54', '-o', destinationVideo]
    output1 = Popen(cmdLine, stdout=PIPE).communicate()[0]
    print output1
    output2 = Popen(['del', sourceVideo], stdout=PIPE).communicate()[0]
    print output2

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

JSON.parse unexpected character error

You're not parsing a string, you're parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

No resource found that matches the given name '@style/ Theme.Holo.Light.DarkActionBar'

The @android did not work for me. When I use android (without the @) it works like a charm.

Example:

<style name="CustomActionBarTheme"
       parent="android:style/Theme.Holo.Light.DarkActionBar">

Git 'fatal: Unable to write new index file'

I had ACL (somehow) attached to all files in the .git folder.

Check it with ls -le in the .git folder.

You can remove the ACL with chmod -N (for a folder/file) or chmod -RN (recursive)

File Upload using AngularJS

Some of the answers here propose using FormData(), but unfortunately that is a browser object not available in Internet Explorer 9 and below. If you need to support those older browsers, you will need a backup strategy such as using <iframe> or Flash.

There are already many Angular.js modules to perform file uploading. These two have explicit support for older browsers:

And some other options:

One of these should fit your project, or may give you some insight into how to code it yourself.

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

Get a DataTable Columns DataType

dt.Columns[0].DataType.Name.ToString()

How to make a Div appear on top of everything else on the screen?

One form to do this is insert the panel that you want to expand inside a DIV setted as relative: let me show you:

<div style="position:relative">
  <div style="position:absolute; z-index: 1000;">
    your code
  </div>
</div>

You use the first div to position the inner content in a specific area inside your page and the second absolute should be referred to the container (because is relative) The z-index in this case is referred also to container and if it higher that the container should be at top. You can put the style in a CSS class and change the size of the absolute div to expand it on hover or another action that you want to control.

I hope that this help

In Java, how do I check if a string contains a substring (ignoring case)?

How about matches()?

String string = "Madam, I am Adam";

// Starts with
boolean  b = string.startsWith("Mad");  // true

// Ends with
b = string.endsWith("dam");             // true

// Anywhere
b = string.indexOf("I am") >= 0;        // true

// To ignore case, regular expressions must be used

// Starts with
b = string.matches("(?i)mad.*");

// Ends with
b = string.matches("(?i).*adam");

// Anywhere
b = string.matches("(?i).*i am.*");

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

It worked for me, but the exe4j can leave a signature when you double click the .exe application

Using reCAPTCHA on localhost

I was recently working on creating a website involving recaptcha v2 and I have a need to do test automation on my localhost. I did not add any ip or localhost into recaptcha admin portal.

Follow the below steps

  1. Log in to recaptcha admin site screenshot

  2. Locate Key Settings

  3. Click on advanced settings

  4. Under Domain Name Validation, un-check Verify the origin of reCAPTCHA solutions checkbox. This option is used to verifying requests come from one of the above listed domains.

    Please note that, If disabled, you are required to check the host-name on your server when verifying a solution.


I created a new key and disable this and use this key for testing in localhost.

This is a sample page which implements reCAPTCHA for comments.

How to allow Cross domain request in apache2

Enable mod_headers in Apache2 to be able to use Header directive :

a2enmod headers

PHP, display image with Header()

Though weirdly named, you can use the getimagesize() function. This will also give you mime information:

Array
(
    [0] => 295 // width
    [1] => 295 // height
    [2] => 3 // http://php.net/manual/en/image.constants.php
    [3] => width="295" height="295" // width and height as attr's
    [bits] => 8
    [mime] => image/png
)

How to increase the gap between text and underlining in CSS

I know it's an old question, but for single line text setting display: inline-block and then setting the height has worked well for me to control the distance between a border and the text.

Difference between null and empty ("") Java String

as a curiosity

    String s1 = null;
    String s2 = "hello";

     s1 = s1 + s2;
   

    System.out.println((s); // nullhello

Correct way to import lodash

I just put them in their own file and export it for node and webpack:

// lodash-cherries.js
module.exports = {
  defaults: require('lodash/defaults'),
  isNil: require('lodash/isNil'),
  isObject: require('lodash/isObject'),
  isArray: require('lodash/isArray'),
  isFunction: require('lodash/isFunction'),
  isInteger: require('lodash/isInteger'),
  isBoolean: require('lodash/isBoolean'),
  keys: require('lodash/keys'),
  set: require('lodash/set'),
  get: require('lodash/get'),
}

?: operator (the 'Elvis operator') in PHP

It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = bar ? bar : baz;

or

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

with the difference that bar will only be evaluated once.

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

Some more examples:

<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>

By the way, it's called the Elvis operator.

Elvis operator

Image re-size to 50% of original size in HTML

You can use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

Clip/Crop background-image with CSS

You can put the graphic in a pseudo-element with its own dimensional context:

#graphic {
  position: relative;
  width: 200px;
  height: 100px;
}
#graphic::before {
  position: absolute;
  content: '';
  z-index: -1;
  width: 200px;
  height: 50px;
  background-image: url(image.jpg);
}

_x000D_
_x000D_
#graphic {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
    content: '';_x000D_
    _x000D_
    position: absolute;_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    z-index: -1;_x000D_
    _x000D_
    background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
_x000D_
_x000D_

Browser support is good, but if you need to support IE8, use a single colon :before. IE has no support for either syntax in versions prior to that.

How do I make an HTTP request in Swift?

Another option is the Alamofire lib that offers Chainable Request / Response methods.

https://github.com/Alamofire/Alamofire

Making a Request

import Alamofire

Alamofire.request(.GET, "http://httpbin.org/get")

Response Handling

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { request, response, data, error in
              print(request)
              print(response)
              print(error)
          }

How do I create a MongoDB dump of my database?

cmd -->

C:\Program Files\MongoDB\Server\3.2\bin>mongodump.exe --db Dintest

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can also write it like this:

let elem: any;
elem = $("div.printArea");
elem.printArea();

Java logical operator short-circuiting

if(demon!=0&& num/demon>10)

Since the short-circuit form of AND(&&) is used, there is no risk of causing a run-time exception when demon is zero.

Ref. Java 2 Fifth Edition by Herbert Schildt

Multidimensional arrays in Swift

Using http://blog.trolieb.com/trouble-multidimensional-arrays-swift/ as a start, I added generics to mine:

class Array2DTyped<T>{

var cols:Int, rows:Int
var matrix:[T]

init(cols:Int, rows:Int, defaultValue:T){
    self.cols = cols
    self.rows = rows
    matrix = Array(count:cols*rows,repeatedValue:defaultValue)
}

subscript(col:Int, row:Int) -> T {
    get{
        return matrix[cols * row + col]
    }
    set{
        matrix[cols * row + col] = newValue
    }
}

func colCount() -> Int {
    return self.cols
}

func rowCount() -> Int {
    return self.rows
}
}

Variable interpolation in the shell

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`

How to capitalize the first letter of a String in Java?

try this one

What this method does is that, Consider the word "hello world" this method turn it into "Hello World" capitalize the beginning of each word .

 private String capitalizer(String word){

        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();

    }

Running Selenium Webdriver with a proxy in Python

Try setting up sock5 proxy too. I was facing the same problem and it is solved by using the socks proxy

def install_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("network.proxy.https",PROXY_HOST)
        fp.set_preference("network.proxy.https_port",int(PROXY_PORT))
        fp.set_preference("network.proxy.ssl",PROXY_HOST)
        fp.set_preference("network.proxy.ssl_port",int(PROXY_PORT))  
        fp.set_preference("network.proxy.ftp",PROXY_HOST)
        fp.set_preference("network.proxy.ftp_port",int(PROXY_PORT))   
        fp.set_preference("network.proxy.socks",PROXY_HOST)
        fp.set_preference("network.proxy.socks_port",int(PROXY_PORT))   
        fp.set_preference("general.useragent.override","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call install_proxy ( ip , port ) from your program.

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

What is the use of DesiredCapabilities in Selenium WebDriver?

I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities are used like setting your config with key-value pair.
Below is an example related to Appium used for Automating Mobile platforms like Android and IOS.
So we generally set DesiredCapabilities for conveying our WebDriver for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.

So we set our DesiredCapabilities as:

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");

// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");

// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability.

//You need to check for your appPackage Name for your app, you can use this app for that APK INFO

// Set your application's appPackage if you are using any other app. 
capabilities.setCapability("appPackage", "com.android.appPackageName");

// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

This DesiredCapabilities are very specific to Appium on Android Platform. For more you can refer to the official site of Selenium desiredCapabilities class

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

The ENOSPC ("No space left on device") error will be triggered in any situation in which the data or the metadata associated with an I/O operation can't be written down anywhere because of lack of space. This doesn't always mean disk space – it could mean physical disk space, logical space (e.g. maximum file length), space in a certain data structure or address space. For example you can get it if there isn't space in the directory table (vfat) or there aren't any inodes left. It roughly means “I can't find where to write this down”.

Particularly in Python, this can happen on any write I/O operation. It can happen during f.write, but it can also happen on open, on f.flush and even on f.close. Where it happened provides a vital clue for the reason that it did – if it happened on open there wasn't enough space to write the metadata for the entry, if it happened during f.write, f.flush or f.close there wasn't enough disk space left or you've exceeded the maximum file size.

If the filesystem in the given directory is vfat you'd hit the maximum file limit at about the same time that you did. The limit is supposed to be 2^16 directory entries, but if I recall correctly some other factors can affect it (e.g. some files require more than one entry).

It would be best to avoid creating so many files in a directory. Few filesystems handle so many directory entries with ease. Unless you're certain that your filesystem deals well with many files in a directory, you can consider another strategy (e.g. create more directories).

P.S. Also do not trust the remaining disk space – some file systems reserve some space for root and others miscalculate the free space and give you a number that just isn't true.

How do I create a comma-separated list using a SQL query?

I don't know if there's any solution to do this in a database-agnostic way, since you most likely will need some form of string manipulation, and those are typically different between vendors.

For SQL Server 2005 and up, you could use:

SELECT
     r.ID, r.Name,
     Resources = STUFF(
       (SELECT ','+a.Name
        FROM dbo.Applications a
        INNER JOIN dbo.ApplicationsResources ar ON ar.app_id = a.id
        WHERE ar.resource_id = r.id
        FOR XML PATH('')), 1, 1, '')
FROM
     dbo.Resources r

It uses the SQL Server 2005 FOR XML PATH construct to list the subitems (the applications for a given resource) as a comma-separated list.

Marc

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I encounter this problem when trying to use matlab eng to call m functions from c code. which occurs with command mex -f .. ..

My solution:

strings /usr/lib/i386-<tab>/libstdc++.so.6 | grep GLIBC

I found it includes 3.4.15

so my system has the newest libs.

the problem comes from matlab itself, it calls its own libstdc++.so.6 from {MATLAB}/bin

so, just replace it with the updated system lib.

How can I use NSError in my iPhone App?

Well, what I usually do is have my methods that could error-out at runtime take a reference to a NSError pointer. If something does indeed go wrong in that method, I can populate the NSError reference with error data and return nil from the method.

Example:

- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}

We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:

// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

We were able to access the error's localizedDescription because we set a value for NSLocalizedDescriptionKey.

The best place for more information is Apple's documentation. It really is good.

There is also a nice, simple tutorial on Cocoa Is My Girlfriend.

How to set Linux environment variables with Ansible

There are multiple ways to do this and from your question it's nor clear what you need.

1. If you need environment variable to be defined PER TASK ONLY, you do this:

- hosts: dev
  tasks:
    - name: Echo my_env_var
      shell: "echo $MY_ENV_VARIABLE"
      environment:
        MY_ENV_VARIABLE: whatever_value

    - name: Echo my_env_var again
      shell: "echo $MY_ENV_VARIABLE"

Note that MY_ENV_VARIABLE is available ONLY for the first task, environment does not set it permanently on your system.

TASK: [Echo my_env_var] ******************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}

TASK: [Echo my_env_var again] ************************************************* 
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}

Hopefully soon using environment will also be possible on play level, not only task level as above. There's currently a pull request open for this feature on Ansible's GitHub: https://github.com/ansible/ansible/pull/8651

UPDATE: It's now merged as of Jan 2, 2015.

2. If you want permanent environment variable + system wide / only for certain user

You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:

  • ~/.profile
  • /etc/environment
  • /etc/profile.d directory
  • ...

You will find Ubuntu docs about it here: https://help.ubuntu.com/community/EnvironmentVariables

After all for setting environment variable in ex. Ubuntu you can just use lineinfile module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

Trigger change() event when setting <select>'s value with val() function

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

How to fill Dataset with multiple tables?

public DataSet GetDataSet()
    {
        try
        {
            DataSet dsReturn = new DataSet();
            using (SqlConnection myConnection = new SqlConnection(Core.con))
            {
                string query = "select * from table1;  select* from table2";
                SqlCommand cmd = new SqlCommand(query, myConnection);
                myConnection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                dsReturn.Load(reader, LoadOption.PreserveChanges, new string[] { "tableOne", "tableTwo" });
                return dsReturn;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

How about something like this?

<div id="leftContainer">
  <span>Company Name</span>
  <br><input type="text" value="John Lewis Partnership">
</div>
<div id="rightContainer">
  <span>Contact Name</span>
  <br><input type="text" value="Timothy Patten">
</div>

Then, you can align the 2 divs by floating them left and right:-

#leftContainer {
   float:left;
}

#rightContainer {
   float:right;
}

Open another application from your own (intent)

If you already have the package name you wish to activate, you can use the following code which is a bit more generic:

PackageManager pm = context.getPackageManager();
Intent appStartIntent = pm.getLaunchIntentForPackage(appPackageName);
if (null != appStartIntent)
{
    context.startActivity(appStartIntent);
}

I found that it works better for cases where the main activity was not found by the regular method of start the MAIN activity.

How do I catch an Ajax query post error?

you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...

quickie example:

ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
    alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );

Returning a stream from File.OpenRead()

You forgot to reset the position of the memory stream:

private void Test()
{            
    System.IO.MemoryStream data = new System.IO.MemoryStream();
    System.IO.Stream str = TestStream();

    str.CopyTo(data);
    // Reset memory stream
    data.Seek(0, SeekOrigin.Begin);
    byte[] buf = new byte[data.Length];
    data.Read(buf, 0, buf.Length);                       
}

Update:

There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:

private void Test()
{            
    using(MemoryStream data = new MemoryStream())
    {
        using(Stream str = TestStream())
        {
           str.CopyTo(data);
        }
        // Reset memory stream
        data.Seek(0, SeekOrigin.Begin);
        byte[] buf = new byte[data.Length];
        int bytesRead = data.Read(buf, 0, buf.Length);

        Debug.Assert(bytesRead == data.Length, 
                    String.Format("Expected to read {0} bytes, but read {1}.",
                        data.Length, bytesRead));
    }                     
}

Nexus 5 USB driver

Currently experienced this problem with my Nexus 5, when attempting to sideload latest 4.4.1 OTA update via stock recovery.

Solution:

  1. Open Android SDK Manager (in console get to sdk directory then run tools\android)
  2. Download/install latest USB drivers (under Extras).
  3. In Windows Device Manager (devmgmt.msc), right click the Nexus 5 device and select Update Driver Software.
  4. Browse My Computer for driver software > Android SDK Dir > Extras > usb_driver

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Calling performSelector with an NSNumber or other NSValue will not work. Instead of using the value of the NSValue/NSNumber, it will effectively cast the pointer to an int, float, or whatever and use that.

But the solution is simple and obvious. Create the NSInvocation and call

[invocation performSelector:@selector(invoke) withObject:nil afterDelay:delay]

How to check if an Object is a Collection Type in Java?

Have you thinked about using instanceof ? Like, say

if(myObject instanceof Collection) {
     Collection myCollection = (Collection) myObject;

Although not that pure OOP style, it is however largely used for so-called "type escalation".

Why do you need to invoke an anonymous function on the same line?

Another point of view

First, you can declare an anonymous function:

var foo = function(msg){
 alert(msg);
}

Then you call it:

foo ('Few');

Because foo = function(msg){alert(msg);} so you can replace foo as:

function(msg){
 alert(msg);
} ('Few');

But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,

(function(msg){
 alert(msg);
}) ('Few');

By this way, It's easy understand for me.

JSON formatter in C#?

There are already a bunch of great answers here that use Newtonsoft.JSON, but here's one more that uses JObject.Parse in combination with ToString(), since that hasn't been mentioned yet:

var jObj = Newtonsoft.Json.Linq.JObject.Parse(json);
var formatted = jObj.ToString(Newtonsoft.Json.Formatting.Indented);

Assign an initial value to radio button as checked

Note that if you have two radio button with same "name" attribute and they have "required" attribute, then adding "checked" attribute to them won't make them checked.

Example: This makes both radio button remain unchecked.

<input type="radio" name="gender" value="male" required <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" required />

This will makes the "male" radio button checked.

<input type="radio" name="gender" value="male" <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" />

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date +%s

This works fine for me on OS X Lion.

IntelliJ does not show 'Class' when we right click and select 'New'

you need to mark your directory as source root (right click on the parent directory)

and then compile the plugin (it is important )

as result you will be able to add classes and more

enter image description here

enter image description here

rewrite a folder name using .htaccess

try:

RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.

See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/

There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php

to redirect from /folder1 to /apple try this:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]

to redirect and then rewrite just combine the above in the htaccess file:

RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]

How to override !important?

I would like to add an answer to this that hasn't been mentioned, as I have tried all of the above to no avail. My specific situation is that I am using semantic-ui, which has built in !important attributes on elements (extremely annoying). I tried everything to override it, only in the end did one thing work (using jquery). It is as follows:

$('.active').css('cssText', 'border-radius: 0px !important');

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

Hide/Show components in react native

An additional option is to apply absolute positioning via styling, setting the hidden component in out-of-screen coordinates:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})}
    style={this.state.hide ? {position: 'absolute', top: -200} : {}}
/>

Unlike in some of the previous suggestions, this would hide your component from view BUT will also render it (keep it in the DOM), thus making it truly invisible.

How do I use tools:overrideLibrary in a build.gradle file?

use this code in manifest.xml

<uses-sdk
android:minSdkVersion="16"
android:maxSdkVersion="17"
tools:overrideLibrary="x"/>

How do you test that a Python function throws an exception?

I use doctest[1] almost everywhere because I like the fact that I document and test my functions at the same time.

Have a look at this code:

def throw_up(something, gowrong=False):
    """
    >>> throw_up('Fish n Chips')
    Traceback (most recent call last):
    ...
    Exception: Fish n Chips

    >>> throw_up('Fish n Chips', gowrong=True)
    'I feel fine!'
    """
    if gowrong:
        return "I feel fine!"
    raise Exception(something)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

If you put this example in a module and run it from the command line both test cases are evaluated and checked.

[1] Python documentation: 23.2 doctest -- Test interactive Python examples

Nginx no-www to www and www to no-www

try this

    if ($host !~* ^www\.){
        rewrite ^(.*)$ https://www.yoursite.com$1;
    }

Other way: Nginx no-www to www

server {
  listen       80;
  server_name  yoursite.com;
  root /path/;
  index index.php;
  return       301 https://www.yoursite.com$request_uri;
}

and www to no-www

server {
  listen       80;
  server_name  www.yoursite.com;
  root /path/;
  index index.php;
  return       301 https://yoursite.com$request_uri;
}

Why is it string.join(list) instead of list.join(string)?

- in "-".join(my_list) declares that you are converting to a string from joining elements a list.It's result-oriented. (just for easy memory and understanding)

I made an exhaustive cheatsheet of methods_of_string for your reference.

string_methods_44 = {
    'convert': ['join','split', 'rsplit','splitlines', 'partition', 'rpartition'],
    'edit': ['replace', 'lstrip', 'rstrip', 'strip'],
    'search': ['endswith', 'startswith', 'count', 'index', 'find','rindex', 'rfind',],
    'condition': ['isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isnumeric','isidentifier',
                  'islower','istitle', 'isupper','isprintable', 'isspace', ],
    'text': ['lower', 'upper', 'capitalize', 'title', 'swapcase',
             'center', 'ljust', 'rjust', 'zfill', 'expandtabs','casefold'],
    'encode': ['translate', 'maketrans', 'encode'],
    'format': ['format', 'format_map']}

Cannot open Windows.h in Microsoft Visual Studio

1) Go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A for VS2013

2) Copy the folders Include and Lib (you should check where are your folders in folder windows such as v7.1, v8, v6, etc.)

3) Paste them into C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC

I solved my problems like:

error lnk1104: cannot open file 'kernel32.lib'.
error c1083: Cannot open Windows.h

Thanks.

Get size of folder or file

public static long getFolderSize(File dir) {
    long size = 0;
    for (File file : dir.listFiles()) {
        if (file.isFile()) {
            System.out.println(file.getName() + " " + file.length());
            size += file.length();
        }
        else
            size += getFolderSize(file);
    }
    return size;
}

How do I split an int into its digits?

#include <iostream>

using namespace std;

int main()

{


int n1 ;

cout <<"Please enter five digits number: ";
cin >> n1;

    cout << n1 / 10000 % 10 << " ";
    cout << n1 / 1000 % 10 << " ";
    cout << n1 / 100 % 10 << " ";
    cout << n1 / 10 % 10 << " ";
    cout << n1 % 10 << " :)";   

cout << endl;

return 0;
}

What is the use of ObservableCollection in .net?

One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.

EDIT: Here's some sample code from MSDN: http://msdn.microsoft.com/en-us/library/ms748365.aspx

In C#, hooking the ListBox to the collection could be as easy as

listBox.ItemsSource = NameListData;

though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:

public override ToString()
{
    return string.Format("{0} {1}", this.FirstName, this.LastName);
}

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

You want to follow the same pattern as before:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

In this case it would be:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}

How to get a responsive button in bootstrap 3

For anyone who may be interested, another approach is using @media queries to scale the buttons on different viewport widths..

Demo: http://bootply.com/93706

Make a link open a new window (not tab)

With pure HTML you can't influence this - every modern browser (= the user) has complete control over this behavior because it has been misused a lot in the past...

HTML option

You can open a new window (HTML4) or a new browsing context (HTML5). Browsing context in modern browsers is mostly "new tab" instead of "new window". You have no influence on that, and you can't "force" modern browsers to open a new window.

In order to do this, use the anchor element's attribute target[1]. The value you are looking for is _blank[2].

<a href="www.example.com/example.html" target="_blank">link text</a>

JavaScript option

Forcing a new window is possible via javascript - see Ievgen's excellent answer below for a javascript solution.

(!) However, be aware, that opening windows via javascript (if not done in the onclick event from an anchor element) are subject to getting blocked by popup blockers!

[1] This attribute dates back to the times when browsers did not have tabs and using framesets was state of the art. In the meantime, the functionality of this attribute has slightly changed (see MDN Docu)

[2] There are some other values which do not make much sense anymore (because they were designed with framesets in mind) like _parent, _self or _top.

Convert string to JSON array

Input String

[
   {
      "userName": "sandeep",
      "age": 30
   }, 
   {
      "userName": "vivan",
      "age": 5
   }
]

Simple Way to Convert String to JSON

public class Test
{

    public static void main(String[] args) throws JSONException
    {
        String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}]  ";
        JSONArray jsonArr = new JSONArray(data);

        for (int i = 0; i < jsonArr.length(); i++)
        {
            JSONObject jsonObj = jsonArr.getJSONObject(i);

            System.out.println(jsonObj);
        }

    }
}

Output

{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}

Suppress output of a function

The following function should do what you want exactly:

hush=function(code){
  sink("NUL") # use /dev/null in UNIX
  tmp = code
  sink()
  return(tmp)
}

For example with the function here:

foo=function(){
  print("BAR!")
  return(42)
}

running

x = hush(foo())

Will assign 42 to x but will not print "BAR!" to STDOUT

Note than in a UNIX OS you will need to replace "NUL" with "/dev/null"

Sort array of objects by single key with date value

  • Use Array.sort() to sort an array
  • Clone array using spread operator () to make the function pure
  • Sort by desired key (updated_at)
  • Convert date string to date object
  • Array.sort() works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operations
const input = [
  {
    updated_at: '2012-01-01T06:25:24Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-09T11:25:13Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-05T04:13:24Z',
    foo: 'bar',
  }
];

const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));

const output = sortByUpdatedAt(input);

console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/

How to get item count from DynamoDB?

You can use the Select parameter and use COUNT in the request. It "returns the number of matching items, rather than the matching items themselves". Important, as brought up by Saumitra R. Bhave in a comment, "If the size of the Query result set is larger than 1 MB, then ScannedCount and Count will represent only a partial count of the total items. You will need to perform multiple Query operations in order to retrieve all of the results".

I'm Not familiar with PHP but here is how you could use it with Java. And then instead of using Count (which I am guessing is a function in PHP) on the 'Items' you can use the Count value from the response - $result['Count']:

final String week = "whatever";
final Integer myPoint = 1337;
Condition weekCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.EQ)
        .withAttributeValueList(new AttributeValue().withS(week));
Condition myPointCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.GE)
        .withAttributeValueList(new AttributeValue().withN(myPoint.toString()))

Map<String, Condition> keyConditions = new HashMap<>();
keyConditions.put("week", weekCondition);
keyConditions.put("point", myPointCondition);

QueryRequest request = new QueryRequest("game_table");
request.setIndexName("week-point-index");
request.setSelect(Select.COUNT);
request.setKeyConditions(keyConditions);

QueryResult result = dynamoDBClient.query(request);
Integer count = result.getCount();

If you don't need to emulate the WHERE clause, you can use a DescribeTable request and use the resulting item count to get an estimate.

The number of items in the specified table. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.

Also, an important note from the documentation as noted by Saumitra R. Bhave in the comments on this answer:

If the size of the Query result set is larger than 1 MB, ScannedCount and Count represent only a partial count of the total items. You need to perform multiple Query operations to retrieve all the results (see Paginating Table Query Results).

How to play YouTube video in my Android application?

Use YouTube Android Player API.

activity_main.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.andreaskonstantakos.vfy.MainActivity">

<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="visible"
    android:layout_centerHorizontal="true"
    android:id="@+id/youtube_player"
    android:layout_alignParentTop="true" />

<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="195dp"
android:visibility="visible"
android:id="@+id/button" />


</RelativeLayout>

MainActivity.java:

package com.example.andreaskonstantakos.vfy;


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;



public class MainActivity extends YouTubeBaseActivity {

YouTubePlayerView youTubePlayerView;
Button button;
YouTubePlayer.OnInitializedListener onInitializedListener;

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

     youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
     button = (Button) findViewById(R.id.button);


     onInitializedListener = new YouTubePlayer.OnInitializedListener(){

         @Override
         public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

            youTubePlayer.loadVideo("Hce74cEAAaE");

             youTubePlayer.play();
     }

         @Override
         public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

         }
     };

    button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
        }
    });
}
}

and the PlayerConfig.java class:

    package com.example.andreaskonstantakos.vfy;

/**
 * Created by Andreas Konstantakos on 13/4/2017.
 */

public class PlayerConfig {

PlayerConfig(){}

public static final String API_KEY = 
"xxxxx";
}

Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk