Programs & Examples On #Nstextfieldcell

webpack: Module not found: Error: Can't resolve (with relative path)

If you use multiple node_modules (yarn workspace etc), tell webpack where they are:

  externals: [nodeExternals({
    modulesDir: path.resolve(__dirname, '../node_modules'),
  }),  nodeExternals()],

ProcessStartInfo hanging on "WaitForExit"? Why?

I was having the same issue, but the reason was different. It would however happen under Windows 8, but not under Windows 7. The following line seems to have caused the problem.

pProcess.StartInfo.UseShellExecute = False

The solution was to NOT disable UseShellExecute. I now received a Shell popup window, which is unwanted, but much better than the program waiting for nothing particular to happen. So I added the following work-around for that:

pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

Now the only thing bothering me is to why this is happening under Windows 8 in the first place.

fatal error LNK1169: one or more multiply defined symbols found in game programming

The two int variables are defined in the header file. This means that every source file which includes the header will contain their definition (header inclusion is purely textual). The of course leads to multiple definition errors.

You have several options to fix this.

  1. Make the variables static (static int WIDTH = 1024;). They will still exist in each source file, but their definitions will not be visible outside of the source file.

  2. Turn their definitions into declarations by using extern (extern int WIDTH;) and put the definition into one source file: int WIDTH = 1024;.

  3. Probably the best option: make the variables const (const int WIDTH = 1024;). This makes them static implicitly, and also allows them to be used as compile-time constants, allowing the compiler to use their value directly instead of issuing code to read it from the variable etc.

Get the difference between two dates both In Months and days in sql

Updated for correctness. Originally answered by @jen.

with DATES as (
   select TO_DATE('20120101', 'YYYYMMDD') as Date1,
          TO_DATE('20120325', 'YYYYMMDD') as Date2
   from DUAL union all
   select TO_DATE('20120101', 'YYYYMMDD') as Date1,
          TO_DATE('20130101', 'YYYYMMDD') as Date2
   from DUAL union all
   select TO_DATE('20120101', 'YYYYMMDD') as Date1,
          TO_DATE('20120101', 'YYYYMMDD') as Date2
   from DUAL union all
   select TO_DATE('20130228', 'YYYYMMDD') as Date1,
          TO_DATE('20130301', 'YYYYMMDD') as Date2
   from DUAL union all
   select TO_DATE('20130228', 'YYYYMMDD') as Date1,
          TO_DATE('20130401', 'YYYYMMDD') as Date2
   from DUAL
), MONTHS_BTW as (
   select Date1, Date2,
          MONTHS_BETWEEN(Date2, Date1) as NumOfMonths
   from DATES
)
select TO_CHAR(Date1, 'MON DD YYYY') as Date_1,
       TO_CHAR(Date2, 'MON DD YYYY') as Date_2,
       NumOfMonths as Num_Of_Months,
       TRUNC(NumOfMonths) as "Month(s)",
       ADD_MONTHS(Date2, - TRUNC(NumOfMonths)) - Date1 as "Day(s)"
from MONTHS_BTW;

SQLFiddle Demo :

    +--------------+--------------+-----------------+-----------+--------+
    |   DATE_1     |   DATE_2     | NUM_OF_MONTHS   | MONTH(S)  | DAY(S) |
    +--------------+--------------+-----------------+-----------+--------+
    | JAN 01 2012  | MAR 25 2012  | 2.774193548387  |        2  |     24 |
    | JAN 01 2012  | JAN 01 2013  | 12              |       12  |      0 |
    | JAN 01 2012  | JAN 01 2012  | 0               |        0  |      0 |
    | FEB 28 2013  | MAR 01 2013  | 0.129032258065  |        0  |      1 |
    | FEB 28 2013  | APR 01 2013  | 1.129032258065  |        1  |      1 |
    +--------------+--------------+-----------------+-----------+--------+

Notice, how for the last two dates, Oracle reports the decimal part of months (which gives days) incorrectly. 0.1290 corresponds to exactly 4 days with Oracle considering 31 days in a month (for both March and April).

Set default value of javascript object attributes

Or you can try this

dict = {
 'somekey': 'somevalue'
};

val = dict['anotherkey'] || 'anotherval';

How to create Drawable from resource

This code is deprecated:

Drawable drawable = getResources().getDrawable( R.drawable.icon );

Use this instead:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

align text center with android

Set also android:gravity parameter in TextView to center.

For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.

I am not able launch JNLP applications using "Java Web Start"?

In my case, the problem was caused by starting my app from a shortcut on the public desktop (windows 7). As a result, as far as I can tell, the temporary files location was set to c:\users\public\etc. This resulted in the unable to write to cache detail. When I reset to defaults in the temporary files control applet, all worked fine.

Raising a number to a power in Java

we can use

Math.pow(2, 4);

this mean 2 to the power 4 (2^4)

answer = 16

How do I horizontally center an absolute positioned element inside a 100% width div?

In my experience, the best way is right:0;, left:0; and margin:0 auto. This way if the div is wide then you aren't hindered by the left: 50%; that will offset your div which results in adding negative margins etc.

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

Where do I call the BatchNormalization function in Keras?

Keras now supports the use_bias=False option, so we can save some computation by writing like

model.add(Dense(64, use_bias=False))
model.add(BatchNormalization(axis=bn_axis))
model.add(Activation('tanh'))

or

model.add(Convolution2D(64, 3, 3, use_bias=False))
model.add(BatchNormalization(axis=bn_axis))
model.add(Activation('relu'))

Constant pointer vs Pointer to constant

Referncing from This Thread

Constant Pointers

Lets first understand what a constant pointer is. A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.

A constant pointer is declared as follows :
<type of pointer> * const <name of pointer>
An example declaration would look like :
int * const ptr;
Lets take a small code to illustrate these type of pointers :

#include<stdio.h>

int main(void)
{
    int var1 = 0, var2 = 0;
    int *const ptr = &var1;
    ptr = &var2;
    printf("%d\n", *ptr);

    return 0;
} 

In the above example :

  • We declared two variables var1 and var2
  • A constant pointer ‘ptr’ was declared and made to point var1
  • Next, ptr is made to point var2.
  • Finally, we try to print the value ptr is pointing to.

Pointer to Constant

As evident from the name, a pointer through which one cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value kept at those address.

A pointer to constant is defined as : const <type of pointer>* <name of pointer> An example of definition could be : const int* ptr; Lets take a small code to illustrate a pointer to a constant :

 #include<stdio.h>

int main(void)
{
    int var1 = 0;
    const int* ptr = &var1;
    *ptr = 1;
    printf("%d\n", *ptr);

    return 0;
} 

In the code above :

  • We defined a variable var1 with value 0
  • we defined a pointer to a constant which points to variable var1
  • Now, through this pointer we tried to change the value of var1
  • Used printf to print the new value.

Create Carriage Return in PHP String?

Fragment PHP (in console Cloud9):

echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";

resulting output:

  1: first_srt=1
  secnd_srt=2

  2: first_srt=1\nsecnd_srt=2\n
  ==============

Difference between 1 and 2: " versus '

How to combine 2 plots (ggplot) into one plot?

Just combine them. I think this should work but it's untested:

p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() + 
     geom_smooth(fill="blue", colour="darkblue", size=1)

p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) + 
     geom_smooth(data=visual2, fill="red", colour="red", size=1)

print(p)

How to initialize var?

A var cannot be set to null since it needs to be statically typed.

var foo = null;
// compiler goes: "Huh, what's that type of foo?"

However, you can use this construct to work around the issue:

var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."

I don't know for sure, but from what I heard you can also use dynamic instead of var. This does not require static typing.

dynamic foo = null;
foo = "hi";

Also, since it was not clear to me from the question if you meant the varkeyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:

string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable

But you cannot do this:

int i = null; // integers cannot contain null

How to convert a JSON string to a Map<String, String> with Jackson JSON

Using Google's Gson

Why not use Google's Gson as mentioned in here?

Very straight forward and did the job for me:

HashMap<String,String> map = new Gson().fromJson( yourJsonString, new TypeToken<HashMap<String, String>>(){}.getType());

Close virtual keyboard on button press

Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

What is the Difference Between Mercurial and Git?

I realize this isn't a part of the answer, but on that note, I also think the availability of stable plugins for platforms like NetBeans and Eclipse play a part in which tool is a better fit for the task, or rather, which tool is the best fit for "you". That is, unless you really want to do it the CLI-way.

Both Eclipse (and everything based on it) and NetBeans sometimes have issues with remote file systems (such as SSH) and external updates of files; which is yet another reason why you want whatever you choose to work "seamlessly".

I'm trying to answer this question for myself right now too .. and I've boiled down the candidates to Git or Mercurial .. thank you all for providing useful inputs on this topic without going religious.

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

The current accepted answer by crack is deprecated in Symfony 2.3 and will be removed by 3.0. It should be moved to the constructor:

public function __construct($environment, $debug) {
    date_default_timezone_set('Europe/Warsaw');
    parent::__construct($environment, $debug);
}

Bootstrap 3.0 Popovers and tooltips

I use this on all my pages to enable tooltip

$(function () { $("[data-toggle='tooltip']").tooltip(); });

Simple file write function in C++

This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters. This can be done by adding a "prototype". In your case this simply means adding before main the following line:

int writeFile();

this tells the compiler that there exist a function named writeFile that will be defined somewhere, that returns an int and that accepts no parameters.

Alternatively you can define first the function writeFile and then main because in this case when the compiler gets to main already knows your function.

Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...

struct Foo {
    void bar() {
        if (baz() != 99) {
            std::cout << "Hey!";
        }
    }

    int baz() {
        return 42;
    }
};

In this case the compiler has no problem analyzing the definition of bar even if it depends on a function baz that is declared later in the source code.

Jquery Hide table rows

Using parents('tr').hide() works. However if there is an embedded table, all parent tr rows will be hidden. In my case, the entire form is hidden since there are many embedded tables.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Note to anyone else:

If you have a directory like so, you can add a __main__.py file to tell the interpreter what to execute if you call the module directly.

my_module
  |
  | __init__.py
  | my_cool_file.py # print "Hello  World"
  | __main__.py # import my_cool_file

$ python my_module # Hello World

Display open transactions in MySQL

How can I display these open transactions and commit or cancel them?

There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).

You display threads using

SHOW FULL PROCESSLIST  

See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html

It will not help you, because you cannot commit a transaction from a broken connection.

What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html

4.5.1.6.3. Disabling mysql Auto-Reconnect

If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.

This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:

Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

