Programs & Examples On #Hyphenation

No line-break after a hyphen

IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.

As I could not use the CSS answer specified by Deb I instead opted to use no break tags.

<nobr>e-mail</nobr>

In addition I found a specific scenario that caused IE8/9 to break on a hyphen.

  • A string contains words separated by non-breaking spaces - &nbsp;
  • Width is limited
  • Contains a dash

IE renders it like this.

Example of hyphen breaking in IE8/9

The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=9" />
        <meta charset="utf-8"/>
        <style>
            body { padding: 20px; }
            div { width: 300px; border: 1px solid gray; }
        </style>
    </head>
    <body>
        <div>      
            <p>If&nbsp;there&nbsp;is&nbsp;a&nbsp;-&nbsp;and&nbsp;words&nbsp;are&nbsp;separated&nbsp;by&nbsp;the&nbsp;whitespace&nbsp;code&nbsp;&amp;nbsp;&nbsp;then&nbsp;IE&nbsp;will&nbsp;wrap&nbsp;on&nbsp;the&nbsp;dash.</p>
        </div>
    </body>
</html>

How do I get LaTeX to hyphenate a word that contains a dash?

I answered something similar here: LaTeX breaking up too many words

I said:

you should set a hyphenation penalty somewhere in your preamble:

\hyphenpenalty=750

The value of 750 suited my needs for a two column layout on letter paper (8.5x11 in) with a 12 pt font. Adjust the value to suit your needs. The higher the number, the less hyphenation will occur. You may also want to have a look at the hyphenatpackage, it provides a bit more than just hyphenation penalty

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

django admin - add custom form fields that are not part of the model

It it possible to do in the admin, but there is not a very straightforward way to it. Also, I would like to advice to keep most business logic in your models, so you won't be dependent on the Django Admin.

Maybe it would be easier (and maybe even better) if you have the two seperate fields on your model. Then add a method on your model that combines them.

For example:

class MyModel(models.model):

    field1 = models.CharField(max_length=10)
    field2 = models.CharField(max_length=10)

    def combined_fields(self):
        return '{} {}'.format(self.field1, self.field2)

Then in the admin you can add the combined_fields() as a readonly field:

class MyModelAdmin(models.ModelAdmin):

    list_display = ('field1', 'field2', 'combined_fields')
    readonly_fields = ('combined_fields',)

    def combined_fields(self, obj):
        return obj.combined_fields()

If you want to store the combined_fields in the database you could also save it when you save the model:

def save(self, *args, **kwargs):
    self.field3 = self.combined_fields()
    super(MyModel, self).save(*args, **kwargs)

Removing items from a ListBox in VB.net

There is a simple method for deleting selected items, and all these people are going for a hard method:

lstYOURVARIABLE.Items.Remove(lstYOURVARIABLE.SelectedItem)

I used this in Visual Basic mode on Visual Studio.

Vue 'export default' vs 'new Vue'

Whenever you use

export someobject

and someobject is

{
 "prop1":"Property1",
 "prop2":"Property2",
}

the above you can import anywhere using import or module.js and there you can use someobject. This is not a restriction that someobject will be an object only it can be a function too, a class or an object.

When you say

new Object()

like you said

new Vue({
  el: '#app',
  data: []
)}

Here you are initiating an object of class Vue.

I hope my answer explains your query in general and more explicitly.

How I can delete in VIM all text from current line to end of file?

Go to the first line from which you would like to delete, and press the keys dG

How to validate numeric values which may contain dots or commas?

In order to represent a single digit in the form of a regular expression you can use either:

[0-9] or \d

In order to specify how many times the number appears you would add

[0-9]*: the star means there are zero or more digits

[0-9]{2}: {N} means N digits

[0-9]{0,2}: {N,M} N digits or M digits

[0-9]{0-9}: {N-M} N digits to M digits. Note: M can be left blank for an infinite representation

Lets say I want to represent a number between 1 and 99 I would express it as such:

[0-9]{1-2} or [0-9]{1,2} or \d{1-2} or \d{1,2}

Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:

[0-1]{8} representation of a binary byte

Then if you want to add a , or a . symbol you would use:

\, or \. or you can use [.] or [,]

You can also state a selection between possible values as such

[.,] means either a dot or a comma symbol

And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows: >

[0-9]{1,2}[.,]\d{1-2}

Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\

How do I work with dynamic multi-dimensional arrays in C?

int rows, columns;
/* initialize rows and columns to the desired value */

    arr = (int**)malloc(rows*sizeof(int*));
        for(i=0;i<rows;i++)
        {
            arr[i] = (int*)malloc(cols*sizeof(int));
        }

Timing Delays in VBA

If you are in Excel VBA you can use the following.

Application.Wait(Now + TimeValue("0:00:01"))

(The time string should look like H:MM:SS.)

Why are only a few video games written in Java?

Runescape by Jagex is written in Java, the "video game" tag might not specifically apply it being an on-line game, but it does have a decent following.

Asynchronously wait for Task<T> to complete with timeout

I'm recombinging the ideas of some other answers here and this answer on another thread into a Try-style extension method. This has a benefit if you want an extension method, yet avoiding an exception upon timeout.

public static async Task<bool> TryWithTimeoutAfter<TResult>(this Task<TResult> task,
    TimeSpan timeout, Action<TResult> successor)
{

    using var timeoutCancellationTokenSource = new CancellationTokenSource();
    var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token))
                                  .ConfigureAwait(continueOnCapturedContext: false);

    if (completedTask == task)
    {
        timeoutCancellationTokenSource.Cancel();

        // propagate exception rather than AggregateException, if calling task.Result.
        var result = await task.ConfigureAwait(continueOnCapturedContext: false);
        successor(result);
        return true;
    }
    else return false;        
}     

async Task Example(Task<string> task)
{
    string result = null;
    if (await task.TryWithTimeoutAfter(TimeSpan.FromSeconds(1), r => result = r))
    {
        Console.WriteLine(result);
    }
}    

Why can't Python import Image from PIL?

I had the same issue, and did this to fix it:

  1. In command prompt

    pip install Pillow ##
    
  2. Ensure that you use

    from PIL import Image
    

I in Image has to be capital. That was the issue in my case.

How to create a new schema/new user in Oracle Database 11g?

From oracle Sql developer, execute the below in sql worksheet:

create user lctest identified by lctest;
grant dba to lctest;

then right click on "Oracle connection" -> new connection, then make everything lctest from connection name to user name password. Test connection shall pass. Then after connected you will see the schema.

jQuery load more data on scroll

I spent some time trying to find a nice function to wrap a solution. Anyway, ended up with this which I feel is a better solutions when loading multiple content on a single page or across a site.

Function:

function ifViewLoadContent(elem, LoadContent)
    {
            var top_of_element = $(elem).offset().top;
            var bottom_of_element = $(elem).offset().top + $(elem).outerHeight();
            var bottom_of_screen = $(window).scrollTop() + window.innerHeight;
            var top_of_screen = $(window).scrollTop();

            if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
            if(!$(elem).hasClass("ImLoaded"))   {
                $(elem).load(LoadContent).addClass("ImLoaded");
            }
            }
            else {
               return false;
            }
        }

You can then call the function using window on scroll (for example, you could also bind it to a click etc. as I also do, hence the function):

To use:

$(window).scroll(function (event) {
        ifViewLoadContent("#AjaxDivOne", "someFile/somecontent.html"); 

        ifViewLoadContent("#AjaxDivTwo", "someFile/somemorecontent.html"); 
    });

This approach should also work for scrolling divs etc. I hope it helps, in the question above you could use this approach to load your content in sections, maybe append and thereby dribble feed all that image data rather than bulk feed.

I used this approach to reduce the overhead on https://www.taxformcalculator.com. It died the trick, if you look at the site and inspect element etc. you can see impact on page load in Chrome (as an example).

Performing Breadth First Search recursively

If you use an array to back the binary tree, you can determine the next node algebraically. if i is a node, then its children can be found at 2i + 1 (for the left node) and 2i + 2 (for the right node). A node's next neighbor is given by i + 1, unless i is a power of 2

Here's pseudocode for a very naive implementation of breadth first search on an array backed binary search tree. This assumes a fixed size array and therefore a fixed depth tree. It will look at parentless nodes, and could create an unmanageably large stack.

bintree-bfs(bintree, elt, i)
    if (i == LENGTH)
        return false

    else if (bintree[i] == elt)
        return true

    else 
        return bintree-bfs(bintree, elt, i+1)        

How do I choose grid and block dimensions for CUDA kernels?

The blocksize is usually selected to maximize the "occupancy". Search on CUDA Occupancy for more information. In particular, see the CUDA Occupancy Calculator spreadsheet.

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.

Changing the version in the pom.xml should fix the problem

Python urllib2, basic HTTP authentication, and tr.im

Same solutions as Python urllib2 Basic Auth Problem apply.

see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler to add the Authorization header to each request that matches the known url.

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

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'

Assign keyboard shortcut to run procedure

F5 is a standard shortcut to run a macro in VBA editor. I don't think you can add a shortcut key in editor itself. If you want to run the macro from excel, you can assign a shortcut from there.

In excel press alt+F8 to open macro dialog box. select the macro for which you want to assign shortcut key and click options. there you can assign a shortcut to the macro.

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

Restoring Nuget References?

This script will reinstall all packages of a project without messing up dependencies or installing dependencies that may have been intentianlyz removed. (More for their part package developers.)

Update-Package -Reinstall -ProjectName Proteus.Package.LinkedContent -IgnoreDependencies

How to open an external file from HTML

If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.

You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

Set attribute without value

The accepted answer doesn't create a name-only attribute anymore (as of September 2017).

You should use JQuery prop() method to create name-only attributes.

$(body).prop('data-body', true)

What is log4j's default log file dumping path

You have copy this sample code from Here,right?
now, as you can see there property file they have define, have you done same thing? if not then add below code in your project with property file for log4j

So the content of log4j.properties file would be as follows:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

make changes as per your requirement like log path

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

How can I fix "Design editor is unavailable until a successful build" error?

Go online before starting android studio. Then go file->New project Follow onscreen steps. Then wait It will download the necessary files over internet. And that should fix it.

How to run composer from anywhere?

You can do a simple global install to run it from anywhere

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

The https://getcomposer.org/doc/00-intro.md#globally website recommends this way. Worked well on Ubuntu 14.04 no problem. This way you don't need to do as an example php compomser.phar show , you just do composer show , in any directory you are working with.

How to define a variable in a Dockerfile?

Late to the party, but if you don't want to expose environment variables, I guess it's easier to do something like this:

RUN echo 1 > /tmp/__var_1
RUN echo `cat /tmp/__var_1`
RUN rm -f /tmp/__var_1

I ended up doing it because we host private npm packages in aws codeartifact:

RUN aws codeartifact get-authorization-token --output text > /tmp/codeartifact.token
RUN npm config set //company-123456.d.codeartifact.us-east-2.amazonaws.com/npm/internal/:_authToken=`cat /tmp/codeartifact.token`
RUN rm -f /tmp/codeartifact.token

And here ARG cannot work and i don't want to use ENV because i don't want to expose this token to anything else

Node.js https pem error: routines:PEM_read_bio:no start line

I faced with the problem like this.

The problem was that I added the public key without '-----BEGIN PUBLIC KEY-----' at the beginning and without '-----END PUBLIC KEY-----'.

So it causes the error.

Initially, my public key was like this:

-----BEGIN PUBLIC KEY-----
WnsbGUXbb0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2wKKyRdcROK7ZTSCSMsJpAFOY
-----END PUBLIC KEY-----

But I used just this part:

WnsbGUXb+b0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2w+KKyRdcROK7ZTSCSMsJpAFOY