How to diagnose and fix this
To check for auto-reconnection:

If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.

Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you want a table where only the columns scroll horizontally, you can position: absolute the first column (and specify its width explicitly), and then wrap the entire table in an overflow-x: scroll block. Don't bother trying this in IE7, however...

Relevant HTML & CSS:

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 0;_x000D_
  border-top: 1px solid grey;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
  margin: 0;_x000D_
  border: 1px solid grey;_x000D_
  white-space: nowrap;_x000D_
  border-top-width: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
  width: 500px;_x000D_
  overflow-x: scroll;_x000D_
  margin-left: 5em;_x000D_
  overflow-y: visible;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.headcol {_x000D_
  position: absolute;_x000D_
  width: 5em;_x000D_
  left: 0;_x000D_
  top: auto;_x000D_
  border-top-width: 1px;_x000D_
  /*only relevant for first row*/_x000D_
  margin-top: -1px;_x000D_
  /*compensate for top border*/_x000D_
}_x000D_
_x000D_
.headcol:before {_x000D_
  content: 'Row ';_x000D_
}_x000D_
_x000D_
.long {_x000D_
  background: yellow;_x000D_
  letter-spacing: 1em;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
        <tr><th class="headcol">1</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">2</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">3</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">4</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">5</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
        <tr><th class="headcol">6</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

How to update json file with python

The issue here is that you've opened a file and read its contents so the cursor is at the end of the file. By writing to the same file handle, you're essentially appending to the file.

The easiest solution would be to close the file after you've read it in, then reopen it for writing.

with open("replayScript.json", "r") as jsonFile:
    data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
    json.dump(data, jsonFile)

Alternatively, you can use seek() to move the cursor back to the beginning of the file then start writing, followed by a truncate() to deal with the case where the new data is smaller than the previous.

with open("replayScript.json", "r+") as jsonFile:
    data = json.load(jsonFile)

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()

Twitter Bootstrap Modal Form Submit

You can also cheat in some way by hidding a submit button on your form and triggering it when you click on your modal button.

Microsoft Excel mangles Diacritics in .csv files?

Echo UTF-8 BOM before outputing CSV data. This fixes all character issues in Windows but doesnt work for Mac.

echo "\xEF\xBB\xBF";

It works for me because I need to generate a file which will be used on Windows PCs only.

AngularJS - Trigger when radio button is selected

Should use ngChange instead of ngClick if trigger source is not from click.

Is the below what you want ? what exactly doesn't work in your case ?

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.value = "none" ;
    $scope.isChecked = false;
    $scope.checkStuff = function () {
        $scope.isChecked = !$scope.isChecked;
    }
}


<div ng-controller="MyCtrl">
    <input type="radio" ng-model="value" value="one" ng-change="checkStuff()" />
    <span> {{value}} isCheck:{{isChecked}} </span>
</div>   

Reading value from console, interactively

A common use case would probably be for the app to display a generic prompt and handle it in a switch statement.

You could get a behaviour equivalent to a while loop by using a helper function that would call itself in the callback:

const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);

function promptInput (prompt, handler)
{
    rl.question(prompt, input =>
    {
        if (handler(input) !== false)
        {
            promptInput(prompt, handler);
        }
        else
        {
            rl.close();
        }
    });
}

promptInput('app> ', input =>
{
    switch (input)
    {
        case 'my command':
            // handle this command
            break;
        case 'exit':
            console.log('Bye!');
            return false;
    }
});

You could pass an empty string instead of 'app> ' if your app already prints something to the screen outside of this loop.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

Following worked for me -

1) In Package.json add this:

"scripts": {
    "dev": "webpack-dev-server --progress --colors"
}

2) In webpack.config.js add this under config object that you export:

devServer: {
    host: "GACDTL001SS369k", // Your Computer Name
    port: 8080
}

3) Now on terminal type: npm run dev

4) After #3 compiles and ready just head over to your browser and key in address as http://GACDTL001SS369k:8080/

Your app should hopefully be working now with an external URL which others can access on the same network.

PS: GACDTL001SS369k was my Computer Name so do replace with whatever is yours on your machine.

Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.


Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

torch.save(the_model.state_dict(), PATH)

Then later:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

The second saves and loads the entire model:

torch.save(the_model, PATH)

Then later:

the_model = torch.load(PATH)

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

Selecting one row from MySQL using mysql_* API

use mysql_fetch_assoc to fetch the result at an associated array instead of mysql_fetch_array which returns a numeric indexed array.

Get JSON Data from URL Using Android?

I feel your frustration.

Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.

That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.

(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)

protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
{
    @Override
    protected JSONObject doInBackground(Void... params)
    {

        String str="http://your.domain.here/yourSubMethod";
        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(str);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuffer.append(line);
            }

            return new JSONObject(stringBuffer.toString());
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(JSONObject response)
    {
        if(response != null)
        {
            try {
                Log.e("App", "Success: " + response.getString("yourJsonElement") );
            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }
        }
    }
}

This would be the json object it is targeted towards.

{
    "yourJsonElement":"Hi, I'm a string",
    "anotherElement":"Ohh, why didn't you pick me"
}

It is working on my end, hope this is helpful to someone else out there.

How to make a parent div auto size to the width of its children divs

Your interior <div> elements should likely both be float:left. Divs size to 100% the size of their container width automatically. Try using display:inline-block instead of width:auto on the container div. Or possibly float:left the container and also apply overflow:auto. Depends on what you're after exactly.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to flush route table in windows?

route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.

Run php script as daemon process

If you can - grab a copy of Advanced Programming in the UNIX Environment. The entire chapter 13 is devoted to daemon programming. Examples are in C, but all the function you need have wrappers in PHP (basically the pcntl and posix extensions).

In a few words - writing a daemon (this is posible only on *nix based OS-es - Windows uses services) is like this:

  1. Call umask(0) to prevent permission issues.
  2. fork() and have the parent exit.
  3. Call setsid().
  4. Setup signal processing of SIGHUP (usually this is ignored or used to signal the daemon to reload its configuration) and SIGTERM (to tell the process to exit gracefully).
  5. fork() again and have the parent exit.
  6. Change the current working dir with chdir().
  7. fclose() stdin, stdout and stderr and don't write to them. The corrrect way is to redirect those to either /dev/null or a file, but I couldn't find a way to do it in PHP. It is possible when you launch the daemon to redirect them using the shell (you'll have to find out yourself how to do that, I don't know :).
  8. Do your work!

Also, since you are using PHP, be careful for cyclic references, since the PHP garbage collector, prior to PHP 5.3, has no way of collecting those references and the process will memory leak, until it eventually crashes.

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

nginx showing blank PHP pages

For reference, I am attaching my location block for catching files with the .php extension:

location ~ \.php$ {
    include /path/to/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}

Double-check the /path/to/fastcgi-params, and make sure that it is present and readable by the nginx user.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

If you are not using Maven, just drop the javax.servlet-api.jar in your project lib folder.

Passing a variable from node.js to html

To pass variables from node.js to html by using the res.render() method.

Example:

var bodyParser = require('body-parser');
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render('index.html',{email:data.email,password:data.password});
});

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

How can I resolve the error: "The command [...] exited with code 1"?

I know this is too late for sure, but, this could help someone as well.

In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).

Make sure that you can copy from the command prompt,

What is the C# equivalent of NaN or IsNumeric?

I have a slightly different version which returns the number. I would guess that in most cases after testing the string you would want to use the number.

public bool IsNumeric(string numericString, out Double numericValue)
{
    if (Double.TryParse(numericString, out numericValue))
        return true;
    else
        return false;
}

How to start anonymous thread class

Add: now you can use lambda to simplify your syntax. Requirement: Java 8+

public class A {
    public static void main(String[] arg)
    {
        Thread th = new Thread(() -> {System.out.println("blah");});
        th.start();
    }
}

Best way to verify string is empty or null

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

Can't ping a local VM from the host

Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the format specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s). try this. or more precisely

The Ant editor that ships with Eclipse can be used to reformat

XML/XHTML/HTML code (with a few configuration options in Window > Preferences > Ant > Editor).

You can right-click a file then

Open With... > Other... > Internal Editors > Ant Editor

Or add a file association between .html (or .xhtml) and that editor with

Window > Preferences > General > Editors > File Associations

Once open in the editor, hit ESC then CTRL-F to reformat.

How to pass object with NSNotificationCenter

Building on the solution provided I thought it might be helpful to show an example passing your own custom data object (which I've referenced here as 'message' as per question).

Class A (sender):

YourDataObject *message = [[YourDataObject alloc] init];
// set your message properties
NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];

Class B (receiver):

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
}

#pragma mark - Notification
-(void) triggerAction:(NSNotification *) notification
{
    NSDictionary *dict = notification.userInfo;
    YourDataObject *message = [dict valueForKey:@"message"];
    if (message != nil) {
        // do stuff here with your message data
    }
}

Date ticks and rotation in matplotlib

Another way to applyhorizontalalignment and rotation to each tick label is doing a for loop over the tick labels you want to change:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]
hours_value = np.random.random(len(hours))
days_value = np.random.random(len(days))

fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
axs[0].plot(hours,hours_value)
axs[1].plot(days,days_value)

for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
    label.set_rotation(30)
    label.set_horizontalalignment("right")

enter image description here

And here is an example if you want to control the location of major and minor ticks:

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

fig, axs = plt.subplots(2)
fig.subplots_adjust(hspace=0.75)
now = dt.datetime.now()
hours = [now + dt.timedelta(minutes=x) for x in range(0,24*60,10)]
days = [now + dt.timedelta(days=x) for x in np.arange(0,30,1/4.)]

axs[0].plot(hours,np.random.random(len(hours)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.HourLocator(byhour = range(0,25,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[0].xaxis.set_major_locator(x_major_lct)
axs[0].xaxis.set_minor_locator(x_minor_lct)
axs[0].xaxis.set_major_formatter(x_fmt)
axs[0].set_xlabel("minor ticks set to every hour, major ticks start with 00:00")

axs[1].plot(days,np.random.random(len(days)))
x_major_lct = mpl.dates.AutoDateLocator(minticks=2,maxticks=10, interval_multiples=True)
x_minor_lct = matplotlib.dates.DayLocator(bymonthday = range(0,32,1))
x_fmt = matplotlib.dates.AutoDateFormatter(x_major_lct)
axs[1].xaxis.set_major_locator(x_major_lct)
axs[1].xaxis.set_minor_locator(x_minor_lct)
axs[1].xaxis.set_major_formatter(x_fmt)
axs[1].set_xlabel("minor ticks set to every day, major ticks show first day of month")
for label in axs[0].get_xmajorticklabels() + axs[1].get_xmajorticklabels():
    label.set_rotation(30)
    label.set_horizontalalignment("right")

enter image description here

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

Quick trick-

SELECT CAST('<A><![CDATA[' + CAST(LogInfo as nvarchar(max)) + ']]></A>' AS xml)
FROM Logs
WHERE IDLog = 904862629

How to check if a MySQL query using the legacy API was successful?

You can use mysql_errno() for this too.

$result = mysql_query($query);

if(mysql_errno()){
    echo "MySQL error ".mysql_errno().": "
         .mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}

What is the difference between bool and Boolean types in C#

I realise this is many years later but I stumbled across this page from google with the same question.

There is one minor difference on the MSDN page as of now.

VS2005

Note:

If you require a Boolean variable that can also have a value of null, use bool. For more information, see Nullable Types (C# Programming Guide).

VS2010

Note:

If you require a Boolean variable that can also have a value of null, use bool?. For more information, see Nullable Types (C# Programming Guide).

Interface naming in Java

There is also another convention, used by many open source projects including Spring.

interface User {
}

class DefaultUser implements User {
}

class AnotherClassOfUser implements User {
}

I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

Ternary operator ?: vs if...else

Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.

Vertically align text next to an image?

This code works in IE as well as FF:

<div>
  <img style="width:auto; height:auto;vertical-align: middle;">
  <span>It does work on all browsers</span>
</div>

Pass Additional ViewData to a Strongly-Typed Partial View

This should also work.

this.ViewData.Add("index", index);

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       this.ViewData
); 

How to use the gecko executable with Selenium

You can handle the Firefox driver automatically using WebDriverManager.

This library downloads the proper binary (geckodriver) for your platform (Mac, Windows, Linux) and then exports the proper value of the required Java environment variable (webdriver.gecko.driver).

Take a look at a complete example as a JUnit test case:

public class FirefoxTest {

  private WebDriver driver;

  @BeforeClass
  public static void setupClass() {
    WebDriverManager.firefoxdriver().setup();
  }

  @Before
  public void setupTest() {
    driver = new FirefoxDriver();
  }

  @After
  public void teardown() {
    if (driver != null) {
      driver.quit();
    }
  }

  @Test
  public void test() {
    // Your test code here
  }
}

If you are using Maven you have to put at your pom.xml:

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>4.3.1</version>
</dependency>

WebDriverManager does magic for you:

  1. It checks for the latest version of the WebDriver binary
  2. It downloads the WebDriver binary if it's not present on your system
  3. It exports the required WebDriver Java environment variables needed by Selenium

So far, WebDriverManager supports Chrome, Opera, Internet Explorer, Microsoft Edge, PhantomJS, and Firefox.

How to hide a div after some time period?

setTimeout('$("#someDivId").hide()',1500);

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

How/when to generate Gradle wrapper files?

  1. You will generate them once, but update them if you need a new feature or something from a plugin which in turn needs a newer gradle version.

    Easiest way to update: as of Gradle 2.2 you can just download and extract the complete or binary Gradle distribution, and run:

    $ <pathToExpandedZip>/bin/gradle wrapper
    

    No need to define a task, though you probably need some kind of build.gradle file.

    This will update or create the gradlew and gradlew.bat wrapper as well as gradle/wrapper/gradle-wrapper.properties and the gradle-wrapper.jar to provide the current version of gradle, wrapped.

  2. Those are all part of the wrapper.

  3. Some build.gradle files reference other files or files in subdirectories which are sub projects or modules. It gets a bit complicated, but if you have one project you basically need the one file.

  4. settings.gradle handles project, module and other kinds of names and settings, gradle.properties configures resusable variables for your gradle files if you like and you feel they would be clearer that way.

How to pass data to all views in Laravel 5?

I found this to be the easiest one. Create a new provider and user the '*' wildcard to attach it to all views. Works in 5.3 as well :-)

<?php

namespace App\Providers;

use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function ($view)
        {
            $user = request()->user();

            $view->with('user', $user);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

How to prevent column break within an element?

I just fixed some divs that were splitting onto the next column by adding

overflow: auto

to the child divs.

*Realized it only fixes it in Firefox!

Align div with fixed position on the right side

Here's the real solution (with other cool CSS3 stuff):

#fixed-square {
position: fixed;
top: 0;
right: 0;
z-index: 9500;
cursor: pointer;
width: 24px;
padding: 18px 18px 14px;
opacity: 0.618;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-transition: all 0.145s ease-out;
-moz-transition: all 0.145s ease-out;
-ms-transition: all 0.145s ease-out;
transition: all 0.145s ease-out;
}

Note the top:0 and right:0. That's what did it for me.

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

How to execute my SQL query in CodeIgniter

$this->db->select('id, name, price, author, category, language, ISBN, publish_date');

       $this->db->from('tbl_books');

How to verify that a specific method was not called using Mockito?

As a more general pattern to follow, I tend to use an @After block in the test:

@After
public void after() {
    verifyNoMoreInteractions(<your mock1>, <your mock2>...);
}

Then the test is free to verify only what should be called.

Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.

So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.

Using JAXB to unmarshal/marshal a List<String>

Make sure to add @XmlSeeAlso tag with your specific classes used inside JaxbList. It is very important else it throws HttpMessageNotWritableException

How to deal with certificates using Selenium?

WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
driver = new ChromeDriver(options);

I have used it for Java with Chrome browser it is working nice

Redirection of standard and error output appending to the same log file

In order to append to a file you'll need to use a slightly different approach. You can still redirect an individual process' standard error and standard output to a file, but in order to append it to a file you'll need to do one of these things:

  1. Read the stdout/stderr file contents created by Start-Process
  2. Not use Start-Process and use the call operator, &
  3. Not use Start-Process and start the process with .NET objects

The first way would look like this:

$myLog = "C:\File.log"
$stdErrLog = "C:\stderr.log"
$stdOutLog = "C:\stdout.log"
Start-Process -File myjob.bat -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
Get-Content $stdErrLog, $stdOutLog | Out-File $myLog -Append

The second way would look like this:

& myjob.bat 2>&1 >> C:\MyLog.txt

Or this:

& myjob.bat 2>&1 | Out-File C:\MyLog.txt -Append

The third way:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "myjob.bat"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$output += $p.StandardError.ReadToEnd()
$output | Out-File $myLog -Append

Perl: function to trim string leading and trailing whitespace

This is available in String::Util with the trim method:

Editor's note: String::Util is not a core module, but you can install it from CPAN with [sudo] cpan String::Util.

use String::Util 'trim';
my $str = "  hello  ";
$str = trim($str);
print "string is now: '$str'\n";

prints:

string is now 'hello'

However it is easy enough to do yourself:

$str =~ s/^\s+//;
$str =~ s/\s+$//;

PostgreSQL database default location on Linux

I think best method is to query pg_setting view:

 select s.name, s.setting, s.short_desc from pg_settings s where s.name='data_directory';

Output:

      name      |        setting         |            short_desc
----------------+------------------------+-----------------------------------
 data_directory | /var/lib/pgsql/10/data | Sets the server's data directory.
(1 row)

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

There is a very easy work around for this problem.

If you run a 10046 trace on your session (google this... too much to explain). You will see that before any DDL operation Oracle does the following:

LOCK TABLE 'TABLE_NAME' NO WAIT

So if another session has an open transaction you get an error. So the fix is... drum roll please. Issue your own lock before the DDL and leave out the 'NO WAIT'.

Special Note:

if you are doing splitting/dropping partitions oracle just locks the partition. -- so yo can just lock the partition subpartition.

So... The following steps fix the problem.

  1. LOCK TABLE 'TABLE NAME'; -- you will 'wait' (developers call this hanging). until the session with the open transaction, commits. This is a queue. so there may be several sessions ahead of you. but you will NOT error out.
  2. Execute DDL. Your DDL will then run a lock with the NO WAIT. However, your session has aquired the lock. So you are good.
  3. DDL auto-commits. This frees the locks.

DML statements will 'wait' or as developers call it 'hang' while the table is locked.

I use this in code that runs from a job to drop partitions. It works fine. It is in a database that is constantly inserting at a rate of several hundred inserts/second. No errors.

if you are wondering. Doing this in 11g. I have done this in 10g before as well in the past.

Unable to find velocity template resources

you can try to add these code:

VelocityEngine ve = new VelocityEngine();
String vmPath = request.getSession().getServletContext().getRealPath("${your dir}");
Properties p = new Properties();
p.setProperty("file.resource.loader.path", vmPath+"//");
ve.init(p);

I do this, and pass!

Debugging in Maven?

Just as Brian said, you can use remote debugging:

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 com.mycompany.app.App"

Then in your eclipse, you can use remote debugging and attach the debugger to localhost:1044.

Clear and reset form input fields

The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks @Dan-Esparza for providing the links.

Also, please note that using string literals in ref is deprecated. Use the standard callback method instead.


Clearing a form with uncontrolled fields

You can clear the entire form rather than each form field individually.

cancelCourse = () => { 
  document.getElementById("create-course-form").reset();
}

render() {
  return (
    <form id="create-course-form">
      <input />
      <input />
      ...
      <input />
    </form>
  );
}

If your form didn't have an id attribute you could use a ref as well:

cancelCourse = () => { 
  this.myFormRef.reset();
}

render() {
  return (
    <form ref={(el) => this.myFormRef = el;}>
      <input />
      <input />
      ...
      <input />
    </form>
  );
}

Clearing a form with controlled fields

If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.

If they are declared individually, you need to reset each one explicitly:

cancelCourse = () => { 
  this.setState({
    inputVal_1: "",
    inputVal_2: "",
    ...
    inputVal_n: "",
  });
}

render() {
  return (
    <input value={this.state.inputVal_1} onChange={this.handleInput1Change}>
    <input value={this.state.inputVal_2} onChange={this.handleInput2Change}>
    ...
    <input value={this.state.inputVal_n} onChange={this.handleInputnChange}>
  );
}

Demo below:

_x000D_
_x000D_
class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      inputVal_1: "",
      inputVal_2: "",
      inputVal_3: "",
      inputVal_4: "",
      inputVal_5: "",
      inputVal_6: "",
      inputVal_7: "",
      inputVal_8: "",
      inputVal_9: "",
      inputVal_10: ""
    };
  }
  
  handleInput1Change = (e) => {
    this.setState({inputVal_1: e.target.value});
  }
  
  handleInput2Change = (e) => {
    this.setState({inputVal_2: e.target.value});
  }
  
  handleInput3Change = (e) => {
    this.setState({inputVal_3: e.target.value});
  }
  
  handleInput4Change = (e) => {
    this.setState({inputVal_4: e.target.value});
  }
  
  handleInput5Change = (e) => {
    this.setState({inputVal_5: e.target.value});
  }
  
  handleInput6Change = (e) => {
    this.setState({inputVal_6: e.target.value});
  }
  
  handleInput7Change = (e) => {
    this.setState({inputVal_7: e.target.value});
  }
  
  handleInput8Change = (e) => {
    this.setState({inputVal_8: e.target.value});
  }
  
  handleInput9Change = (e) => {
    this.setState({inputVal_9: e.target.value});
  }
  
  handleInput10Change = (e) => {
    this.setState({inputVal_10: e.target.value});
  }
  
  cancelCourse = () => { 
    this.setState({
      inputVal_1: "",
      inputVal_2: "",
      inputVal_3: "",
      inputVal_4: "",
      inputVal_5: "",
      inputVal_6: "",
      inputVal_7: "",
      inputVal_8: "",
      inputVal_9: "",
      inputVal_10: ""
    });
  }
  
  render() {
    return (
      <form>
        <input value={this.state.inputVal_1} onChange={this.handleInput1Change} />
        <input value={this.state.inputVal_2} onChange={this.handleInput2Change} />
        <input value={this.state.inputVal_3} onChange={this.handleInput3Change} />
        <input value={this.state.inputVal_4} onChange={this.handleInput4Change} />
        <input value={this.state.inputVal_5} onChange={this.handleInput5Change} />
        <input value={this.state.inputVal_6} onChange={this.handleInput6Change} />
        <input value={this.state.inputVal_7} onChange={this.handleInput7Change} />
        <input value={this.state.inputVal_8} onChange={this.handleInput8Change} />
        <input value={this.state.inputVal_9} onChange={this.handleInput9Change} />
        <input value={this.state.inputVal_10} onChange={this.handleInput10Change} />
        <input type="submit" name="saveCourse" value="Create" />
        <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
      </form>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
_x000D_
_x000D_
_x000D_

There is a cleaner way to do this though. Rather than having n state properties and n event handlers, one for each input, with some clever coding we can reduce the code dramatically.

In the constructor we just declare an empty object, which will be used to hold input values. We use only one input handler and pass it the index of the input element we want to change the value of. This means that the value of an individual input is generated the moment we start typing into it.

To reset the form, we only need to set our input object back to being empty again.

The input value is this.state.inputVal[i]. If i doesn't exist (we haven't typed anything yet into that input) we want the value to be an empty string (instead of null).

cancelCourse = () => { 
  this.setState({inputVal: {}});
}

render() {
  return (
    <form>
      {[...Array(n)].map(
        (item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />
      )}
    </form>
  );
}

Demo below:

_x000D_
_x000D_
class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      inputVal: {}
    };
  }
  
  handleInputChange = (idx, {target}) => {
    this.setState(({inputVal}) => {
      inputVal[idx] = target.value;
      return inputVal;
    });
  }
  
  cancelCourse = () => { 
    this.setState({inputVal: {}});
  }
  
  render() {
    return(
      <form>
        {[...Array(10)].map(  //create an array with a length of 10
          (item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />  //bind the index to the input handler
        )}
        <input type="submit" name="saveCourse" value="Create" />
        <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
      </form>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
_x000D_
_x000D_
_x000D_

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

How do you overcome the HTML form nesting limitation?

In response to a question posted by Yar in a comment to his own answer, I present some JavaScript which will resize an iframe. For the case of a form button, it is safe to assume the iframe will be on the same domain. This is the code I use. You will have to alter the maths/constants for your own site:

function resizeIFrame(frame)
{
    try {
        innerDoc = ('contentDocument' in frame) ? frame.contentDocument : frame.contentWindow.document;
        if('style' in frame) {
            frame.style.width = Math.min(755, Math.ceil(innerDoc.body.scrollWidth)) + 'px';
            frame.style.height = Math.ceil(innerDoc.body.scrollHeight) + 'px';
        } else {
            frame.width = Math.ceil(innerDoc.body.scrollWidth);
            frame.height = Math.ceil(innerDoc.body.scrollHeight);
        }
    } catch(err) {
        window.status = err.message;
    }
}

Then call it like this:

<iframe ... frameborder="0" onload="if(window.parent && window.parent.resizeIFrame){window.parent.resizeIFrame(this);}"></iframe>

WPF Label Foreground Color

The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:

<StackPanel>
    <Label Foreground="Red">Red text</Label>
    <Label Foreground="Blue">Blue text</Label>
</StackPanel>

In summary, No, there was nothing wrong with your snippet.

add item in array list of android

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;

look up ArrayAdapter.notifyDataSetChanged()

Find a file by name in Visual Studio Code

Press Ctl+T will open a search box. Delete # symbol and enter your file name.

Text in HTML Field to disappear when clicked?

How about something like this?

<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">

This will clear upon focusing the first time, but then won't clear on subsequent focuses after the user enters their value, when left blank it restores the given value.

Binding Listbox to List<object> in WinForms

You're looking for the DataSource property:

List<SomeType> someList = ...;
myListBox.DataSource = someList;

You should also set the DisplayMember property to the name of a property in the object that you want the listbox to display. If you don't, it will call ToString().

How to add an item to a drop down list in ASP.NET?

Try this, it will insert the list item at index 0;

DropDownList1.Items.Insert(0, new ListItem("Add New", ""));

javascript multiple OR conditions in IF statement

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

Reference to a non-shared member requires an object reference occurs when calling public sub

Go to the Declaration of the desired object and mark it Shared.

Friend Shared WithEvents MyGridCustomer As Janus.Windows.GridEX.GridEX

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

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

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

Fastest way to update 120 Million records

If you have the disk space, you could use SELECT INTO and create a new table. It's minimally logged, so it would go much faster

select t.*, int_field = CAST(-1 as int)
into mytable_new 
from mytable t

-- create your indexes and constraints

GO

exec sp_rename mytable, mytable_old
exec sp_rename mytable_new, mytable

drop table mytable_old

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

Don't drop, just take the rows where EPS is not NA:

df = df[df['EPS'].notna()]

Getting the Facebook like/share count for a given URL

As of August 8th, 2016, FQLs are deprecated.


Update 10/2017 (v2.10):

Here's a non-deprecated way to get a given URL's like and share count (no access token required):

https://graph.facebook.com/?fields=og_object{likes.summary(total_count).limit(0)},share&id=https://www.stackoverflow.com


Result:

{
   "og_object": {
      "likes": {
         "data": [

         ],
         "summary": {
            "total_count": 83
         }
      },
      "id": "10151023731873397"
   },
   "share": {
      "comment_count": 0,
      "share_count": 2915
   },
   "id": "https://www.stackoverflow.com"
}

JQuery Example:

$.get('https://graph.facebook.com/'
    + '?fields=og_object{likes.summary(total_count).limit(0)},share&id='
    + url-goes-here,
    function (data) {
        if (data) {
            var like_count = data.og_object.likes.summary.total_count;
            var share_count = data.share.share_count;
        }
    });

Reference:

https://developers.facebook.com/docs/graph-api/reference/url

How to change the type of a field?

What really helped me to change the type of the object in MondoDB was just this simple line, perhaps mentioned before here...:

db.Users.find({age: {$exists: true}}).forEach(function(obj) {
    obj.age = new NumberInt(obj.age);
    db.Users.save(obj);
});

Users are my collection and age is the object which had a string instead of an integer (int32).

Adding a custom header to HTTP request using angular.js

For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?

{
   headers: { 
      Authorization: "Basic " + getAuthDigest(), 
      Accept: "text/plain" 
   }
}

I'm using $http.ajax(), though I wouldn't expect that to be a game changer.

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

d = dict([(x,0) for x in a])

**edit Tim's solution is better because it uses generators see the comment to his answer.

Select all where [first letter starts with B]

Following your comment posted to ceejayoz's answer, two things are messed up a litte:

  1. $first is not an array, it's a string. Replace $first = $first[0] . "%" by $first .= "%". Just for simplicity. (PHP string operators)

  2. The string being compared with LIKE operator should be quoted. Replace LIKE ".$first."") by LIKE '".$first."'"). (MySQL String Comparison Functions)

How to fix 'Microsoft Excel cannot open or save any more documents'

Test like this.Sometimes, permission problem.

cmd => dcomcnfg

Click

Component services >Computes >My Computer>Dcom config> and select micro soft Excel Application

Right Click on microsoft Excel Application

Properties>Give Asp.net Permissions

Select Identity table >Select interactive user >select ok

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


Google Chrome cache file format description.

Cache files list, see URLs (copy and paste to your browser address bar):

  • chrome://cache/
  • chrome://view-http-cache/

Cache folder in Linux: $~/.cache/google-chrome/Default/Cache

Let's determine in file GZIP encoding:

$ head f84358af102b1064_0 | hexdump -C | grep --before-context=100 --after-context=5 "1f 8b 08"

Extract Chrome cache file by one line on PHP (without header, CRC32 and ISIZE block):

$ php -r "echo gzinflate(substr(strchr(file_get_contents('f84358af102b1064_0'), \"\x1f\x8b\x08\"), 10,
-8));"

How do I set response headers in Flask?

This was how added my headers in my flask application and it worked perfectly

@app.after_request
def add_header(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

Then you can do things like:

var day = moment("12-25-1995", "MM-DD-YYYY");

or

var day = moment("25/12/1995", "DD/MM/YYYY");

then operate on the date

day.add('days', 7)

and to get the native javascript date

day.toDate();

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Can scripts be inserted with innerHTML?

For anyone still trying to do this, no, you can't inject a script using innerHTML, but it is possible to load a string into a script tag using a Blob and URL.createObjectURL.

I've created an example that lets you run a string as a script and get the 'exports' of the script returned through a promise:

function loadScript(scriptContent, moduleId) {
    // create the script tag
    var scriptElement = document.createElement('SCRIPT');

    // create a promise which will resolve to the script's 'exports'
    // (i.e., the value returned by the script)
    var promise = new Promise(function(resolve) {
        scriptElement.onload = function() {
            var exports = window["__loadScript_exports_" + moduleId];
            delete window["__loadScript_exports_" + moduleId];
            resolve(exports);
        }
    });

    // wrap the script contents to expose exports through a special property
    // the promise will access the exports this way
    var wrappedScriptContent =
        "(function() { window['__loadScript_exports_" + moduleId + "'] = " + 
        scriptContent + "})()";

    // create a blob from the wrapped script content
    var scriptBlob = new Blob([wrappedScriptContent], {type: 'text/javascript'});

    // set the id attribute
    scriptElement.id = "__loadScript_module_" + moduleId;

    // set the src attribute to the blob's object url 
    // (this is the part that makes it work)
    scriptElement.src = URL.createObjectURL(scriptBlob);

    // append the script element
    document.body.appendChild(scriptElement);

    // return the promise, which will resolve to the script's exports
    return promise;
}

...

function doTheThing() {
    // no evals
    loadScript('5 + 5').then(function(exports) {
         // should log 10
        console.log(exports)
    });
}

I've simplified this from my actual implementation, so no promises that there aren't any bugs in it. But the principle works.

If you don't care about getting any value back after the script runs, it's even easier; just leave out the Promise and onload bits. You don't even need to wrap the script or create the global window.__load_script_exports_ property.

List of encodings that Node.js supports

The list of encodings that node supports natively is rather short:

  • ascii
  • base64
  • hex
  • ucs2/ucs-2/utf16le/utf-16le
  • utf8/utf-8
  • binary/latin1 (ISO8859-1, latin1 only in node 6.4.0+)

If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:

Use iconv-lite to recode files:

var iconvlite = require('iconv-lite');
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    return iconvlite.decode(content, encoding);
}

Alternatively, use iconv:

var Iconv = require('iconv').Iconv;
var fs = require('fs');

function readFileSync_encoding(filename, encoding) {
    var content = fs.readFileSync(filename);
    var iconv = new Iconv(encoding, 'UTF-8');
    var buffer = iconv.convert(content);
    return buffer.toString('utf8');
}

How to add a border to a widget in Flutter?

Using BoxDecoration() is the best way to show border.

Container(
  decoration: BoxDecoration(
    border: Border.all(
    color: Color(0xff000000),
    width: 4,
  )),
  child: //Your child widget
),

You can also view full format here

Using Java with Microsoft Visual Studio 2012

theoretically it could be done by defining a custom build step to the VS project. And you can make a file template to create a new java file, don't know if you could have it throw things in the right package or not, so you may end up writing quite a bit of the stuff a java ide would throw in already. it's not impossible, but from experience (I've used xcode on mac, vs in windows, eclipse, netbeans, code::blocks, and ended up compiling from command line for both java and c++ a lot) it's easier just to learn the new ide.

if you are insistent, i found this: http://improve.dk/compiling-java-in-visual-studio/

i plan on following and trying to modify it to create a general template for java

if possible (meaning if i understand enough of what im doing) im goint to implement a custom wizard for java projects and files.

Is there any sed like utility for cmd.exe?

Cygwin works, but these utilities are also available. Just plop them on your drive, put the directory into your path, and you have many of your friendly unix utilities. Lighterweight IMHO that Cygwin (although that works just as well).

Calling a function of a module by using its name (a string)

Assuming module foo with method bar:

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

You could shorten lines 2 and 3 to:

result = getattr(foo, 'bar')()

if that makes more sense for your use case.

You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.

How can I increase the JVM memory?

Right click on project -> Run As -> Run Configurations..-> Select Arguments tab -> In VM Arguments you can increase your JVM memory allocation. Java HotSpot document will help you to setup your VM Argument HERE

I will not prefer to make any changes into eclipse.ini as minor mistake cause lot of issues. It's easier to play with VM Args

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

Java: How to convert a File object to a String object in java?

Readin file with file inputstream and append file content to string.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CopyOffileInputStream {

    public static void main(String[] args) {

        //File file = new File("./store/robots.txt");
        File file = new File("swingloggingsscce.log");

        FileInputStream fis = null;
        String str = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                str += (char) content;
            }

            System.out.println("After reading file");
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

Go install fails with error: no install location for directory xxx outside GOPATH

You need to setup both GOPATH and GOBIN. Make sure you have done the following (please replace ~/go with your preferred GOPATH and subsequently change GOBIN). This is tested on Ubuntu 16.04 LTS.

export GOPATH=~/go 

mkdir ~/go/bin

export GOBIN=$GOPATH/bin

The selected answer did not solve the problem for me.

How to hide code from cells in ipython notebook visualized with nbviewer?

This is now possible directly from nbconvert as of version 5.2.1: content can be filtered using the built-in template exporter exclude options. For example:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

will exclude the "input code" cells, ie the code itself. Similar options exist to exclude prompts, markdown cells, or outputs, or both inputs and outputs.

(These options should work irrespective of output format.)

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'

Can Android do peer-to-peer ad-hoc networking?

Yes, but:
1. root your device (in case you've got Nexus S like me, see this)
2. install root explorer (search in market)
3. find appropriate wpa_supplcant file and replace (and backup) original as shown in this thread

above was tested on my Nexus S I9023 android 2.3.6

How to block calls in android

You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.

Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.

Evenly distributing n points on a sphere

# create uniform spiral grid
numOfPoints = varargin[0]
vxyz = zeros((numOfPoints,3),dtype=float)
sq0 = 0.00033333333**2
sq2 = 0.9999998**2
sumsq = 2*sq0 + sq2
vxyz[numOfPoints -1] = array([(sqrt(sq0/sumsq)), 
                              (sqrt(sq0/sumsq)), 
                              (-sqrt(sq2/sumsq))])
vxyz[0] = -vxyz[numOfPoints -1] 
phi2 = sqrt(5)*0.5 + 2.5
rootCnt = sqrt(numOfPoints)
prevLongitude = 0
for index in arange(1, (numOfPoints -1), 1, dtype=float):
  zInc = (2*index)/(numOfPoints) -1
  radius = sqrt(1-zInc**2)

  longitude = phi2/(rootCnt*radius)
  longitude = longitude + prevLongitude
  while (longitude > 2*pi): 
    longitude = longitude - 2*pi

  prevLongitude = longitude
  if (longitude > pi):
    longitude = longitude - 2*pi

  latitude = arccos(zInc) - pi/2
  vxyz[index] = array([ (cos(latitude) * cos(longitude)) ,
                        (cos(latitude) * sin(longitude)), 
                        sin(latitude)])

Best timestamp format for CSV/Excel?

As for timezones. I have to store the UTC offset as seconds from UTC that way formulas in Excel/OpenOffice can eventually localize datetimes. I found this to be easier than storing any number that has a 0 in front of it. -0900 didn't parse well in any spreadsheet system and importing it was nearly impossible to train people to do.

What tools do you use to test your public REST API?

We use Groovy and Spock for writing highly expressive BDD style tests. Unbeatable combo! Jersey Client API or HttpClient is used for handling the HTTP requests.

For manual/acceptance testing we use Curl or Chrome apps as Postman or Dev HTTP Client.

How to reset AUTO_INCREMENT in MySQL?

You need to follow the advice from Miles M comment and here is a little code that fixes the range in mysql. Also u need to open up my.ini(Mysql) and change max_execution_time=60 to max_execution_time=6000; for large databases. Dont use "ALTER TABLE tablename AUTO_INCREMENT = 1" it will delete everything in your database.

$con=mysqli_connect($dbhost, $dbuser, $dbpass, $database);
$res=mysqli_query($con, "select * FROM data WHERE id LIKE id ORDER BY id ASC");
$count = 0;  
while ($row = mysqli_fetch_array($res)){
         $count++;
        
    mysqli_query($con, "UPDATE data SET id='".$count."' WHERE id='".$row['id']."'");
    
         }
         echo 'Done reseting id';
         mysqli_close($con);

Difference between private, public, and protected inheritance

It's essentially the access protection of the public and protected members of the base class in the derived class. With public inheritance, the derived class can see public and protected members of the base. With private inheritance, it can't. With protected, the derived class and any classes derived from that can see them.

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You can try this solution :-

To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)

mysql -u root -p new_password

MySQLl access denied

In the Second link someone has commented the same problem.

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

Convert Int to String in Swift

Swift 2:

var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)

String comparison using '==' vs. 'strcmp()'

You can use strcmp() if you wish to order/compare strings lexicographically. If you just wish to check for equality then == is just fine.

How to get the path of the batch script in Windows?

%~dp0 will be the directory. Here's some documentation on all of the path modifiers. Fun stuff :-)

To remove the final backslash, you can use the :n,m substring syntax, like so:

SET mypath=%~dp0
echo %mypath:~0,-1%

I don't believe there's a way to combine the %0 syntax with the :~n,m syntax, unfortunately.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

I explain this to users by comparing Perforce changelists to a stack (from data structures).

Backing out removes one item from anywhere in the stack.

Rolling back removes n items from the top of the stack.

Java: method to get position of a match in a String?

The family of methods that does this are:

Returns the index within this string of the first (or last) occurrence of the specified substring [searching forward (or backward) starting at the specified index].


String text = "0123hello9012hello8901hello7890";
String word = "hello";

System.out.println(text.indexOf(word)); // prints "4"
System.out.println(text.lastIndexOf(word)); // prints "22"

// find all occurrences forward
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
    System.out.println(i);
} // prints "4", "13", "22"

// find all occurrences backward
for (int i = text.length(); (i = text.lastIndexOf(word, i - 1)) != -1; i++) {
    System.out.println(i);
} // prints "22", "13", "4"

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Return JSON response from Flask view

if its a dict, flask can return it directly (Version 1.0.2)

def summary():
    d = make_summary()
    return d, 200

In SQL, is UPDATE always faster than DELETE+INSERT?

Keep in mind the actual fragmentation that occurs when DELETE+INSERT is issued opposed to a correctly implemented UPDATE will make great difference by time.

Thats why, for instance, REPLACE INTO that MySQL implements is discouraged as opposed to using the INSERT INTO ... ON DUPLICATE KEY UPDATE ... syntax.

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

What is the difference between smoke testing and sanity testing?

Smoke Testing

  1. Smoke testing is a wide approach where all areas of the software application are tested without getting into too deep

  2. The test cases for smoke testing of the software can be either manual or automated

  3. Smoke testing is done to ensure whether the main functions of the software application are working or not. During smoke testing of the software, we do not go into finer details.

  4. Smoke testing of the software application is done to check whether the build can be accepted for through software testing

  5. This testing is performed by the developers or testers

  6. Smoke testing exercises the entire system from end to end

  7. Smoke testing is like General Health Check Up

  8. Smoke testing is usually documented or scripted

Santy Testing

  1. Sanity software testing is a narrow regression testing with a focus on one or a small set of areas of functionality of the software application.

  2. Sanity test is generally without test scripts or test cases.

  3. Sanity testing is a cursory software testing type. It is done whenever a quick round of software testing can prove that the software application is functioning according to business / functional requirements.

  4. Sanity testing of the software is to ensure whether the requirements are met or not.

  5. Sanity testing is usually performed by testers

  6. Sanity testing exercises only the particular component of the entire system

  7. Sanity Testing is like specialized health check up

  8. Sanity testing is usually not documented and is unscripted

For more visit Link

CRC32 C or C++ implementation

rurban's fork of SMHasher (the original SMHasher seems abandoned) has hardware CRC32 support. The changes were added before the initial commit, but try comparing the new CMakeLists.txt and the old one (which doesn't mention SSE at all).

The best option is probably Intel's zlib fork with PCLMULQDQ support described in this paper. This library also has the SSE 4.2 optimizations.

If you don't need portability and you're on Linux, you can use the kernel's implementation (which is hardware accelerated if available): https://stackoverflow.com/a/11156040/309483

How to download image from url

Most of the posts that I found will timeout after a second iteration. Particularly if you are looping through a bunch if images as I have been. So to improve the suggestions above here is the entire method:

public System.Drawing.Image DownloadImage(string imageUrl)
    {
        System.Drawing.Image image = null;

        try
        {
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Timeout = 30000;
            webRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
            webRequest.ServicePoint.MaxIdleTime = 5000;

            using (System.Net.WebResponse webResponse = webRequest.GetResponse())
            {

                using (System.IO.Stream stream = webResponse.GetResponseStream())
                {
                    image = System.Drawing.Image.FromStream(stream);
                }
            }

            webRequest.ServicePoint.CloseConnectionGroup(webRequest.ConnectionGroupName);
            webRequest = null; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);

        }


        return image;
    }