Moment JS start and end of given month

var d = new moment();
var startMonth = d.clone().startOf('month');
var endMonth = d.clone().endOf('month');
console.log(startMonth, endMonth);

doc

How do I select an element with its name attribute in jQuery?

it's very simple getting a name:

$('[name=elementname]');

Resource:

http://www.electrictoolbox.com/jquery-form-elements-by-name/ (google search: get element by name jQuery - first result)

Excel to JSON javascript code?

NOTE: Not 100% Cross Browser

Check browser compatibility @ http://caniuse.com/#search=FileReader

as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..

The Fiddle: http://jsfiddle.net/d2atnbrt/3/

THE HTML CODE:

<input type="file" id="my_file_input" />
<div id='my_file_output'></div>

THE JS CODE:

var oFileIn;

$(function() {
    oFileIn = document.getElementById('my_file_input');
    if(oFileIn.addEventListener) {
        oFileIn.addEventListener('change', filePicked, false);
    }
});


function filePicked(oEvent) {
    // Get The File From The Input
    var oFile = oEvent.target.files[0];
    var sFilename = oFile.name;
    // Create A File Reader HTML5
    var reader = new FileReader();

    // Ready The Event For When A File Gets Selected
    reader.onload = function(e) {
        var data = e.target.result;
        var cfb = XLS.CFB.read(data, {type: 'binary'});
        var wb = XLS.parse_xlscfb(cfb);
        // Loop Over Each Sheet
        wb.SheetNames.forEach(function(sheetName) {
            // Obtain The Current Row As CSV
            var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);   
            var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);   

            $("#my_file_output").html(sCSV);
            console.log(oJS)
        });
    };

    // Tell JS To Start Reading The File.. You could delay this if desired
    reader.readAsBinaryString(oFile);
}

This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed

This is as basic as i could get it,

EDIT - Generating A Table

The Fiddle: http://jsfiddle.net/d2atnbrt/5/

This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..

One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least

Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls

This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.

How to output only captured groups with sed?

you can use grep

grep -Eow "[0-9]+" file

How to do INSERT into a table records extracted from another table

You have two syntax options:

Option 1

CREATE TABLE Table1 (
    id int identity(1, 1) not null,
    LongIntColumn1 int,
    CurrencyColumn money
)

CREATE TABLE Table2 (
    id int identity(1, 1) not null,
    LongIntColumn2 int,
    CurrencyColumn2 money
)

INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)

INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1

Option 2

CREATE TABLE Table1 (
    id int identity(1, 1) not null,
    LongIntColumn1 int,
    CurrencyColumn money
)

INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)


SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1

Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).

Create Directory When Writing To File In Node.js

Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-frança fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:

function mkdirp(filepath) {
    var dirname = path.dirname(filepath);

    if (!fs.existsSync(dirname)) {
        mkdirp(dirname);
    }

    fs.mkdirSync(filepath);
}

What do the crossed style properties in Google Chrome devtools mean?

If you want to apply the style even after getting struck-trough indication, you can use "!important" to enforce the style. It may not be a right solution but solve the problem.

How to remove leading and trailing whitespace in a MySQL field?

You're looking for TRIM.

UPDATE FOO set FIELD2 = TRIM(FIELD2);

Seems like it might be worth it to mention that TRIM can support multiple types of whitespace, but only one at a time and it will use a space by default. You can, however, nest TRIMs.

 TRIM(BOTH ' ' FROM TRIM(BOTH '\n' FROM column))

If you really want to get rid of all the whitespace in one call, you're better off using REGEXP_REPLACE along with the [[:space:]] notation. Here is an example:

SELECT 
    -- using concat to show that the whitespace is actually removed.
    CONCAT(
         '+', 
         REGEXP_REPLACE(
             '    ha ppy    ', 
             -- This regexp matches 1 or more spaces at the beginning with ^[[:space:]]+
             -- And 1 or more spaces at the end with [[:space:]]+$
             -- By grouping them with `()` and splitting them with the `|`
             -- we match all of the expected values.
             '(^[[:space:]]+|[[:space:]]+$)', 

             -- Replace the above with nothing
             ''
         ), 
         '+') 
    as my_example;
-- outputs +ha ppy+

Python creating a dictionary of lists

You can build it with list comprehension like this:

>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}

And for the second part of your question use defaultdict

>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
        d[k].append(v)

>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

How to check the extension of a filename in a bash script?

I think you want to say "Are the last four characters of $file equal to .txt?" If so, you can use the following:

if [ ${file: -4} == ".txt" ]

Note that the space between file: and -4 is required, as the ':-' modifier means something different.

How to pass arguments to a Button command in Tkinter?

Example GUI:

Let's say I have the GUI:

import tkinter as tk

root = tk.Tk()

btn = tk.Button(root, text="Press")
btn.pack()

root.mainloop()

What Happens When a Button Is Pressed

See that when btn is pressed it calls its own function which is very similar to button_press_handle in the following example:

def button_press_handle(callback=None):
    if callback:
        callback() # Where exactly the method assigned to btn['command'] is being callled

with:

button_press_handle(btn['command'])

You can simply think that command option should be set as, the reference to the method we want to be called, similar to callback in button_press_handle.


Calling a Method(Callback) When the Button is Pressed

Without arguments

So if I wanted to print something when the button is pressed I would need to set:

btn['command'] = print # default to print is new line

Pay close attention to the lack of () with the print method which is omitted in the meaning that: "This is the method's name which I want you to call when pressed but don't call it just this very instant." However, I didn't pass any arguments for the print so it printed whatever it prints when called without arguments.

With Argument(s)

Now If I wanted to also pass arguments to the method I want to be called when the button is pressed I could make use of the anonymous functions, which can be created with lambda statement, in this case for print built-in method, like the following:

btn['command'] = lambda arg1="Hello", arg2=" ", arg3="World!" : print(arg1 + arg2 + arg3)

Calling Multiple Methods when the Button Is Pressed

Without Arguments

You can also achieve that using lambda statement but it is considered bad practice and thus I won't include it here. The good practice is to define a separate method, multiple_methods, that calls the methods wanted and then set it as the callback to the button press:

def multiple_methods():
    print("Vicariously") # the first inner callback
    print("I") # another inner callback

With Argument(s)

In order to pass argument(s) to method that calls other methods, again make use of lambda statement, but first:

def multiple_methods(*args, **kwargs):
    print(args[0]) # the first inner callback
    print(kwargs['opt1']) # another inner callback

and then set:

btn['command'] = lambda arg="live", kw="as the" : a_new_method(arg, opt1=kw)

Returning Object(s) From the Callback

Also further note that callback can't really return because it's only called inside button_press_handle with callback() as opposed to return callback(). It does return but not anywhere outside that function. Thus you should rather modify object(s) that are accessible in the current scope.


Complete Example with global Object Modification(s)

Below example will call a method that changes btn's text each time the button is pressed:

import tkinter as tk

i = 0
def text_mod():
    global i, btn           # btn can be omitted but not sure if should be
    txt = ("Vicariously", "I", "live", "as", "the", "whole", "world", "dies")
    btn['text'] = txt[i]    # the global object that is modified
    i = (i + 1) % len(txt)  # another global object that gets modified

root = tk.Tk()

btn = tk.Button(root, text="My Button")
btn['command'] = text_mod

btn.pack(fill='both', expand=True)

root.mainloop()

Mirror

How can I change cols of textarea in twitter-bootstrap?

I don't know if this is the correct way however I did this:

<div class="control-group">
  <label class="control-label" for="id1">Label:</label>
  <div class="controls">
    <textarea id="id1" class="textareawidth" rows="10" name="anyname">value</textarea>
  </div>
</div>

and put this in my bootstrapcustom.css file:

@media (min-width: 768px) {
    .textareawidth {
        width:500px;
    }
}
@media (max-width: 767px) {
    .textareawidth {

    }
}

This way it resizes based on the viewport. Seems to line everything up nicely on a big browser and on a small mobile device.

Python Socket Receive Large Amount of Data

TCP/IP is a stream-based protocol, not a message-based protocol. There's no guarantee that every send() call by one peer results in a single recv() call by the other peer receiving the exact data sent—it might receive the data piece-meal, split across multiple recv() calls, due to packet fragmentation.

You need to define your own message-based protocol on top of TCP in order to differentiate message boundaries. Then, to read a message, you continue to call recv() until you've read an entire message or an error occurs.

One simple way of sending a message is to prefix each message with its length. Then to read a message, you first read the length, then you read that many bytes. Here's how you might do that:

def send_msg(sock, msg):
    # Prefix each message with a 4-byte length (network byte order)
    msg = struct.pack('>I', len(msg)) + msg
    sock.sendall(msg)

def recv_msg(sock):
    # Read message length and unpack it into an integer
    raw_msglen = recvall(sock, 4)
    if not raw_msglen:
        return None
    msglen = struct.unpack('>I', raw_msglen)[0]
    # Read the message data
    return recvall(sock, msglen)

def recvall(sock, n):
    # Helper function to recv n bytes or return None if EOF is hit
    data = bytearray()
    while len(data) < n:
        packet = sock.recv(n - len(data))
        if not packet:
            return None
        data.extend(packet)
    return data

Then you can use the send_msg and recv_msg functions to send and receive whole messages, and they won't have any problems with packets being split or coalesced on the network level.

XPath OR operator for different nodes

It the element has two xpath. Then you can write two xpaths like below:

xpath1 | xpath2

Eg:

//input[@name="username"] | //input[@id="wm_login-username"]

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

Is PowerShell ready to replace my Cygwin shell on Windows?

When you compare PowerShell to the combination Cygwin/Perl/Shell, be aware that PowerShell only represents the "Shell" part of that combination.

You can however invoke any command from PowerShell just as you do from cmd.exe or Cygwin. It does not re-implement the specified functions, and it is certainly not comparable to Perl.

It's "just" a shell, but it makes programming easier providing a comfortable interface to the .NET universe.

Also keep in mind that PowerShell requires Windows XP, Windows Server 2003 or higher, which may pose a problem depending on your IT infrastructure.

Update:

I had no idea what kind of philosophical debate my answer would spark.

I posted my answer in the context of the question: Compare PowerShell to Cygwin and Perl and Bash.

PowerShell is a shell, as it makes no syntactic difference between built-in commands, commandlets, user functions, and external commands (.exe, .bat, .cmd). Only invoking .NET methods differ by adding a namespace or an object in the call.

Its programmability derives from the .NET framework, not from anything specific to the PowerShell "language".

I'd say I believe PowerShell is a "scripting language" as soon as Bugzilla or MediaWiki are implemented as PowerShell scripts running on a web server ;)

Until then, enjoy the comparisons.

Difference between java.exe and javaw.exe

The difference is in the subsystem that each executable targets.

  • java.exe targets the CONSOLE subsystem.
  • javaw.exe targets the WINDOWS subsystem.

Most efficient way to prepend a value to an array

Example of prepending in-place:

_x000D_
_x000D_
var A = [7,8,9]_x000D_
var B = [1,2,3]_x000D_
_x000D_
A.unshift(...B)_x000D_
_x000D_
console.log(A) // [1,2,3,7,8,9]
_x000D_
_x000D_
_x000D_

JavaScript isset() equivalent

Be careful in ES6, all the previous solutions doesn't work if you want to check a declaration of a let variable and declare it, if it isn't

example

let myTest = 'text';

if(typeof myTest === "undefined") {
    var myTest = 'new text'; // can't be a let because let declare in a scope
}

you will see a error

Uncaught SyntaxError: Identifier 'myTest' has already been declared

The solution was to change it by a var

var myTest = 'text'; // I replace let by a var

if(typeof myTest === "undefined") {
    var myTest = 'new text';
}

another solution if you can change a let by a var, you need to remove your var

let myTest = 'text';

if(typeof myTest === "undefined") {
    myTest = 'new text'; // I remove the var declaration
}

Send POST data via raw json with postman

Install Postman native app, Chrome extension has been deprecated. (Mine was opening in own window but still ran as Chrome app)

When I catch an exception, how do I get the type, file, and line number?

import sys, os

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)

Entity Framework: There is already an open DataReader associated with this Command

I noticed that this error happens when I send an IQueriable to the view and use it in a double foreach, where the inner foreach also needs to use the connection. Simple example (ViewBag.parents can be IQueriable or DbSet):

foreach (var parent in ViewBag.parents)
{
    foreach (var child in parent.childs)
    {

    }
}

The simple solution is to use .ToList() on the collection before using it. Also note that MARS does not work with MySQL.

How can I write a heredoc to a file in Bash script?

I like this method for concision, readability and presentation in an indented script:

<<-End_of_file >file
?       foo bar
End_of_file

Where ?        is a tab character.

jQuery - How to dynamically add a validation rule

The documentation says:

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is,

> $("form").validate() is called first.

Did you do that? The error message kind of indicates that you didn't.

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

github markdown colspan

I recently needed to do the same thing, and was pleased that the colspan worked fine with consecutive pipes ||

MultiMarkdown v4.5

Tested on v4.5 (latest on macports) and the v5.4 (latest on homebrew). Not sure why it doesn't work on the live preview site you provide.

A simple test that I started with was:

| Header ||
|--------------|
| 0 | 1 |

using the command:

multimarkdown -t html test.md > test.html

Restore the mysql database from .frm files

After much trial and error I was able to get this working based on user359187 answer and this blog post.

To get my old .frm and .ibd transferred to a new MySQL database after copying the files over and assigning MySQL ownership, the key for me was to then log into MySQL and connect to the new database then let MySQL do the work by importing the tablespace.

mysql> connect test;
mysql> ALTER TABLE t1 IMPORT TABLESPACE;

This will import the data using the copied .frm and .ibd files.

I had to run the Alter command for each table separately but this worked and I was able to recover the tables and data.

iPhone App Minus App Store?

With the help of this post, I have made a script that will install via the app Installous for rapid deployment:

# compress application.
/bin/mkdir -p $CONFIGURATION_BUILD_DIR/Payload
/bin/cp -R $CONFIGURATION_BUILD_DIR/MyApp.app $CONFIGURATION_BUILD_DIR/Payload
/bin/cp iTunesCrap/logo_itunes.png $CONFIGURATION_BUILD_DIR/iTunesArtwork
/bin/cp iTunesCrap/iTunesMetadata.plist $CONFIGURATION_BUILD_DIR/iTunesMetadata.plist

cd $CONFIGURATION_BUILD_DIR

# zip up the HelloWorld directory

/usr/bin/zip -r MyApp.ipa Payload iTunesArtwork iTunesMetadata.plist

What Is missing in the post referenced above, is the iTunesMetadata. Without this, Installous will not install apps correctly. Here is an example of an iTunesMetadata:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>appleId</key>
    <string></string>
    <key>artistId</key>
    <integer>0</integer>
    <key>artistName</key>
    <string>MYCOMPANY</string>
    <key>buy-only</key>
    <true/>
    <key>buyParams</key>
    <string></string>
    <key>copyright</key>
    <string></string>
    <key>drmVersionNumber</key>
    <integer>0</integer>
    <key>fileExtension</key>
    <string>.app</string>
    <key>genre</key>
    <string></string>
    <key>genreId</key>
    <integer>0</integer>
    <key>itemId</key>
    <integer>0</integer>
    <key>itemName</key>
    <string>MYAPP</string>
    <key>kind</key>
    <string>software</string>
    <key>playlistArtistName</key>
    <string>MYCOMPANY</string>
    <key>playlistName</key>
    <string>MYAPP</string>
    <key>price</key>
    <integer>0</integer>
    <key>priceDisplay</key>
    <string>nil</string>
    <key>rating</key>
    <dict>
        <key>content</key>
        <string></string>
        <key>label</key>
        <string>4+</string>
        <key>rank</key>
        <integer>100</integer>
        <key>system</key>
        <string>itunes-games</string>
    </dict>
    <key>releaseDate</key>
    <string>Sunday, December 12, 2010</string>
    <key>s</key>
    <integer>143441</integer>
    <key>softwareIcon57x57URL</key>
    <string></string>
    <key>softwareIconNeedsShine</key>
    <false/>
    <key>softwareSupportedDeviceIds</key>
    <array>
        <integer>1</integer>
    </array>
    <key>softwareVersionBundleId</key>
    <string>com.mycompany.myapp</string>
    <key>softwareVersionExternalIdentifier</key>
    <integer>0</integer>
    <key>softwareVersionExternalIdentifiers</key>
    <array>
        <integer>1466803</integer>
        <integer>1529132</integer>
        <integer>1602608</integer>
        <integer>1651681</integer>
        <integer>1750461</integer>
        <integer>1930253</integer>
        <integer>1961532</integer>
        <integer>1973932</integer>
        <integer>2026202</integer>
        <integer>2526384</integer>
        <integer>2641622</integer>
        <integer>2703653</integer>
    </array>
    <key>vendorId</key>
    <integer>0</integer>
    <key>versionRestrictions</key>
    <integer>0</integer>
</dict>
</plist>

Obviously, replace all instances of MyApp with the name of your app and MyCompany with the name of your company.

Basically, this will install on any jailbroken device with Installous installed. After it is set up, this results in very fast deployment, as it can be installed from anywhere, just upload it to your companies website, and download the file directly to the device, and copy / move it to ~/Documents/Installous/Downloads.

CSS background-image - What is the correct usage?

  1. No you don’t need quotes.

  2. Yes you can. But note that relative URLs are resolved from the URL of your stylesheet.

  3. Better don’t use quotes. I think there are clients that don’t understand them.

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Unable to locate tools.jar

As many people mentioned, it looks like you are looking in your JRE instead of the JDK for the tools.jar file.

I would also like to mention that on recent versions of the JDK, there is no more tools.jar file. I downloaded the most recent JDK as of today (JDK version 12) and I could not find any tools.jar. I had to download JDK version 8 (1.8.0) here https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html to get the tools.jar file. I downloaded that version, took the tools.jar file and put it into my recent version's lib folder.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How to find and turn on USB debugging mode on Nexus 4

Solution

To see the option for USB debugging mode in Nexus 4 or Android 4.2 or higher OS, do the following:

  • Open up your device’s “Settings”. This can be done by pressing the Menu button while on your home screen and tapping “System settings”
  • Now scroll to the bottom and tap “About phone” or “About tablet”.
  • At the “About” screen, scroll to the bottom and tap on “Build number” seven times.
    • Make sure you tap seven times. If you see a “Not need, you are already a developer!” message pop up, then you know you have done it correctly.

Done! By tapping on “Build number” seven times, you have unlocked USB debugging mode on Android 4.2 and higher. You can now enable/disable it whenever you desire by going to “Settings” -> “Developer Options” -> “Debugging” ->” USB debugging”.

CONCLUSION

That was easy. The best part is you only have to do the tap-build-number-seven-times once. After you do it once, USB debugging has been unlocked and you can enable or disable at your leisure. Please restart after done these steps.

Additional information

Setting up a Device for Development native documentation of Google Android developer site

Update: Google Pixel 3

If you need to facilitate a connection between your device and a computer with the Android SDK (software development kit), view this info.

  1. From a Home screen, swipe up to display all apps.
  2. Navigate: Settings > System > Advanced.
  3. Developer options .
    If Developer options isn't available, navigate: SettingsAbout phone then tap Build number 7 times. Tap the Back icon  to Settings then select System > Advanced > Developer options.
  4. Ensure that the Developer options switch (upper-right) is turned on .
  5. Tap USB debugging to turn on or off .
  6. If prompted with 'Allow USB debugging?', tap OK to confirm.

Doc by Verizon: Original source

Correct way to synchronize ArrayList in java

Looking at your example, I think ArrayBlockingQueue (or its siblings) may be of use. They look after the synchronisation for you, so threads can write to the queue or peek/take without additional synchronisation work on your part.

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

You either have to make the method Shared or use an instance of the class General:

Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)

or

General.updateDynamics(get_prospect.dynamicsID)

Public Shared Sub updateDynamics(dynID As Int32)
    ' ... '
End Sub

Shared(VB.NET)

Can a table row expand and close?

Well, I'd say use the DIV instead of table as it would be much easier (but there's nothing wrong with using tables).

My approach would be to use jQuery.ajax and request more data from server and that way, the selected DIV (or TD if you use table) will automatically expand based on requested content.

That way, it saves bandwidth and makes it go faster as you don't load all content at once. It loads only when it's selected.

How to "EXPIRE" the "HSET" child key in redis?

You can use Sorted Set in redis to get a TTL container with timestamp as score. For example, whenever you insert a event string into the set you can set its score to the event time. Thus you can get data of any time window by calling zrangebyscore "your set name" min-time max-time

Moreover, we can do expire by using zremrangebyscore "your set name" min-time max-time to remove old events.

The only drawback here is you have to do housekeeping from an outsider process to maintain the size of the set.

LDAP server which is my base dn

Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:

slapcat > backup.ldif

If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.

Caesar Cipher Function in Python

You need to move cipherText = "" before the start of the for loop. You're resetting it each time through the loop.

def caesar(plainText, shift): 
  cipherText = ""
  for ch in plainText:
    if ch.isalpha():
      stayInAlphabet = ord(ch) + shift 
      if stayInAlphabet > ord('z'):
        stayInAlphabet -= 26
      finalLetter = chr(stayInAlphabet)
      cipherText += finalLetter
  print "Your ciphertext is: ", cipherText
  return cipherText

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Use

export LD_LIBRARY_PATH="/path/to/library/"

in your .bashrc otherwise, it'll only be available to bash and not any programs you start.

Try -R/path/to/library/ flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.

EDIT: Looks like -R is Solaris only, and you're on Linux.

An alternate way would be to add the path to /etc/ld.so.conf and run ldconfig. Note that this is a global change that will apply to all dynamically linked binaries.

CSS to keep element at "fixed" position on screen

The easiest way is to use position: fixed:

.element {
  position: fixed;
  bottom: 0;
  right: 0;
}

http://www.w3.org/TR/CSS21/visuren.html#choose-position

(note that position fixed is buggy / doesn't work on ios and android browsers)

Get POST data in C#/ASP.NET

c.Request["AP"] will read posted values. Also you need to use a submit button to post the form:

<input type="submit" value="Submit" />

instead of

<input type=button value="Submit" />

Why in C++ do we use DWORD rather than unsigned int?

SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.

Underline text in UIlabel

Based on Kovpas & Damien Praca's Answers, here is an implementation of UILabelUnderligned which also support textAlignemnt.

#import <UIKit/UIKit.h>

@interface UILabelUnderlined : UILabel

@end

and the implementation:

#import "UILabelUnderlined.h"

@implementation DKUILabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

    CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA

    CGContextSetLineWidth(ctx, 1.0f);

    CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];

    // handle textAlignement

    int alignementXOffset = 0;

    switch (self.textAlignment) {
        case UITextAlignmentLeft:
            break;
        case UITextAlignmentCenter:
            alignementXOffset = (self.frame.size.width - textSize.width)/2;
            break;
        case UITextAlignmentRight:
            alignementXOffset = self.frame.size.width - textSize.width;
            break;
    }

    CGContextMoveToPoint(ctx, alignementXOffset, self.bounds.size.height - 1);
    CGContextAddLineToPoint(ctx, alignementXOffset+textSize.width, self.bounds.size.height - 1);

    CGContextStrokePath(ctx);

    [super drawRect:rect];  
}