How to serialize an Object into a list of URL query parameters?

this method uses recursion to descend into object hierarchy and generate rails style params which rails interprets as embedded hashes. objToParams generates a query string with an extra ampersand on the end, and objToQuery removes the final amperseand.

 function objToQuery(obj){
  let str = objToParams(obj,'');
  return str.slice(0, str.length);
}
function   objToParams(obj, subobj){
  let str = "";

   for (let key in obj) {
     if(typeof(obj[key]) === 'object') {
       if(subobj){
         str += objToParams(obj[key], `${subobj}[${key}]`);
       } else {
         str += objToParams(obj[key], `[${key}]`);
       }

     } else {
       if(subobj){
         str += `${key}${subobj}=${obj[key]}&`;
       }else{
         str += `${key}=${obj[key]}&`;
       }
     }
   }
   return str;
 }

Android Button Onclick

There are two solutions for this are :-

(1) do not put onClick in xml

(2) remove

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
            // TODO Auto-generated method stub
    }
});

and put

public void setLogin(View v) {
    // Your code here
}

Check string for palindrome

Recently I wrote a palindrome program which doesn't use StringBuilder. A late answer but this might come in handy to some people.

public boolean isPalindrome(String value) {
    boolean isPalindrome = true;
    for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
        if (value.charAt(i) != value.charAt(j)) {
            isPalindrome = false;
        }
    }
    return isPalindrome;
}