@end

C# Equivalent of SQL Server DataTypes

In case anybody is looking for methods to convert from/to C# and SQL Server formats, here goes a simple implementation:

private readonly string[] SqlServerTypes = { "bigint", "binary", "bit",  "char", "date",     "datetime", "datetime2", "datetimeoffset", "decimal", "filestream", "float",  "geography",                              "geometry",                              "hierarchyid",                              "image",  "int", "money",   "nchar",  "ntext",  "numeric", "nvarchar", "real",   "rowversion", "smalldatetime", "smallint", "smallmoney", "sql_variant", "text",   "time",     "timestamp", "tinyint", "uniqueidentifier", "varbinary", "varchar", "xml" };
private readonly string[] CSharpTypes    = { "long",   "byte[]", "bool", "char", "DateTime", "DateTime", "DateTime",  "DateTimeOffset", "decimal", "byte[]",     "double", "Microsoft.SqlServer.Types.SqlGeography", "Microsoft.SqlServer.Types.SqlGeometry", "Microsoft.SqlServer.Types.SqlHierarchyId", "byte[]", "int", "decimal", "string", "string", "decimal", "string",   "Single", "byte[]",     "DateTime",      "short",    "decimal",    "object",      "string", "TimeSpan", "byte[]",    "byte",    "Guid",             "byte[]",    "string",  "string" };

public string ConvertSqlServerFormatToCSharp(string typeName)
{
    var index = Array.IndexOf(SqlServerTypes, typeName);

    return index > -1
        ? CSharpTypes[index]
        : "object";
}

public string ConvertCSharpFormatToSqlServer(string typeName)
{
    var index = Array.IndexOf(CSharpTypes, typeName);

    return index > -1
        ? SqlServerTypes[index]
        : null;
}

Edit: fixed typo

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Convert Unix timestamp to a date string

The standard Perl solution is:

echo $TIMESTAMP | perl -nE 'say scalar gmtime $_'

(or localtime, if preferred)

What is the difference between Builder Design pattern and Factory Design pattern?

Both are Creational patterns, to create Object.

1) Factory Pattern - Assume, you have one super class and N number of sub classes. The object is created depends on which parameter/value is passed.

2) Builder pattern - to create complex object.

Ex: Make a Loan Object. Loan could be house loan, car loan ,
    education loan ..etc. Each loan will have different interest rate, amount ,  
    duration ...etc. Finally a complex object created through step by step process.

Convert date to datetime in Python

Do I really have to manually call datetime(d.year, d.month, d.day)

No, you'd rather like to call

date_to_datetime(dt)

which you can implement once in some utils/time.py in your project:

from typing import Optional
from datetime import date, datetime

def date_to_datetime(
    dt: date,
    hour: Optional[int] = 0,
    minute: Optional[int] = 0, 
    second: Optional[int] = 0) -> datetime:

    return datetime(dt.year, dt.month, dt.day, hour, minute, second)

Print all but the first three columns

I can't believe nobody offered plain shell:

while read -r a b c d; do echo "$d"; done < file

Getting a browser's name client-side

In c# you your browser name using:

System.Web.HttpBrowserCapabilities browser = Request.Browser;

For details see a link.

http://msdn.microsoft.com/en-us/library/3yekbd5b%28v=vs.100%29.aspx

and in Client side:

JQuery:

jQuery.browser

For details see a link:

http://api.jquery.com/jQuery.browser/

Column name or number of supplied values does not match table definition

Update to SQL server 2016/2017/…
We have some stored procedures in place to import and export databases.
In the sp we use (amongst other things) RESTORE FILELISTONLY FROM DISK where we create a table "#restoretemp" for the restore from file.

With SQL server 2016, MS has added a field SnapshotURL nvarchar(360) (restore url Azure) what has caused the error message.
After I have enhanced the additional field, the restore has worked again.
Code snipped (see last field):

 SET @query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(@BackupFile , '''')
CREATE TABLE #restoretemp
(
LogicalName nvarchar(128)
,PhysicalName nvarchar(128)
,[Type] char(1)
,FileGroupName nvarchar(128)
,[Size] numeric(20,0)
,[MaxSize] numeric(20,0)
,FileID bigint
,CreateLSN numeric(25,0)
,DropLSN numeric(25,0) NULL
,UniqueID uniqueidentifier
,ReadOnlyLSN numeric(25,0)
,ReadWriteLSN numeric(25,0)
,BackupSizeInByte bigint
,SourceBlockSize int
,FilegroupID int
,LogGroupGUID uniqueidentifier NULL
,DifferentialBaseLSN numeric(25,0)
,DifferentialbaseGUID uniqueidentifier
,IsReadOnly bit
,IsPresent bit
,TDEThumbprint varbinary(32)
-- Added field 01.10.2018 needed from SQL Server 2016 (Azure URL)
,SnapshotURL nvarchar(360)
)

INSERT #restoretemp EXEC (@query)
SET @errorstat = @@ERROR
if @errorstat <> 0 
Begin
if @Rueckgabe = 0 SET @Rueckgabe = 6
End
Print @Rueckgabe

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Take for example the case where Class A has a getSomething method and class B has a getSomething method and class C extends A and B. What would happen if someone called C.getSomething? There is no way to determine which method to call.

Interfaces basically just specify what methods a implementing class needs to contain. A class that implements multiple interfaces just means that class has to implement the methods from all those interfaces. Whci would not lead to any issues as described above.

What is the simplest SQL Query to find the second largest value?

The easiest way to get second last row from a SQL table is to use ORDER BYColumnNameDESC and set LIMIT 1,1.

Try this:

SELECT * from `TableName` ORDER BY `ColumnName` DESC LIMIT 1,1

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.

But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:

{ Id: 1, 
name:'john', 
phones:[{title:'home',number:111111,...},
        {title:'office',number:22222,...}]
}

sends

{ Id: 1, 
name:'john', 
phones:[object object]
phones:[object object]
}

how to make negative numbers into positive

Use float fabsf (float n) for float values.

Use double fabs (double n) for double values.

Use long double fabsl(long double) for long double values.

Use abs(int) for int values.

How to send a correct authorization header for basic authentication

no need to use user and password as part of the URL

you can try this

byte[] encodedBytes = Base64.encodeBase64("user:passwd".getBytes());

String USER_PASS = new String(encodedBytes);

HttpUriRequest request = RequestBuilder.get(url).addHeader("Authorization", USER_PASS).build();

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

Visual Studio 2015/2017's live debugger is injecting code that contains the deprecated call.

How to read until EOF from cin in C++

The only way you can read a variable amount of data from stdin is using loops. I've always found that the std::getline() function works very well:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

By default getline() reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to getline().

How to retrieve JSON Data Array from ExtJS Store

Here is another simple clean way:

var jsonArr = [];
grid.getStore().each( function (model) {
    jsonArr.push(model.data);
});

Java variable number or arguments for a method

Yes Java allows vargs in method parameter .

public class  Varargs
{
   public int add(int... numbers)
   { 
      int result = 1; 
      for(int number: numbers)
      {
         result= result+number;  
      }  return result; 
   }
}

"Integer number too large" error message for 600851475143

Or, you can declare input number as long, and then let it do the code tango :D ...

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number");
    long n = in.nextLong();

    for (long i = 2; i <= n; i++) {
        while (n % i == 0) {
            System.out.print(", " + i);
            n /= i;
        }
    }
}

wget ssl alert handshake failure

You probably have an old version of wget. I suggest installing wget using Chocolatey, the package manager for Windows. This should give you a more recent version (if not the latest).

Run this command after having installed Chocolatey (as Administrator):

choco install wget

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

How to stop default link click behavior with jQuery

e.preventDefault();

from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Cancels the event if it is cancelable, without stopping further propagation of the event.

In JavaScript can I make a "click" event fire programmatically for a file input element?

You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:

$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();

It works with the hide before the click() but I don't know if it works without calling the show method. Never tried this on Opera, I tested on IE/FF/Safari/Chrome and it works. I hope this will help.

How to copy file from HDFS to the local file system

1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.

$hdfs dfs -get /output-fileFolderName-In-hdfs

How do we update URL or query strings using javascript/jQuery without reloading the page?

Plain javascript: document.location = 'http://www.google.com';

This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.

How to add a new object (key-value pair) to an array in javascript?

If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :

var postData = $('#yourform').serializeArray();

// postData (array with objects) : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]

...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :

postData.push({"name": "phone", "value": "1234-123456"});

Result:

// postData : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]

Using curl POST with variables defined in bash script functions

  • the info from Sir Athos worked perfectly !!

Here's how I had to use it in my curl script for couchDB. It really helped out a lot. Thanks!

bin/curl -X PUT "db_domain_name_:5984/_config/vhosts/$1.couchdb" -d '"/'"$1"'/"' --user "admin:*****"

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

Using async/await with a forEach loop

In addition to @Bergi’s answer, I’d like to offer a third alternative. It's very similar to @Bergi’s 2nd example, but instead of awaiting each readFile individually, you create an array of promises, each which you await at the end.

import fs from 'fs-promise';
async function printFiles () {
  const files = await getFilePaths();

  const promises = files.map((file) => fs.readFile(file, 'utf8'))

  const contents = await Promise.all(promises)

  contents.forEach(console.log);
}

Note that the function passed to .map() does not need to be async, since fs.readFile returns a Promise object anyway. Therefore promises is an array of Promise objects, which can be sent to Promise.all().

In @Bergi’s answer, the console may log file contents in the order they’re read. For example if a really small file finishes reading before a really large file, it will be logged first, even if the small file comes after the large file in the files array. However, in my method above, you are guaranteed the console will log the files in the same order as the provided array.

PostgreSQL: Which version of PostgreSQL am I running?

use VERSION special variable

$psql -c "\echo :VERSION"

how to set width for PdfPCell in ItextSharp

Why not use a PdfPTable object for this? Create a fixed width table and use a float array to set the widths of the columns

PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);

addCell(table, "SER.\nNO.", 2);

addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);

addCell(table, "DESCRIPTION OF GOODS", 2);

addCell(table, "LINE DOC. RECL DATE", 1);

addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);

addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);

....

private static void addCell(PdfPTable table, string text, int rowspan)
{
    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

    PdfPCell cell = new PdfPCell(new Phrase(text, times));
    cell.Rowspan = rowspan;
    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
    cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
    table.AddCell(cell);
}

have a look at this tutorial too...

Creating for loop until list.length

I'd try to search for the solution by google and the string Python for statement, it is as simple as that. The first link says everything. (A great forum, really, but its usage seems to look sometimes like the usage of the Microsoft understanding of all their GUI products' benefits: windows inside, idiots outside.)

TypeError: tuple indices must be integers, not str

The Problem is how you access row

Specifically row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])

If you look up the official-documentation of fetchall() you find.

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.

Therefore you have to access the values of rows with row[__integer__] like row[0]

How to increase the vertical split window size in Vim

In case you need HORIZONTAL SPLIT resize as well:
The command is the same for all splits, just the parameter changes:

- + instead of < >

Examples:
Decrease horizontal size by 10 columns

:10winc -

Increase horizontal size by 30 columns

:30winc +

or within normal mode:

Horizontal splits

10 CTRL+w -

30 CTRL+w +

Vertical splits

10 CTRL+w < (decrease)

30 CTRL+w > (increase)

Python: read all text file lines in loop

You can stop the 2-line separation in the output by using

    with open('t.ini') as f:
       for line in f:
           print line.strip()
           if 'str' in line:
              break

Android ADB devices unauthorized

For FIRE STICK 4K it actually says in the dialog:

Otherwise check for a confirmation dialog on your device

Indeed on the TV in the other room there was a confirmation dialog. Doh'!

How to delete a certain row from mysql table with same column values?

All tables should have a primary key (consisting of a single or multiple columns), duplicate rows doesn't make sense in a relational database. You can limit the number of delete rows using LIMIT though:

DELETE FROM orders WHERE id_users = 1 AND id_product = 2 LIMIT 1

But that just solves your current issue, you should definitely work on the bigger issue by defining primary keys.

Converting an OpenCV Image to Black and White

For those doing video I cobbled the following based on @tsh :

import cv2 as cv
import numpy as np

def nothing(x):pass

cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)

while(True):
    ret, frame = cap.read()
    vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    thresh = cv.getTrackbarPos('T','videoUI');
    vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]

    cv.imshow('videoUI',cv.flip(vid_bw,1))

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv.destroyAllWindows()

Results in:

enter image description here

Mysql adding user for remote access

for what DB is the user? look at this example

mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

so to return to you question the "%" operator means all computers in your network.

like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:

SELECT user,password,host FROM user;

as soon as you got your user set up you should be able to connect like this:

mysql -h localhost -u gmeier -p

hope it helps

How to stop the Timer in android?

     CountDownTimer waitTimer;
     waitTimer = new CountDownTimer(60000, 300) {

       public void onTick(long millisUntilFinished) {
          //called every 300 milliseconds, which could be used to
          //send messages or some other action
       }

       public void onFinish() {
          //After 60000 milliseconds (60 sec) finish current 
          //if you would like to execute something when time finishes          
       }
     }.start();

to stop the timer early:

     if(waitTimer != null) {
         waitTimer.cancel();
         waitTimer = null;
     }

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the presently accepted answer, here's a bit more detail.

The model class referenced by the ForeignKey needs to have a __unicode__ method within it, like here:

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.

How can I introduce multiple conditions in LIKE operator?

This is a good use of a temporary table.

CREATE TEMPORARY TABLE patterns (
  pattern VARCHAR(20)
);

INSERT INTO patterns VALUES ('ABC%'), ('XYZ%'), ('PQR%');

SELECT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);

In the example patterns, there's no way col could match more than one pattern, so you can be sure you'll see each row of tbl at most once in the result. But if your patterns are such that col could match more than one, you should use the DISTINCT query modifier.

SELECT DISTINCT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

I had to cast the integer equivalent to get around the fact that I'm still using .NET 4.0

System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
/* Note the property type  
   [System.Flags]
   public enum SecurityProtocolType
   {
     Ssl3 = 48,
     Tls = 192,
     Tls11 = 768,
     Tls12 = 3072,
   } 
*/

PHP Composer update "cannot allocate memory" error (using Laravel 4)

you can use the following to check your free (swap) memory

free -m

total used free shared buffers cached

Mem: 2048 357 1690 0 0 237
-/+ buffers/cache: 119 1928
Swap: 0 0 0

To enable the swap you can use for example:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

An established connection was aborted by the software in your host machine

This problem appear if two software use same port
generally Android studio use the port 5037
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge.

I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved.

Hopefully this answer will help someone in the future.

MVC [HttpPost/HttpGet] for Action

You cant combine this to attributes.

But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.

The ActionName Attribute allows to have 2 ActionMethods with the same name.

[HttpGet]
public ActionResult MyMethod()
{
    return MyMethodHandler();
}

[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
    return MyMethodHandler();
}

private ActionResult MyMethodHandler()
{
    // handle the get or post request
    return View("MyMethod");
}

Spark RDD to DataFrame python

Try if that works

sc = spark.sparkContext

# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")

How to connect to MongoDB in Windows?

Follow

  1. Create default db folder.

    c:\data\db

    and also log folder

    c:\data\log\mongo.log

    or use following commands in command-prompt

    mkdir c:\data\log    
    mkdir c:\data\db
    
  2. Create config file in bin folder of mongo (or you may in save your desired destination).

    Add following in text file named "mongod" and save it as
    mongod.cfg
    dbpath=c:\data\db
    logpath=c:\data\log\mongo.log

    or use following commands in command-prompt

    echo dbpath=c:\data\db>> "mongod.cfg"
    echo logpath=c:\data\log\mongo.log>> "mongod.cfg"
    
  3. Now open command-prompt (administrator) and run the following command to start mongo server

    mongod
    
  4. Open another command-prompt (don't close 1st prompt) and run client command:

    mongo
    

Hope this will help or you have done this already.

string comparison in batch file

While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.

Example:

@echo off
SetLocal

set Lhs="
set Rhs="

if "%Lhs%" == "%Rhs%" echo Equal

Error:

echo was unexpected at this time.

Solution:

Enable delayed expansion and use ! instead of %.

@echo off
SetLocal EnableDelayedExpansion

set Lhs="
set Rhs="

if !Lhs! == !Rhs! echo Equal

:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal

I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.

Test:

@echo off
SetLocal EnableDelayedExpansion

:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

Creating a list of dictionaries results in a list of copies of the same dictionary

If you want one line:

list_of_dict = [{} for i in range(list_len)]

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

If you want to remove the support for any architecture, for example, ARMv7-s in your case, use menu Project -> Build Settings -> remove the architecture from "valid architectures".

You can use this as a temporary solution until the library has been updated. You have to remove the architecture from your main project, not from the library.

Alternatively, you can set the flag for your debug configuration's "Build Active Architecture Only" to Yes. Leave the release configuration's "Build Active Architecture Only" to No, just so you'll get a reminder before releasing that you ought to upgrade any third-party libraries you're using.

.htaccess or .htpasswd equivalent on IIS?

There isn't a direct 1:1 equivalent.

You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.

If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/

How to validate an Email in PHP?

Stay away from regex and filter_var() solutions for validating email. See this answer: https://stackoverflow.com/a/42037557/953833

How to get the fields in an Object via reflection?

Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.

public Map<String, Object> getNonNullProperties(final Object thingy) {
    final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
                .getClass());
        for (final PropertyDescriptor descriptor : beanInfo
                .getPropertyDescriptors()) {
            try {
                final Object propertyValue = descriptor.getReadMethod()
                        .invoke(thingy);
                if (propertyValue != null) {
                    nonNullProperties.put(descriptor.getName(),
                            propertyValue);
                }
            } catch (final IllegalArgumentException e) {
                // handle this please
            } catch (final IllegalAccessException e) {
                // and this also
            } catch (final InvocationTargetException e) {
                // and this, too
            }
        }
    } catch (final IntrospectionException e) {
        // do something sensible here
    }
    return nonNullProperties;
}

See these references:

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

With mysql Ver 14.14 Distrib 5.7.22 the update statement is now:

update user set authentication_string=password('1111') where user='root';

In C++, what is a virtual base class?

About the memory layout

As a side note, the problem with the Dreaded Diamond is that the base class is present multiple times. So with regular inheritance, you believe you have:

  A
 / \
B   C
 \ /
  D

But in the memory layout, you have:

A   A
|   |
B   C
 \ /
  D

This explain why when call D::foo(), you have an ambiguity problem. But the real problem comes when you want to use a member variable of A. For example, let's say we have:

class A
{
    public :
       foo() ;
       int m_iValue ;
} ;

When you'll try to access m_iValue from D, the compiler will protest, because in the hierarchy, it'll see two m_iValue, not one. And if you modify one, say, B::m_iValue (that is the A::m_iValue parent of B), C::m_iValue won't be modified (that is the A::m_iValue parent of C).

This is where virtual inheritance comes handy, as with it, you'll get back to a true diamond layout, with not only one foo() method only, but also one and only one m_iValue.

What could go wrong?

Imagine:

  • A has some basic feature.
  • B adds to it some kind of cool array of data (for example)
  • C adds to it some cool feature like an observer pattern (for example, on m_iValue).
  • D inherits from B and C, and thus from A.

With normal inheritance, modifying m_iValue from D is ambiguous and this must be resolved. Even if it is, there are two m_iValues inside D, so you'd better remember that and update the two at the same time.

With virtual inheritance, modifying m_iValue from D is ok... But... Let's say that you have D. Through its C interface, you attached an observer. And through its B interface, you update the cool array, which has the side effect of directly changing m_iValue...

As the change of m_iValue is done directly (without using a virtual accessor method), the observer "listening" through C won't be called, because the code implementing the listening is in C, and B doesn't know about it...

Conclusion

If you're having a diamond in your hierarchy, it means that you have 95% probability to have done something wrong with said hierarchy.

Creating temporary files in Android

This is what I typically do:

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

The timeout you specify here needs to be shorter than the default timeout.

The default timeout is 5000 and the framework by default is jasmine in case of jest. You can specify the timeout inside the test by adding

jest.setTimeout(30000);

But this would be specific to the test. Or you can set up the configuration file for the framework.

Configuring Jest

// jest.config.js
module.exports = {
  // setupTestFrameworkScriptFile has been deprecated in
  // favor of setupFilesAfterEnv in jest 24
  setupFilesAfterEnv: ['./jest.setup.js']
}

// jest.setup.js
jest.setTimeout(30000)

See also these threads:

setTimeout per test #5055

Make jasmine.DEFAULT_TIMEOUT_INTERVAL configurable #652

P.S.: The misspelling setupFilesAfterEnv (i.e. setupFileAfterEnv) will also throw the same error.

How do I change the formatting of numbers on an axis with ggplot?

I'm late to the game here but in-case others want an easy solution, I created a set of functions which can be called like:

 ggplot + scale_x_continuous(labels = human_gbp)

which give you human readable numbers for x or y axes (or any number in general really).

You can find the functions here: Github Repo Just copy the functions in to your script so you can call them.

Create Django model or update if exists

Thought I'd add an answer since your question title looks like it is asking how to create or update, rather than get or create as described in the question body.

If you did want to create or update an object, the .save() method already has this behaviour by default, from the docs:

Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:

If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.

It's worth noting that when they say 'if the UPDATE didn't update anything' they are essentially referring to the case where the id you gave the object doesn't already exist in the database.

Conditional logic in AngularJS template

Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.

If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:


Original answer:

Here is a not-so-great "ng-if" directive:

myApp.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
                element.replaceWith(element.children())
            } else {
                element.replaceWith(' ')
            }
        }
    }
});

that allows for this HTML syntax:

<div ng-repeat="message in data.messages" ng-class="message.type">
   <hr>
   <div ng-if="showFrom(message)">
       <div>From: {{message.from.name}}</div>
   </div>    
   <div ng-if="showCreatedBy(message)">
      <div>Created by: {{message.createdBy.name}}</div>
   </div>    
   <div ng-if="showTo(message)">
      <div>To: {{message.to.name}}</div>
   </div>    
</div>

Fiddle.

replaceWith() is used to remove unneeded content from the DOM.

Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?

The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.

E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.

c++ array - expression must have a constant value

The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables. So go with:

const int row = 8;
const int col= 8;
int a[row][col];

UPD: some compilers will actually allow you to pull this off. IIRC, g++ has this feature. However, never use it because your code will become un-portable across compilers.

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

java.lang.NoClassDefFoundError: Could not initialize class XXX

I encounter the same problem. I inited a bean object in static block like below:

static {
    try{
        mqttConfiguration = SpringBootBeanUtils.<MqttConfiguration>getBean(MqttConfiguration.class);
    }catch (Throwable e){
        System.out.println(e);
    }
 }

Just because the process the my bean obejct inition caused a NPE, I get trouble into it. So I think you should check you static code block carefully.

What does PHP keyword 'var' do?

here and now in 2018 using var for variable declaration is synonymous with public as in

class Sample{
    var $usingVar;
    public $usingPublic;

    function .....

}

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If you are early into the development cycle you can try this -

Remove/comment that model and all its usages. Apply migrations. That would delete that model and then add the model again, run migrations and you have a clean model with the new field added.

How can I set the default timezone in node.js?

You can config global timezone with the library tzdata:

npm install tzdata -y

After set your environment with the variable for example: TZ=America/Bogota

And testing in your project:

new Date()

I hope helpyou

Sum of two input value by jquery

use parseInt

   var total = parseInt(a) + parseInt(b);


    $('#total_price').val(total);

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

I've also had this happen (by accident) after creating a new venv while inside an existing virtual environment. an easy way to diagnose this would be to see where the python is symlinked to, i.e. run:

ls -l venv/bin/python

and make sure it points to the appropriate Python binary. For most systems this will be /usr/bin/python or /usr/bin/python3. while if it points to an existing virtual environment it'll be something like /home/youruser/somedir/bin/python. if it's the latter than I'd suggest recreating the venv while making sure that you aren't "inside" any existing virtualenv (i.e. run deactivate )

How do I use brew installed Python as the default Python?

Homebrew does NOT replace stuff in "/usr/bin". You'll just want to put "/usr/local/bin" ahead of "/usr/bin" in your path, then "which python" will give you "/usr/local/bin/python".

Replacing /usr/bin/python (or /usr/bin/ruby) is highly unrecommended.

Escaping Double Quotes in Batch Script

eplawless's own answer simply and effectively solves his specific problem: it replaces all " instances in the entire argument list with \", which is how Bash requires double-quotes inside a double-quoted string to be represented.

To generally answer the question of how to escape double-quotes inside a double-quoted string using cmd.exe, the Windows command-line interpreter (whether on the command line - often still mistakenly called the "DOS prompt" - or in a batch file):See bottom for a look at PowerShell.

tl;dr:

  • You must use "" when passing a string to a(nother) batch file and you may use "" with applications created with Microsoft's C/C++/.NET compilers (which also accept \"), which on Windows includes Python and Node.js:

    • Example: foo.bat "We had 3"" of rain."

    • The following applies to batch files only:

      • "" is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument.

      • Sadly, however, not only are the enclosing double-quotes retained (as usual), but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument, %1:

      • set "str=%~1" removes the enclosing double-quotes; set "str=%str:""="%" then converts the doubled double-quotes to single ones.
        Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

  • \" is required - as the only option - by many other programs, (e.g., Ruby, Perl, and even Microsoft's own Windows PowerShell(!)), but ITS USE IS NOT SAFE:

    • \" is what many executables and interpreters either require - including Windows PowerShell - when passed strings from the outside - or, in the case of Microsoft's compilers, support as an alternative to "" - ultimately, though, it's up to the target program to parse the argument list.
      • Example: foo.exe "We had 3\" of rain."
    • HOWEVER, USE OF \" CAN RESULT IN UNWANTED, ARBITRARY EXECUTION OF COMMANDS and/or INPUT/OUTPUT REDIRECTIONS:
      • The following characters present this risk: & | < >
      • For instance, the following results in unintended execution of the ver command; see further below for an explanation and the next bullet point for a workaround:
        • foo.exe "3\" of snow" "& ver."
    • For Windows PowerShell, \"" and "^"" are robust, but limited alternatives (see section "Calling PowerShell's CLI ..." below).
  • If you must use \", there are only 3 safe approaches, which are, however quite cumbersome: Tip of the hat to T S for his help.

    • Using (possibly selective) delayed variable expansion in your batch file, you can store literal \" in a variable and reference that variable inside a "..." string using !var! syntax - see T S's helpful answer.

      • The above approach, despite being cumbersome, has the advantage that you can apply it methodically and that it works robustly, with any input.
    • Only with LITERAL strings - ones NOT involving VARIABLES - do you get a similarly methodical approach: categorically ^-escape all cmd.exe metacharacters: " & | < > and - if you also want to suppress variable expansion - %:
      foo.exe ^"3\^" of snow^" ^"^& ver.^"

    • Otherwise, you must formulate your string based on recognizing which portions of the string cmd.exe considers unquoted due to misinterpreting \" as closing delimiters:

      • in literal portions containing shell metacharacters: ^-escape them; using the example above, it is & that must be ^-escaped:
        foo.exe "3\" of snow" "^& ver."

      • in portions with %...%-style variable references: ensure that cmd.exe considers them part of a "..." string and that that the variable values do not themselves have embedded, unbalanced quotes - which is not even always possible.

For background information, read on.


Background

Note: This is based on my own experiments. Do let me know if I'm wrong.

POSIX-like shells such as Bash on Unix-like systems tokenize the argument list (string) before passing arguments individually to the target program: among other expansions, they split the argument list into individual words (word splitting) and remove quoting characters from the resulting words (quote removal). The target program is handed an array of individual arguments, with syntactic quotes removed.

By contrast, the Windows command interpreter apparently does not tokenize the argument list and simply passes the single string comprising all arguments - including quoting chars. - to the target program.
However, some preprocessing takes place before the single string is passed to the target program: ^ escape chars. outside of double-quoted strings are removed (they escape the following char.), and variable references (e.g., %USERNAME%) are interpolated first.

Thus, unlike in Unix, it is the target program's responsibility to parse to parse the arguments string and break it down into individual arguments with quotes removed. Thus, different programs can hypothetically require differing escaping methods and there's no single escaping mechanism that is guaranteed to work with all programs - https://stackoverflow.com/a/4094897/45375 contains excellent background on the anarchy that is Windows command-line parsing.

In practice, \" is very common, but NOT SAFE, as mentioned above:

Since cmd.exe itself doesn't recognize \" as an escaped double-quote, it can misconstrue later tokens on the command line as unquoted and potentially interpret them as commands and/or input/output redirections.
In a nutshell: the problem surfaces, if any of the following characters follow an opening or unbalanced \": & | < >; for example:

foo.exe "3\" of snow" "& ver."

cmd.exe sees the following tokens, resulting from misinterpreting \" as a regular double-quote:

  • "3\"
  • of
  • snow" "
  • rest: & ver.

Since cmd.exe thinks that & ver. is unquoted, it interprets it as & (the command-sequencing operator), followed by the name of a command to execute (ver. - the . is ignored; ver reports cmd.exe's version information).
The overall effect is:

  • First, foo.exe is invoked with the first 3 tokens only.
  • Then, command ver is executed.

Even in cases where the accidental command does no harm, your overall command won't work as designed, given that not all arguments are passed to it.

Many compilers / interpreters recognize ONLY \" - e.g., the GNU C/C++ compiler, Python, Perl, Ruby, even Microsoft's own Windows PowerShell when invoked from cmd.exe - and, except (with limitations) for Windows PowerShell with \"", for them there is no simple solution to this problem.
Essentially, you'd have to know in advance which portions of your command line are misinterpreted as unquoted, and selectively ^-escape all instances of & | < > in those portions.

By contrast, use of "" is SAFE, but is regrettably only supported by Microsoft-compiler-based executables and batch files (in the case of batch files, with the quirks discussed above), which notable excludes PowerShell - see next section.


Calling PowerShell's CLI from cmd.exe or POSIX-like shells:

Note: See the bottom section for how quoting is handled inside PowerShell.

When invoked from the outside - e.g., from cmd.exe, whether from the command line or a batch file:

  • PowerShell [Core] v6+ now properly recognizes "" (in addition to \"), which is both safe to use and whitespace-preserving.

    • pwsh -c " ""a & c"".length " doesn't break and correctly yields 6
  • Windows PowerShell (the legacy edition whose last version is 5.1) recognizes only \" and, on Windows also """ and the more robust \"" / "^"" (even though internally PowerShell uses ` as the escape character in double-quoted strings and also accepts "" - see bottom section):

Calling Windows PowerShell from cmd.exe / a batch file:

  • "" breaks, because it is fundamentally unsupported:

    • powershell -c " ""ab c"".length " -> error "The string is missing the terminator"
  • \" and """ work in principle, but aren't safe:

    • powershell -c " \"ab c\".length " works as intended: it outputs 5 (note the 2 spaces)
    • But it isn't safe, because cmd.exe metacharacters break the command, unless escaped:
      powershell -c " \"a& c\".length " breaks, due to the &, which would have to be escaped as ^&
  • \"" is safe, but normalize interior whitespace, which can be undesired:

    • powershell -c " \""a& c\"".length " outputs 4(!), because the 2 spaces are normalized to 1.
  • "^"" is the best choice for Windows PowerShell specifically, where it is both safe and whitespace-preserving, but with PowerShell Core (on Windows) it is the same as \"", i.e, whitespace-normalizing. Credit goes to Venryx for discovering this approach.

    • powershell -c " "^""a& c"^"".length " works: doesn't break - despite & - and outputs 5, i.e., correctly preserved whitespace.

    • PowerShell Core: pwsh -c " "^""a& c"^"".length " works, but outputs 4, i.e. normalizes whitespace, as \"" does.

On Unix-like platforms (Linux, macOS), when calling PowerShell [Core]'s CLI, pwsh, from a POSIX-like shell such as bash:

You must use \", which, however is both safe and whitespace-preserving:

$ pwsh -c " \"a&  c|\".length" # OK: 5

Related information

  • ^ can only be used as the escape character in unquoted strings - inside double-quoted strings, ^ is not special and treated as a literal.

    • CAVEAT: Use of ^ in parameters passed to the call statement is broken (this applies to both uses of call: invoking another batch file or binary, and calling a subroutine in the same batch file):
      • ^ instances in double-quoted values are inexplicably doubled, altering the value being passed: e.g., if variable %v% contains literal value a^b, call :foo "%v%" assigns "a^^b"(!) to %1 (the first parameter) in subroutine :foo.
      • Unquoted use of ^ with call is broken altogether in that ^ can no longer be used to escape special characters: e.g., call foo.cmd a^&b quietly breaks (instead of passing literal a&b too foo.cmd, as would be the case without call) - foo.cmd is never even invoked(!), at least on Windows 7.
  • Escaping a literal % is a special case, unfortunately, which requires distinct syntax depending on whether a string is specified on the command line vs. inside a batch file; see https://stackoverflow.com/a/31420292/45375

    • The short of it: Inside a batch file, use %%. On the command line, % cannot be escaped, but if you place a ^ at the start, end, or inside a variable name in an unquoted string (e.g., echo %^foo%), you can prevent variable expansion (interpolation); % instances on the command line that are not part of a variable reference are treated as literals (e.g, 100%).
  • Generally, to safely work with variable values that may contain spaces and special characters:

    • Assignment: Enclose both the variable name and the value in a single pair of double-quotes; e.g., set "v=a & b" assigns literal value a & b to variable %v% (by contrast, set v="a & b" would make the double-quotes part of the value). Escape literal % instances as %% (works only in batch files - see above).
    • Reference: Double-quote variable references to make sure their value is not interpolated; e.g., echo "%v%" does not subject the value of %v% to interpolation and prints "a & b" (but note that the double-quotes are invariably printed too). By contrast, echo %v% passes literal a to echo, interprets & as the command-sequencing operator, and therefore tries to execute a command named b.
      Also note the above caveat re use of ^ with the call statement.
    • External programs typically take care of removing enclosing double-quotes around parameters, but, as noted, in batch files you have to do it yourself (e.g., %~1 to remove enclosing double-quotes from the 1st parameter) and, sadly, there is no direct way that I know of to get echo to print a variable value faithfully without the enclosing double-quotes.
      • Neil offers a for-based workaround that works as long as the value has no embedded double quotes; e.g.:
        set "var=^&')|;,%!" for /f "delims=" %%v in ("%var%") do echo %%~v
  • cmd.exe does not recognize single-quotes as string delimiters - they are treated as literals and cannot generally be used to delimit strings with embedded whitespace; also, it follows that the tokens abutting the single-quotes and any tokens in between are treated as unquoted by cmd.exe and interpreted accordingly.

    • However, given that target programs ultimately perform their own argument parsing, some programs such as Ruby do recognize single-quoted strings even on Windows; by contrast, C/C++ executables, Perl and Python do not recognize them.
      Even if supported by the target program, however, it is not advisable to use single-quoted strings, given that their contents are not protected from potentially unwanted interpretation by cmd.exe.

Quoting from within PowerShell:

Windows PowerShell is a much more advanced shell than cmd.exe, and it has been a part of Windows for many years now (and PowerShell Core brought the PowerShell experience to macOS and Linux as well).

PowerShell works consistently internally with respect to quoting:

  • inside double-quoted strings, use `" or "" to escape double-quotes
  • inside single-quoted strings, use '' to escape single-quotes

This works on the PowerShell command line and when passing parameters to PowerShell scripts or functions from within PowerShell.

(As discussed above, passing an escaped double-quote to PowerShell from the outside requires \" or, more robustly, \"" - nothing else works).

Sadly, when invoking external programs from PowerShell, you're faced with the need to both accommodate PowerShell's own quoting rules and to escape for the target program:

This problematic behavior is also discussed and summarized in this answer

Double-quotes inside double-quoted strings:

Consider string "3`" of rain", which PowerShell-internally translates to literal 3" of rain.

If you want to pass this string to an external program, you have to apply the target program's escaping in addition to PowerShell's; say you want to pass the string to a C program, which expects embedded double-quotes to be escaped as \":

foo.exe "3\`" of rain"

Note how both `" - to make PowerShell happy - and the \ - to make the target program happy - must be present.

The same logic applies to invoking a batch file, where "" must be used:

foo.bat "3`"`" of rain"

By contrast, embedding single-quotes in a double-quoted string requires no escaping at all.

Single-quotes inside single-quoted strings do not require extra escaping; consider '2'' of snow', which is PowerShell' representation of 2' of snow.

foo.exe '2'' of snow'
foo.bat '2'' of snow'

PowerShell translates single-quoted strings to double-quoted ones before passing them to the target program.

However, double-quotes inside single-quoted strings, which do not need escaping for PowerShell, do still need to be escaped for the target program:

foo.exe '3\" of rain'
foo.bat '3"" of rain'

PowerShell v3 introduced the magic --% option, called the stop-parsing symbol, which alleviates some of the pain, by passing anything after it uninterpreted to the target program, save for cmd.exe-style environment-variable references (e.g., %USERNAME%), which are expanded; e.g.:

foo.exe --% "3\" of rain" -u %USERNAME%

Note how escaping the embedded " as \" for the target program only (and not also for PowerShell as \`") is sufficient.

However, this approach:

  • does not allow for escaping % characters in order to avoid environment-variable expansions.
  • precludes direct use of PowerShell variables and expressions; instead, the command line must be built in a string variable in a first step, and then invoked with Invoke-Expression in a second.

Thus, despite its many advancements, PowerShell has not made escaping much easier when calling external programs. It has, however, introduced support for single-quoted strings.

I wonder if it's fundamentally possible in the Windows world to ever switch to the Unix model of letting the shell do all the tokenization and quote removal predictably, up front, irrespective of the target program, and then invoke the target program by passing the resulting tokens.

Passing JavaScript array to PHP through jQuery $.ajax

This is because PHP reads your value as a string. If I don't want to pass my data as an object (like in the previous answers, which are also fine), I just do this in my PHP:

 $activitiesString = $_POST['activitiesArray'];
 $activitiesArray = (explode(",",$activitiesString));

The last line splits string into bits after every comma. Now $activitiesArray is also an array. It works even if there is no comma (only one element in your javascript array).

Happy coding!

/etc/apt/sources.list" E212: Can't open file for writing

Pre-append your commands with sudo.

For example, Instead of vim textfile.txt, used sudo vim textfile.txt. This will resolve the issue.

Find all packages installed with easy_install/pip?

Adding to @Paul Woolcock's answer,

pip freeze > requirements.txt

will create a requirements file with all installed packages along with the installed version numbers in the active environment at the current location. Running

pip install -r requirements.txt

will install the packages specified in the requirements file.

Flask Download a File

To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.

Example:

from flask import Flask
from flask import send_file
app = Flask(__name__)

@app.route('/download')
def downloadFile ():
    #For windows you need to use drive name [ex: F:/Example.pdf]
    path = "/Examples.pdf"
    return send_file(path, as_attachment=True)

if __name__ == '__main__':
    app.run(port=5000,debug=True) 

Extract data from log file in specified range of time

well, I have spent some time on your date format.....

however, finally i worked it out..

let's take an example file (named logFile), i made it a bit short. say, you want to get last 5 mins' log in this file:

172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
### lines below are what you want (5 mins till the last record)
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 

here is the solution:

# this variable you could customize, important is convert to seconds. 
# e.g 5days=$((5*24*3600))
x=$((5*60))   #here we take 5 mins as example

# this line get the timestamp in seconds of last line of your logfile
last=$(tail -n1 logFile|awk -F'[][]' '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; print d;}' )

#this awk will give you lines you needs:
awk -F'[][]' -v last=$last -v x=$x '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; if (last-d<=x)print $0 }' logFile      

output:

172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET

EDIT

you may notice that in the output the [ and ] are disappeared. If you do want them back, you can change the last awk line print $0 -> print $1 "[" $2 "]" $3

Change value in a cell based on value in another cell

=IF(A2="Y","Male",IF(A2="N","Female",""))

How to include() all PHP files from a directory?

<?php
//Loading all php files into of functions/ folder 

$folder =   "./functions/"; 
$files = glob($folder."*.php"); // return array files

 foreach($files as $phpFile){   
     require_once("$phpFile"); 
}

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

sql how to cast a select query

I interpreted the question as using cast on a subquery. Yes, you can do that:

select cast((<subquery>) as <newtype>)

If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:

select (select cast(<val> as <newtype>) . . .)

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

If you get the error "Unrecognized attribute 'enableSsl'" when following the advice to add that parameter to your web.config. I found that I was able to workaround the error by adding it to my code file instead in this format:

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;

try
{
    smtp.Send(mm);
}
catch (Exception ex)
{
    MsgBox("Message not emailed: " + ex.ToString());
}

This is the system.net section of my web.config:

<system.net>
  <mailSettings>
    <smtp from="<from_email>">
      <network host="smtp.gmail.com"
       port="587"
       userName="<your_email>"
       password="<your_app_password>" />
    </smtp>
  </mailSettings>
</system.net>

Which Architecture patterns are used on Android?

Update November 2018

After working and blogging about MVC and MVP in Android for several years (see the body of the answer below), I decided to capture my knowledge and understanding in a more comprehensive and easily digestible form.

So, I released a full blown video course about Android applications architecture. So, if you're interested in mastering the most advanced architectural patterns in Android development, check out this comprehensive course here.

This answer was updated in order to remain relevant as of November 2016


It looks like you are seeking for architectural patterns rather than design patterns.

Design patterns aim at describing a general "trick" that programmer might implement for handling a particular set of recurring software tasks. For example: In OOP, when there is a need for an object to notify a set of other objects about some events, the observer design pattern can be employed.

Since Android applications (and most of AOSP) are written in Java, which is object-oriented, I think you'll have a hard time looking for a single OOP design pattern which is NOT used on Android.

Architectural patterns, on the other hand, do not address particular software tasks - they aim to provide templates for software organization based on the use cases of the software component in question.

It sounds a bit complicated, but I hope an example will clarify: If some application will be used to fetch data from a remote server and present it to the user in a structured manner, then MVC might be a good candidate for consideration. Note that I said nothing about software tasks and program flow of the application - I just described it from user's point of view, and a candidate for an architectural pattern emerged.

Since you mentioned MVC in your question, I'd guess that architectural patterns is what you're looking for.

Enter image description here


Historically, there were no official guidelines by Google about applications' architectures, which (among other reasons) led to a total mess in the source code of Android apps. In fact, even today most applications that I see still do not follow OOP best practices and do not show a clear logical organization of code.

But today the situation is different - Google recently released the Data Binding library, which is fully integrated with Android Studio, and, even, rolled out a set of architecture blueprints for Android applications.

Two years ago it was very hard to find information about MVC or MVP on Android. Today, MVC, MVP and MVVM has become "buzz-words" in the Android community, and we are surrounded by countless experts which constantly try to convince us that MVx is better than MVy. In my opinion, discussing whether MVx is better than MVy is totally pointless because the terms themselves are very ambiguous - just look at the answers to this question, and you'll realize that different people can associate these abbreviations with completely different constructs.

Due to the fact that a search for a best architectural pattern for Android has officially been started, I think we are about to see several more ideas come to light. At this point, it is really impossible to predict which pattern (or patterns) will become industry standards in the future - we will need to wait and see (I guess it is matter of a year or two).

However, there is one prediction I can make with a high degree of confidence: Usage of the Data Binding library will not become an industry standard. I'm confident to say that because the Data Binding library (in its current implementation) provides short-term productivity gains and some kind of architectural guideline, but it will make the code non-maintainable in the long run. Once long-term effects of this library will surface - it will be abandoned.


Now, although we do have some sort of official guidelines and tools today, I, personally, don't think that these guidelines and tools are the best options available (and they are definitely not the only ones). In my applications I use my own implementation of an MVC architecture. It is simple, clean, readable and testable, and does not require any additional libraries.

This MVC is not just cosmetically different from others - it is based on a theory that Activities in Android are not UI Elements, which has tremendous implications on code organization.

So, if you're looking for a good architectural pattern for Android applications that follows SOLID principles, you can find a description of one in my post about MVC and MVP architectural patterns in Android.

How to hide Table Row Overflow?

wrap the table in a div with class="container"

div.container {
    width: 100%;
    overflow-x: auto;
}

then

#table_id tr td {
   white-space:nowrap;
}

result

overflow effect

How big can a MySQL database get before performance starts to degrade

The database size does matter. If you have more than one table with more than a million records, then performance starts indeed to degrade. The number of records does of course affect the performance: MySQL can be slow with large tables. If you hit one million records you will get performance problems if the indices are not set right (for example no indices for fields in "WHERE statements" or "ON conditions" in joins). If you hit 10 million records, you will start to get performance problems even if you have all your indices right. Hardware upgrades - adding more memory and more processor power, especially memory - often help to reduce the most severe problems by increasing the performance again, at least to a certain degree. For example 37 signals went from 32 GB RAM to 128GB of RAM for the Basecamp database server.

How to get status code from webclient?

You can check if the error is of type WebException and then inspect the response code;

if (e.Error.GetType().Name == "WebException")
{
   WebException we = (WebException)e.Error;
   HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
   if (response.StatusCode==HttpStatusCode.NotFound)
      System.Diagnostics.Debug.WriteLine("Not found!");
}

or

try
{
    // send request
}
catch (WebException e)
{
    // check e.Status as above etc..
}

java.util.NoSuchElementException: No line found

I also encounter with that problem. In my case the problem was that i closed the scanner inside one of the funcs..

_x000D_
_x000D_
public class Main _x000D_
{_x000D_
 public static void main(String[] args) _x000D_
 {_x000D_
  Scanner menu = new Scanner(System.in);_x000D_
        boolean exit = new Boolean(false);_x000D_
    while(!exit){_x000D_
  String choose = menu.nextLine();_x000D_
        Part1 t=new Part1()_x000D_
        t.start();_x000D_
     System.out.println("Noooooo Come back!!!"+choose);_x000D_
  }_x000D_
 menu.close();_x000D_
 }_x000D_
}_x000D_
_x000D_
public class Part1 extends Thread _x000D_
{_x000D_
public void run()_x000D_
  { _x000D_
     Scanner s = new Scanner(System.in);_x000D_
     String st = s.nextLine();_x000D_
     System.out.print("bllaaaaaaa\n"+st);_x000D_
     s.close();_x000D_
 }_x000D_
}_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

The code above made the same exaption, the solution was to close the scanner only once at the main.

Check if property has attribute

If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)

public class Foo
{
   public string A {get;set;}

   [Special]
   public string B {get;set;}   
}

var type = typeof(Foo);

var specialProperties = type.GetRuntimeProperties()
     .Where(pi => pi.PropertyType == typeof (string) 
      && pi.GetCustomAttributes<Special>(true).Any());

You can then check on the number of properties that have this special property if you need to.

Regular Expression to get all characters before "-"

Find all word and space characters up to and including a -

^[\w ]+-

For loop in multidimensional javascript array

Or you can do this alternatively with "forEach()":

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

cubes.forEach(function each(item) {
  if (Array.isArray(item)) {
    // If is array, continue repeat loop
    item.forEach(each);
  } else {
    console.log(item);
  }
});

If you need array's index, please try this code:

var i = 0; j = 0;

cubes.forEach(function each(item) {
  if (Array.isArray(item)) {
    // If is array, continue repeat loop
    item.forEach(each);
    i++;
    j = 0;
  } else {
    console.log("[" + i + "][" + j + "] = " + item);
    j++;
  }
});

And the result will look like this:

[0][0] = 1
[0][1] = 2
[0][2] = 3
[1][0] = 4
[1][1] = 5
[1][2] = 6
[2][0] = 7
[2][1] = 8
[2][2] = 9

Matching strings with wildcard

*X*YZ* = string contains X and contains YZ

@".*X.*YZ"

X*YZ*P = string starts with X, contains YZ and ends with P.

@"^X.*YZ.*P$"

Convert java.util.Date to java.time.LocalDate

public static LocalDate Date2LocalDate(Date date) {
        return LocalDate.parse(date.toString(), DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"))

this format is from Date#tostring

    public String toString() {
        // "EEE MMM dd HH:mm:ss zzz yyyy";
        BaseCalendar.Date date = normalize();
        StringBuilder sb = new StringBuilder(28);
        int index = date.getDayOfWeek();
        if (index == BaseCalendar.SUNDAY) {
            index = 8;
        }
        convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
        convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
        CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

        CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
        CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
        CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
        TimeZone zi = date.getZone();
        if (zi != null) {
            sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
        } else {
            sb.append("GMT");
        }
        sb.append(' ').append(date.getYear());  // yyyy
        return sb.toString();
    }

Resizing UITableView to fit content

In case your contentSize is not correct this is because it is based on the estimatedRowHeight (automatic), use this before

tableView.estimatedRowHeight = 0;

source : https://forums.developer.apple.com/thread/81895

JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);
        }
    });

    mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

The solution is actually described here: http://www.anujgakhar.com/2013/06/15/duplicates-in-a-repeater-are-not-allowed-in-angularjs/

AngularJS does not allow duplicates in a ng-repeat directive. This means if you are trying to do the following, you will get an error.

// This code throws the error "Duplicates in a repeater are not allowed.
// Repeater: row in [1,1,1] key: number:1"
<div ng-repeat="row in [1,1,1]">

However, changing the above code slightly to define an index to determine uniqueness as below will get it working again.

// This will work
<div ng-repeat="row in [1,1,1] track by $index">

Official docs are here: https://docs.angularjs.org/error/ngRepeat/dupes

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

Converting a column within pandas dataframe from int to string

Just for an additional reference.

All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.

def add_zero_in_prefix(df):
    if(df['Hour']<10):
        return '0' + str(df['Hour'])

data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

How to create dispatch queue in Swift 3

DispatchQueue.main.async(execute: {
   // code
})

java: use StringBuilder to insert at the beginning

you can use strbuilder.insert(0,i);

Euclidean distance of two vectors

try using this:

sqrt(sum((x1-x2)^2))

iOS - UIImageView - how to handle UIImage image orientation

Inspired from @Aqua Answer.....

in Objective C

- (UIImage *)fixImageOrientation:(UIImage *)img {

   UIGraphicsBeginImageContext(img.size);
   [img drawAtPoint:CGPointZero];

   UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if (newImg) {
       return newImg;
   }

   return img;
}

How to return a resolved promise from an AngularJS Service using $q?

Try this:

myApp.service('userService', [
    '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
      var deferred= $q.defer();
      this.user = {
        access: false
      };
      try
      {
      this.isAuthenticated = function() {
        this.user = {
          first_name: 'First',
          last_name: 'Last',
          email: '[email protected]',
          access: 'institution'
        };
        deferred.resolve();
      };
    }
    catch
    {
        deferred.reject();
    }

    return deferred.promise;
  ]);

How to convert an OrderedDict into a regular dict in python3

Here is what seems simplest and works in python 3.7

from collections import OrderedDict

d = OrderedDict([('method', 'constant'), ('data', '1.225')])
d2 = dict(d)  # Now a normal dict

Now to check this:

>>> type(d2)
<class 'dict'>
>>> isinstance(d2, OrderedDict)
False
>>> isinstance(d2, dict)
True

NOTE: This also works, and gives same result -

>>> {**d}
{'method': 'constant', 'data': '1.225'}
>>> {**d} == d2
True

As well as this -

>>> dict(d)
{'method': 'constant', 'data': '1.225'}
>>> dict(d) == {**d}
True

Cheers

Browser Caching of CSS files

It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

Labeling file upload button

Take a step back! Firstly, you're assuming the user is using a foreign locale on their device, which is not a sound assumption for justifying taking over the button text of the file picker, and making it say what you want it to.

It is reasonable that you want to control every item of language visible on your page. The content of the File Upload control is not part of the HTML though. There is more content behind this control, for example, in WebKit, it also says "No file chosen" next to the button.

There are very hacky workarounds that attempt this (e.g. like those mentioned in @ChristopheD's answer), but none of them truly succeed:

  • To a screen reader, the file control will still say "Browse..." or "Choose File", and a custom file upload will not be announced as a file upload control, but just a button or a text input.
  • Many of them fail to display the chosen file, or to show that the user has no longer chosen a file
  • Many of them look nothing like the native control, so might look strange on non-standard devices.
  • Keyboard support is typically poor.
  • An author-created UI component can never be as fully functional as its native equivalent (and the closer you get it to behave to suppose IE10 on Windows 7, the more it will deviate from other Browser and Operating System combinations).
  • Modern browsers support drag & drop into the native file upload control.
  • Some techniques may trigger heuristics in security software as a potential ‘click-jacking’ attempt to trick the user into uploading file.

Deviating from the native controls is always a risky thing, there is a whole host of different devices your users could be using, and whatever workaround you choose, you will not have tested it in every one of those devices.

However, there is an even bigger reason why all attempts fail from a User Experience perspective: there is even more non-localized content behind this control, the file selection dialog itself. Once the user is subject to traversing their file system or what not to select a file to upload, they will be subjected to the host Operating System locale.

Are you sure you're doing your user any justice by deviating from the native control, just to localize the text, when as soon as they click it, they're just going to get the Operating System locale anyway?

The best you can do for your users is to ensure you have adequate localised guidance surrounding your file input control. (e.g. Form field label, hint text, tooltip text).

Sorry. :-(

--

This answer is for those looking for any justification not to localise the file upload control.

How to unzip gz file using Python

import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
    with open('file.txt', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

How do I remove all non alphanumeric characters from a string except dash?

Using System.Linq

string withOutSpecialCharacters = new string(stringWithSpecialCharacters.Where(c =>char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-').ToArray());

Convert date to UTC using moment.js

Don't you need something to compare and then retrieve the milliseconds?

For instance:

let enteredDate = $("#txt-date").val(); // get the date entered in the input
let expires = moment.utc(enteredDate); // convert it into UTC

With that you have the expiring date in UTC. Now you can get the "right-now" date in UTC and compare:

var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
let remainingTimeInMls = duration.asMilliseconds();

How to set default Checked in checkbox ReactJS?

To interact with the box you need to update the state for the checkbox once you change it. And to have a default setting you can use defaultChecked.

An example:

<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />

How can I return the current action in an ASP.NET MVC view?

I saw different answers and came up with a class helper:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}

So in View (or master/layout) you can use it like so (Razor syntax):

            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>

Hope it helps.

Put spacing between divs in a horizontal row?

Another idea: Compensate for your margin on the opposite side of the div.

For the side with the spacing you are looking to achieve as an example: 10px, and for the opposing side, compensate with a -10px. It works for me. This likely won't work in all scenarios, but depending on your layout and spacing of other elements, it might work great.

What is HTTP "Host" header?

I would always recommend going to the authoritative source when trying to understand the meaning and purpose of HTTP headers.

The "Host" header field in a request provides the host and port
information from the target URI, enabling the origin server to
distinguish among resources while servicing requests for multiple
host names on a single IP address.

https://tools.ietf.org/html/rfc7230#section-5.4

Powershell script to locate specific file/file name?

To search the whole computer:

gdr -PSProvider 'FileSystem' | %{ ls -r $.root} 2>$null | where { $.name -eq "httpd.exe" }

I am pretty sure this is a much less efficient command, for MANY reasons, but the simplest is your piping everything to your where-object command, when you could still use -filter "httpd.exe" and save a ton of cycles.

Also, on a lot of computers the get-psdrive is gonna grab shared drives, and I am pretty sure you wanted that to get a complete search. Most shares can be IMMENSE with regard to the sheer number of files and folders, so at the very least I would sort my drives by size, and add a check after each search to exit the loop if we locate the file. That is if you are looking for a single instance, if not the only way to save yourself the IMMENSE time sink of searching a 10TB share or two, is to comment the command and highly suggest any user who were to need to use it should limit their search as much as they can. For instance our User Profile share is 10TB, at least the one I am on is, and I can limit my search to the directory $sharedrive\users\myname and search my 116GB directory rather than the 10TB one. Too many unknowns with shares for this type of script, which is already super inefficient with regard to resources and speed.

If I was seriously considering using something like this, I would add a call to a 3rd party package and leverage a DB.

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

The problem could be in Flex's SOAP encoder. Try extending the SOAP encoder in your Flex application and debug the program to see how the null value is handled.

My guess is, it's passed as NaN (Not a Number). This will mess up the SOAP message unmarshalling process sometime (most notably in the JBoss 5 server...). I remember extending the SOAP encoder and performing an explicit check on how NaN is handled.

NodeJS accessing file with relative path

You can use the path module to join the path of the directory in which helper1.js lives to the relative path of foobar.json. This will give you the absolute path to foobar.json.

var fs = require('fs');
var path = require('path');

var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');

This should work on Linux, OSX, and Windows assuming a UTF8 encoding.

Generating UNIQUE Random Numbers within a range

Get a random number. Is it stored in the array already? If not, store it. If so, then go get another random number and repeat.

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

You can do like this:

    TimeZone tz = TimeZone.getDefault();
    int offset = tz.getRawOffset();

    String timeZone = String.format("%s%02d%02d", offset >= 0 ? "+" : "-", offset / 3600000, (offset / 60000) % 60);

Deleting all files from a folder using PHP?

If you want to delete everything from folder (including subfolders) use this combination of array_map, unlink and glob:

array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

This call can also handle empty directories ( thanks for the tip, @mojuba!)