Center text output from Graphics.DrawString()

Through a combination of the suggestions I got, I came up with this:

    private void DrawLetter()
    {
        Graphics g = this.CreateGraphics();

        float width = ((float)this.ClientRectangle.Width);
        float height = ((float)this.ClientRectangle.Width);

        float emSize = height;

        Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);

        font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);

        SizeF size = g.MeasureString(letter.ToString(), font);
        g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);

    }

    private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
    {
        // Compute actual size, shrink if needed
        while (true)
        {
            SizeF size = g.MeasureString(text, font);

            // It fits, back out
            if (size.Height <= proposedSize.Height &&
                 size.Width <= proposedSize.Width) { return font; }

            // Try a smaller font (90% of old size)
            Font oldFont = font;
            font = new Font(font.Name, (float)(font.Size * .9), font.Style);
            oldFont.Dispose();
        }
    }

So far, this works flawlessly.

The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness.

Laravel migration: unique key is too long, even if specified

Please open user and password rest files. files are located in database/migrations folder.

add line

Schema::defaultStringLength(191); in up function in both files.

Then run

php artisan migrate

How can I tell if a Java integer is null?

For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:

private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null ||     Integer.toString(greenIn) == null )

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

C# Lambda expressions: Why should I use them?

A lot of the times, you are only using the functionality in one place, so making a method just clutters up the class.

Using css transform property in jQuery

If you want to use a specific transform function, then all you need to do is include that function in the value. For example:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Secondly, browser support is getting better, but you'll probably still need to use vendor prefixes like so:

$('.user-text').css({
  '-webkit-transform' : 'scale(' + ui.value + ')',
  '-moz-transform'    : 'scale(' + ui.value + ')',
  '-ms-transform'     : 'scale(' + ui.value + ')',
  '-o-transform'      : 'scale(' + ui.value + ')',
  'transform'         : 'scale(' + ui.value + ')'
});

jsFiddle with example: http://jsfiddle.net/jehka/230/

Which equals operator (== vs ===) should be used in JavaScript comparisons?

If you are making a web application or a secured page you should always use (only when possible)

===

because it will will check if it is the same content and if it is the same type!

so when someone enters:

var check = 1;
if(check == '1') {
    //someone continued with a string instead of number, most of the time useless for your webapp, most of the time entered by a user who does not now what he is doing (this will sometimes let your app crash), or even worse it is a hacker searching for weaknesses in your webapp!
}

but with

var check = 1;
if(check === 1) {
    //some continued with a number (no string) for your script
} else {
    alert('please enter a real number');
}

a hacker will never get deeper in the system to find bugs and hack your app or your users

my point it is that the

===

will add more security to your scripts

of course you can also check if the entered number is valid, is a string, etc.. with other if statements inside the first example, but this is for at least me more easier to understand and use

The reason I posted this is that the word 'more secure' or 'security' has never been said in this conversation (if you look at iCloud.com it uses 2019 times === and 1308 times ==, this also means that you sometimes have the use == instead of === because it will otherwise block your function, but as said in the begin you should use === as much as possible)

Angular 2 TypeScript how to find element in Array

Use this code in your service:

return this.getReports(accessToken)
        .then(reports => reports.filter(report => report.id === id)[0]);

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

Why is setTimeout(fn, 0) sometimes useful?

Take a look at John Resig's article about How JavaScript Timers Work. When you set a timeout, it actually queues the asynchronous code until the engine executes the current call stack.

How to change the size of the font of a JLabel to take the maximum size

 JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");

What does "javascript:void(0)" mean?

A link must have an href target to be specified to enable it to be a usable display object.

Most browsers will not parse advanced JavaScript in the href of an <a> element, for example:

<a href="javascript:var el = document.getElementById('foo');">Get element</a>

Because the href tag in most browsers does not allow whitespace or will convert whitespace to %20 (the HEX code for space), the JavaScript interpreter will run into multiple errors.

So if you want to use an <a> element's href to execute inline JavaScript, you must specify a valid value for href first that isn't too complex (doesn't contain whitespace), and then provide the JavaScript in an event attribute tag like onClick, onMouseOver, onMouseOut, etc.

The typical answer is to do something like this:

<a href="#" onclick="var el = document.getElementById('foo');">Get element</a>

This works fine but it makes the page scroll to the top because the # in the href tells the browser to do this.

Placing a # in the <a> element's href specifies the root anchor, which is by default the top of the page, but you can specify a different location by specifying the name attribute inside an <a> element.

<a name="middleOfPage"></a>

You can then change your <a> element's href to jump to middleOfPage and execute the JavaScript in the onClick event:

<a href="#middleOfPage" onclick="var el = document.getElementById('foo');">Get element</a>

There will be many times where you do not want that link jumping around, so you can do two things:

<a href="#thisLinkName" name="thisLinkCame" onclick="var elem = document.getElementById('foo');">Get element</a>

Now it will go nowhere when clicked, but it could cause the page to re-centre itself from its current viewport.

The best way to use in-line javascript using an <a> element's href, but without having to do any of the above is JavaScript:void(0);:

<a href="javascript:void(0);" onclick="var el = document.getElementById('foo');">Get element</a>

This tells the browser no to go anywhere, but instead execute the JavaScript:void(0); function in the href because it contains no whitespace, and will not be parsed as a URL. It will instead be run by the compiler.

void is a keyword which, when supplied with a parameter of 0 returns undefined, which does not use any more resources to handle a return value that would occur without specifying the 0 (it is more memory-management/performance friendly).

The next thing that happens is the onClick gets executed. The page does not move, nothing happens display-wise.

Why doesn't the height of a container element increase if it contains floated elements?

The floated elements do not add to the height of the container element, and hence if you don't clear them, container height won't increase...

I'll show you visually:

enter image description here

enter image description here

enter image description here

More Explanation:

<div>
  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        besides the top div. Why? Because of the top div 
                                        is floated left, making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div from floating beside the top ones, 
       we use `clear: both;`. This is like a wall, so now none of the div's 
       will be floated after this point. The container height will now also include the 
       height of these floated divs -->
  <div></div>
</div>

You can also add overflow: hidden; on container elements, but I would suggest you use clear: both; instead.

Also if you might like to self-clear an element you can use

.self_clear:after {
  content: "";
  clear: both;
  display: table;
}

How Does CSS Float Work?

What is float exactly and what does it do?

  • The float property is misunderstood by most beginners. Well, what exactly does float do? Initially, the float property was introduced to flow text around images, which are floated left or right. Here's another explanation by @Madara Uchicha.

    So, is it wrong to use the float property for placing boxes side by side? The answer is no; there is no problem if you use the float property in order to set boxes side by side.

  • Floating an inline or block level element will make the element behave like an inline-block element.

    Demo

  • If you float an element left or right, the width of the element will be limited to the content it holds, unless width is defined explicitly ...

  • You cannot float an element center. This is the biggest issue I've always seen with beginners, using float: center;, which is not a valid value for the float property. float is generally used to float/move content to the very left or to the very right. There are only four valid values for float property i.e left, right, none (default) and inherit.

  • Parent element collapses, when it contains floated child elements, in order to prevent this, we use clear: both; property, to clear the floated elements on both the sides, which will prevent the collapsing of the parent element. For more information, you can refer my another answer here.

  • (Important) Think of it where we have a stack of various elements. When we use float: left; or float: right; the element moves above the stack by one. Hence the elements in the normal document flow will hide behind the floated elements because it is on stack level above the normal floated elements. (Please don't relate this to z-index as that is completely different.)


Taking a case as an example to explain how CSS floats work, assuming we need a simple 2 column layout with a header, footer, and 2 columns, so here is what the blueprint looks like...

enter image description here

In the above example, we will be floating only the red boxes, either you can float both to the left, or you can float on to left, and another to right as well, depends on the layout, if it's 3 columns, you may float 2 columns to left where another one to the right so depends, though in this example, we have a simplified 2 column layout so will float one to left and the other to the right.

Markup and styles for creating the layout explained further down...

<div class="main_wrap">
    <header>Header</header>
    <div class="wrapper clear">
        <div class="floated_left">
            This<br />
            is<br />
            just<br />
            a<br />
            left<br />
            floated<br />
            column<br />
        </div>
        <div class="floated_right">
            This<br />
            is<br />
            just<br />
            a<br />
            right<br />
            floated<br />
            column<br />
        </div>
    </div>
    <footer>Footer</footer>
</div>

* {
    -moz-box-sizing: border-box;       /* Just for demo purpose */
    -webkkit-box-sizing: border-box;   /* Just for demo purpose */
    box-sizing: border-box;            /* Just for demo purpose */
    margin: 0;
    padding: 0;
}

.main_wrap {
    margin: 20px;
    border: 3px solid black;
    width: 520px;
}

header, footer {
    height: 50px;
    border: 3px solid silver;
    text-align: center;
    line-height: 50px;
}

.wrapper {
    border: 3px solid green;
}

.floated_left {
    float: left;
    width: 200px;
    border: 3px solid red;
}

.floated_right {
    float: right;
    width: 300px;
    border: 3px solid red;
}

.clear:after {
    clear: both;
    content: "";
    display: table;
}

Let's go step by step with the layout and see how float works..

First of all, we use the main wrapper element, you can just assume that it's your viewport, then we use header and assign a height of 50px so nothing fancy there. It's just a normal non floated block level element which will take up 100% horizontal space unless it's floated or we assign inline-block to it.

The first valid value for float is left so in our example, we use float: left; for .floated_left, so we intend to float a block to the left of our container element.

Column floated to the left

And yes, if you see, the parent element, which is .wrapper is collapsed, the one you see with a green border didn't expand, but it should right? Will come back to that in a while, for now, we have got a column floated to left.

Coming to the second column, lets it float this one to the right

Another column floated to the right

Here, we have a 300px wide column which we float to the right, which will sit beside the first column as it's floated to the left, and since it's floated to the left, it created empty gutter to the right, and since there was ample of space on the right, our right floated element sat perfectly beside the left one.

Still, the parent element is collapsed, well, let's fix that now. There are many ways to prevent the parent element from getting collapsed.

  • Add an empty block level element and use clear: both; before the parent element ends, which holds floated elements, now this one is a cheap solution to clear your floating elements which will do the job for you but, I would recommend not to use this.

Add, <div style="clear: both;"></div> before the .wrapper div ends, like

<div class="wrapper clear">
    <!-- Floated columns -->
    <div style="clear: both;"></div>
</div>

Demo

Well, that fixes very well, no collapsed parent anymore, but it adds unnecessary markup to the DOM, so some suggest, to use overflow: hidden; on the parent element holding floated child elements which work as intended.

Use overflow: hidden; on .wrapper

.wrapper {
    border: 3px solid green;
    overflow: hidden;
}

Demo

That saves us an element every time we need to clear float but as I tested various cases with this, it failed in one particular one, which uses box-shadow on the child elements.

Demo (Can't see the shadow on all 4 sides, overflow: hidden; causes this issue)

So what now? Save an element, no overflow: hidden; so go for a clear fix hack, use the below snippet in your CSS, and just as you use overflow: hidden; for the parent element, call the class below on the parent element to self-clear.

.clear:after {
    clear: both;
    content: "";
    display: table;
}

<div class="wrapper clear">
    <!-- Floated Elements -->
</div>

Demo

Here, shadow works as intended, also, it self-clears the parent element which prevents to collapse.

And lastly, we use footer after we clear the floated elements.

Demo


When is float: none; used anyways, as it is the default, so any use to declare float: none;?

Well, it depends, if you are going for a responsive design, you will use this value a lot of times, when you want your floated elements to render one below another at a certain resolution. For that float: none; property plays an important role there.


Few real-world examples of how float is useful.

  • The first example we already saw is to create one or more than one column layouts.
  • Using img floated inside p which will enable our content to flow around.

Demo (Without floating img)

Demo 2 (img floated to the left)

  • Using float for creating horizontal menu - Demo

Float second element as well, or use `margin`

Last but not the least, I want to explain this particular case where you float only single element to the left but you do not float the other, so what happens?

Suppose if we remove float: right; from our .floated_right class, the div will be rendered from extreme left as it isn't floated.

Demo

So in this case, either you can float the to the left as well

OR

You can use margin-left which will be equal to the size of the left floated column i.e 200px wide.

Create an array or List of all dates between two dates

Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.

How to find length of dictionary values

d={1:'a',2:'b'}
sum=0
for i in range(0,len(d),1):
   sum=sum+1
i=i+1
print i

OUTPUT=2

Styling Form with Label above Inputs

I'd prefer not to use an HTML5 only element such as <section>. Also grouping the input fields might painful if you try to generate the form with code. It's always better to produce similar markup for each one and only change the class names. Therefore I would recommend a solution that looks like this :

CSS

label, input {
    display: block;
}
ul.form {
    width  : 500px;
    padding: 0px;
    margin : 0px;
    list-style-type: none;
}
ul.form li  {
    width : 500px;
}
ul.form li input {
    width : 200px;
}
ul.form li textarea {
    width : 450px;
    height: 150px;
}
ul.form li.twoColumnPart {
    float : left;
    width : 250px;
}

HTML

<form name="message" method="post">
    <ul class="form">
        <li class="twoColumnPart">
            <label for="name">Name</label>
            <input id="name" type="text" value="" name="name">
        </li>
        <li class="twoColumnPart">
            <label for="email">Email</label>
            <input id="email" type="text" value="" name="email">
        </li>
        <li>
            <label for="subject">Subject</label>
            <input id="subject" type="text" value="" name="subject">
        </li>
        <li>
            <label for="message">Message</label>
            <textarea id="message" type="text" name="message"></textarea>
        </li>
    </ul>
</form>

Change fill color on vector asset in Android Studio

Android studio now supports vectors pre-lollipop. No PNG conversion. You can still change your fill color and it will work.

In you ImageView, use

 app:srcCompat="@drawable/ic_more_vert_24dp"

In your gradle file,

 // Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'

Convert a Python list with strings all to lowercase or uppercase

A much simpler version of the top answer is given here by @Amorpheuses.

With a list of values in val:

valsLower = [item.lower() for item in vals]

This worked well for me with an f = open() text source.

Using BufferedReader.readLine() in a while loop properly

In case if you are still stumbling over this question. Nowadays things look nicer with Java 8:

try {
  Files.lines(Paths.get(targetsFile)).forEach(
    s -> {
      System.out.println(s);
      // do more stuff with s
    }
  );
} catch (IOException exc) {
  exc.printStackTrace();
}

C# Create New T()

Take a look at new Constraint

public class MyClass<T> where T : new()
{
    protected T GetObject()
    {
        return new T();
    }
}

T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

You can apply the same constraint to a generic method:

public static T GetObject<T>() where T : new()
{
    return new T();
}

If you need to pass parameters:

protected T GetObject(params object[] args)
{
    return (T)Activator.CreateInstance(typeof(T), args);
}

Convert audio files to mp3 using ffmpeg

You could use this command:

ffmpeg -i input.wav -vn -ar 44100 -ac 2 -b:a 192k output.mp3

Explanation of the used arguments in this example:

  • -i - input file

  • -vn - Disable video, to make sure no video (including album cover image) is included if the source would be a video file

  • -ar - Set the audio sampling frequency. For output streams it is set by default to the frequency of the corresponding input stream. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options.

  • -ac - Set the number of audio channels. For output streams it is set by default to the number of input audio channels. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options. So used here to make sure it is stereo (2 channels)

  • -b:a - Converts the audio bitrate to be exact 192kbit per second

Override element.style using CSS

Using !important will override element.style via CSS like Change

color: #7D7D7D;

to

color: #7D7D7D !important;

That should do it.

Convert String to Float in Swift

to convert string to Float in Xcode 11 as previous methods need modification

func stringToFloat(value : String) -> Float {
    let numberFormatter = NumberFormatter()
    let number = numberFormatter.number(from: value)
    let numberFloatValue = number?.floatValue
    return numberFloatValue!
}

add onclick function to a submit button

if you need to do something before submitting data, you could use form's onsubmit.

<form method=post onsubmit="return doSomething()">
  <input type=text name=text1>
  <input type=submit>
</form>

docker entrypoint running bash script gets "permission denied"

Dot [.]

This problem take with me more than 3 hours finally , I just tried the problem was in removing dot from the end just .

problem was

docker run  -p 3000:80 --rm --name test-con test-app .

/usr/local/bin/docker-entrypoint.sh: 8: exec: .: Permission denied

just remove dot from the end of your command line :

docker run  -p 3000:80 --rm --name test-con test-app 

Permutations in JavaScript?

  let permutations = []

  permutate([], {
    color: ['red', 'green'],
    size: ['big', 'small', 'medium'],
    type: ['saison', 'oldtimer']
  })

  function permutate (currentVals, remainingAttrs) {
    remainingAttrs[Object.keys(remainingAttrs)[0]].forEach(attrVal => {
      let currentValsNew = currentVals.slice(0)
      currentValsNew.push(attrVal)

      if (Object.keys(remainingAttrs).length > 1) {
        let remainingAttrsNew = JSON.parse(JSON.stringify(remainingAttrs))
        delete remainingAttrsNew[Object.keys(remainingAttrs)[0]]

        permutate(currentValsNew, remainingAttrsNew)
      } else {
        permutations.push(currentValsNew)
      }
    })
  }

Result:

[ 
  [ 'red', 'big', 'saison' ],
  [ 'red', 'big', 'oldtimer' ],
  [ 'red', 'small', 'saison' ],
  [ 'red', 'small', 'oldtimer' ],
  [ 'red', 'medium', 'saison' ],
  [ 'red', 'medium', 'oldtimer' ],
  [ 'green', 'big', 'saison' ],
  [ 'green', 'big', 'oldtimer' ],
  [ 'green', 'small', 'saison' ],
  [ 'green', 'small', 'oldtimer' ],
  [ 'green', 'medium', 'saison' ],
  [ 'green', 'medium', 'oldtimer' ] 
]

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

Mockito, JUnit and Spring

If you would migrate your project to Spring Boot 1.4, you could use new annotation @MockBean for faking MyDependentObject. With that feature you could remove Mockito's @Mock and @InjectMocks annotations from your test.

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

Parsing a CSV file using NodeJS

I used this way:-

var fs = require('fs'); 
var parse = require('csv-parse');

var csvData=[];
fs.createReadStream(req.file.path)
    .pipe(parse({delimiter: ':'}))
    .on('data', function(csvrow) {
        console.log(csvrow);
        //do something with csvrow
        csvData.push(csvrow);        
    })
    .on('end',function() {
      //do something with csvData
      console.log(csvData);
    });

Git merge error "commit is not possible because you have unmerged files"

If you have fixed the conflicts you need to add the files to the stage with git add [filename], then commit as normal.

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

For people who use Bootstrap, textarea.form-control can lead to textarea sizing issues as well. Chrome and Firefox appear to use different heights with the following Bootstrap CSS:

textarea.form-conrtol{
    height:auto;
}

How to compile a static library in Linux?

Generate the object files with gcc, then use ar to bundle them into a static library.

Copy multiple files in Python

Here is another example of a recursive copy function that lets you copy the contents of the directory (including sub-directories) one file at a time, which I used to solve this problem.

import os
import shutil

def recursive_copy(src, dest):
    """
    Copy each file from src dir to dest dir, including sub-directories.
    """
    for item in os.listdir(src):
        file_path = os.path.join(src, item)

        # if item is a file, copy it
        if os.path.isfile(file_path):
            shutil.copy(file_path, dest)

        # else if item is a folder, recurse 
        elif os.path.isdir(file_path):
            new_dest = os.path.join(dest, item)
            os.mkdir(new_dest)
            recursive_copy(file_path, new_dest)

EDIT: If you can, definitely just use shutil.copytree(src, dest). This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!

Is there a macro to conditionally copy rows to another worksheet?

This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.

You may want to add logic to sort your monthly data after it's all been copied

Public Sub MoveData(MonthNumber As Integer, SheetName As String)

Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range

Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
    If Format(cell.Value, "MM") = MonthNumber Then
        copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
    End If
Next cell

End Sub

Sub copyRowTo(rng As Range, ws As Worksheet)
    Dim newRange As Range
    Set newRange = ws.Range("A1")
    If newRange.Offset(1).Value <> "" Then
        Set newRange = newRange.End(xlDown).Offset(1)
        Else
        Set newRange = newRange.Offset(1)
    End If
    rng.Copy
    newRange.PasteSpecial (xlPasteAll)
End Sub

Make Https call using HttpClient

I had this issue and in my case the solution was stupidly simple: open Visual Studio with Administrator rights. I tried all the above solutions and it didn't work until I did this. Hope it saves someone some precious time.

Replace new line/return with space using regex

The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.

To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:

String inlinedText = text.replaceAll("\\R", " ");

Making Maven run all tests, even when some fail

I just found the "-fae" parameter, which causes Maven to run all tests and not stop on failure.

Laravel 5 – Clear Cache in Shared Hosting Server

As I can see: http://itsolutionstuff.com/post/laravel-5-clear-cache-from-route-view-config-and-all-cache-data-from-applicationexample.html

is it possible to use the code below with the new clear cache commands:

//Clear Cache facade value:
Route::get('/clear-cache', function() {
    $exitCode = Artisan::call('cache:clear');
    return '<h1>Cache facade value cleared</h1>';
});

//Reoptimized class loader:
Route::get('/optimize', function() {
    $exitCode = Artisan::call('optimize');
    return '<h1>Reoptimized class loader</h1>';
});

//Route cache:
Route::get('/route-cache', function() {
    $exitCode = Artisan::call('route:cache');
    return '<h1>Routes cached</h1>';
});

//Clear Route cache:
Route::get('/route-clear', function() {
    $exitCode = Artisan::call('route:clear');
    return '<h1>Route cache cleared</h1>';
});

//Clear View cache:
Route::get('/view-clear', function() {
    $exitCode = Artisan::call('view:clear');
    return '<h1>View cache cleared</h1>';
});

//Clear Config cache:
Route::get('/config-cache', function() {
    $exitCode = Artisan::call('config:cache');
    return '<h1>Clear Config cleared</h1>';
});

It's not necessary to give the possibility to clear the caches to everyone, especially in a production enviroment, so I suggest to comment that routes and, when it's needed, to de-comment the code and run the routes.

What's the difference between emulation and simulation?

I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.

For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.

How can I login to a website with Python?

Websites in general can check authorization in many different ways, but the one you're targeting seems to make it reasonably easy for you.

All you need is to POST to the auth/login URL a form-encoded blob with the various fields you see there (forget the labels for, they're decoration for human visitors). handle=whatever&password-clear=pwd and so on, as long as you know the values for the handle (AKA email) and password you should be fine.

Presumably that POST will redirect you to some "you've successfully logged in" page with a Set-Cookie header validating your session (be sure to save that cookie and send it back on further interaction along the session!).

How to change css property using javascript

Use document.getElementsByClassName('className').style = your_style.

var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";

Use single quotes for JS strings contained within an html attribute's double quotes

Example

<div class="somelclass"></div>

then document.getElementsByClassName('someclass').style = "NewclassName";

<div class='someclass'></div>

then document.getElementsByClassName("someclass").style = "NewclassName";

This is personal experience.

How to use fetch in typescript

A few examples follow, going from basic through to adding transformations after the request and/or error handling:

Basic:

// Implementation code where T is the returned data shape
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<T>()
    })

}

// Consumer
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Data transformations:

Often you may need to do some tweaks to the data before its passed to the consumer, for example, unwrapping a top level data attribute. This is straight forward:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => { /* <-- data inferred as { data: T }*/
      return data.data
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Error handling:

I'd argue that you shouldn't be directly error catching directly within this service, instead, just allowing it to bubble, but if you need to, you can do the following:

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json<{ data: T }>()
    })
    .then(data => {
      return data.data
    })
    .catch((error: Error) => {
      externalErrorLogging.error(error) /* <-- made up logging service */
      throw error /* <-- rethrow the error so consumer can still catch it */
    })
}

// Consumer - consumer remains the same
api<{ title: string; message: string }>('v1/posts/1')
  .then(({ title, message }) => {
    console.log(title, message)
  })
  .catch(error => {
    /* show error message */
  })

Edit

There has been some changes since writing this answer a while ago. As mentioned in the comments, response.json<T> is no longer valid. Not sure, couldn't find where it was removed.

For later releases, you can do:

// Standard variation
function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<T>
    })
}


// For the "unwrapping" variation

function api<T>(url: string): Promise<T> {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json() as Promise<{ data: T }>
    })
    .then(data => {
        return data.data
    })
}

Unable to cast object of type 'System.DBNull' to type 'System.String`

Convert it Like

string s = System.DBNull.value.ToString();

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

How to slice a Pandas Data Frame by position?

df.ix[10,:] gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive

Is it possible to put CSS @media rules inline?

If you are using Bootstrap Responsive Utilities or similar alternative that allows to hide / show divs depending on the break points, it may be possible to use several elements and show the most appropriate. i.e.

 <span class="hidden-xs" style="background: url(particular_ad.png)"></span>
 <span class="visible-xs" style="background: url(particular_ad_small.png)"></span>

Having services in React application

I am from Angular as well and trying out React, as of now, one recommended(?) way seems to be using High-Order Components:

A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

Let's say you have input and textarea and like to apply the same validation logic:

const Input = (props) => (
  <input type="text"
    style={props.style}
    onChange={props.onChange} />
)
const TextArea = (props) => (
  <textarea rows="3"
    style={props.style}
    onChange={props.onChange} >
  </textarea>
)

Then write a HOC that does validate and style wrapped component:

function withValidator(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props)

      this.validateAndStyle = this.validateAndStyle.bind(this)
      this.state = {
        style: {}
      }
    }

    validateAndStyle(e) {
      const value = e.target.value
      const valid = value && value.length > 3 // shared logic here
      const style = valid ? {} : { border: '2px solid red' }
      console.log(value, valid)
      this.setState({
        style: style
      })
    }

    render() {
      return <WrappedComponent
        onChange={this.validateAndStyle}
        style={this.state.style}
        {...this.props} />
    }
  }
}

Now those HOCs share the same validating behavior:

const InputWithValidator = withValidator(Input)
const TextAreaWithValidator = withValidator(TextArea)

render((
  <div>
    <InputWithValidator />
    <TextAreaWithValidator />
  </div>
), document.getElementById('root'));

I created a simple demo.

Edit: Another demo is using props to pass an array of functions so that you can share logic composed by multiple validating functions across HOCs like:

<InputWithValidator validators={[validator1,validator2]} />
<TextAreaWithValidator validators={[validator1,validator2]} />

Edit2: React 16.8+ provides a new feature, Hook, another nice way to share logic.

const Input = (props) => {
  const inputValidation = useInputValidation()

  return (
    <input type="text"
    {...inputValidation} />
  )
}

function useInputValidation() {
  const [value, setValue] = useState('')
  const [style, setStyle] = useState({})

  function handleChange(e) {
    const value = e.target.value
    setValue(value)
    const valid = value && value.length > 3 // shared logic here
    const style = valid ? {} : { border: '2px solid red' }
    console.log(value, valid)
    setStyle(style)
  }

  return {
    value,
    style,
    onChange: handleChange
  }
}

https://stackblitz.com/edit/react-shared-validation-logic-using-hook?file=index.js

Check if string is in a pandas dataframe

If there is any chance that you will need to search for empty strings,

    a['Names'].str.contains('') 

will NOT work, as it will always return True.

Instead, use

    if '' in a["Names"].values

to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

Error: Argument is not a function, got undefined

Remove the [] from the name ([myApp]) of module

angular.module('myApp', [])

And add ng-app="myApp" to the html and it should work.

How to create a self-signed certificate for a domain name for development?

Another easy way to generate a self signed certificate is to use Jexus Manager,

Jexus Manager

  1. Choose a server node in the Connections panel.
  2. In the middle panel, click Server Certificates icon to open the management page.
  3. Under Actions panel, click “Generate Self-Signed Certificate...” menu item.

https://www.jexusmanager.com/en/latest/tutorials/self-signed.html