Programs & Examples On #Mysql error 1030

Hide scroll bar, but while still being able to scroll

To hide scroll bars for elements with overflowing content use.

.div{

  scrollbar-width: none; /* The most elegant way for Firefox */

}    

Is there a color code for transparent in HTML?

If you are looking for android apps, you can use

#00000000 

What is your most productive shortcut with Vim?

The Control+R mechanism is very useful :-) In either insert mode or command mode (i.e. on the : line when typing commands), continue with a numbered or named register:

  • a - z the named registers
  • " the unnamed register, containing the text of the last delete or yank
  • % the current file name
  • # the alternate file name
  • * the clipboard contents (X11: primary selection)
  • + the clipboard contents
  • / the last search pattern
  • : the last command-line
  • . the last inserted text
  • - the last small (less than a line) delete
  • =5*5 insert 25 into text (mini-calculator)

See :help i_CTRL-R and :help c_CTRL-R for more details, and snoop around nearby for more CTRL-R goodness.

how to get the attribute value of an xml node using java

try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

For anyone looking at this and had no result with adding the Access-Control-Allow-Origin try also adding the Access-Control-Allow-Headers. May safe somebody from a headache.

Difference between "\n" and Environment.NewLine

Environment.NewLine will return the newline character for the corresponding platform in which your code is running

you will find this very useful when you deploy your code in linux on the Mono framework

How To limit the number of characters in JTextField?

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
        evt.consume();
    }

Where "20" is the maximum number of characters that you want.

Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

Deleting all files from a folder using PHP?

public static function recursiveDelete($dir)
{
    foreach (new \DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            if ($fileInfo->isDir()) {
                recursiveDelete($fileInfo->getPathname());
            } else {
                unlink($fileInfo->getPathname());
            }
        }
    }
    rmdir($dir);
}

Padding or margin value in pixels as integer using jQuery

You should be able to use CSS (http://docs.jquery.com/CSS/css#name). You may have to be more specific such as "padding-left" or "margin-top".

Example:

CSS

a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}

JS

$("a").css("margin-top");

The result is 10px.

If you want to get the integer value, you can do the following:

parseInt($("a").css("margin-top"))

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

Difference between a script and a program?

Scripts are usually interpreted (by another executable).

A program is usually a standalone compiled executable in its own right (although it might have library dependencies), consisting of machine code or byte codes (for just-in-time compiled programs)

jQuery autohide element after 5 seconds

Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.

You can do this with 1 line of code:

$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);

If you're using jQuery you don't need setTimeout, at least not to autohide an element.

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

UICollectionView Set number of columns

First add UICollectionViewDelegateFlowLayout as protocol.

Then:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
        var columnCount = 3
        let width  = (view.frame.width - 20) / columnCount
        return CGSize(width: width, height: width)
}

Loading context in Spring using web.xml

You can also load the context while defining the servlet itself (WebApplicationContext)

  <servlet>
    <servlet-name>admin</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/*.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

rather than (ApplicationContext)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

or can do both together.

Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet etc)

Context loaded by ContextLoaderListener will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.

Set Session variable using javascript in PHP

The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:

$.post('/setsessionvariable.php', { name: 'value' });

You should, of course, be cautious about exposing such script.

What are carriage return, linefeed, and form feed?

Apart from above information, there is still an interesting history of LF (\n) and CR (\r). [Original author : ??? Source : http://www.ruanyifeng.com/blog/2006/04/post_213.html] Before computer came out, there was a type of teleprinter called Teletype Model 33. It can print 10 characters each second. But there is one problem with this, after finishing printing each line, it will take 0.2 second to move to next line, which is time of printing 2 characters. If a new characters is transferred during this 0.2 second, then this new character will be lost.

So scientists found a way to solve this problem, they add two ending characters after each line, one is 'Carriage return', which is to tell the printer to bring the print head to the left.; the other one is 'Line feed', it tells the printer to move the paper up 1 line.

Later, computer became popular, these two concepts are used on computers. At that time, the storage device was very expensive, so some scientists said that it was expensive to add two characters at the end of each line, one is enough, so there are some arguments about which one to use.

In UNIX/Mac and Linux, '\n' is put at the end of each line, in Windows, '\r\n' is put at the end of each line. The consequence of this use is that files in UNIX/Mac will be displayed in one line if opened in Windows. While file in Windows will have one ^M at the end of each line if opened in UNIX or Mac.

How to set default value for HTML select?

Simplay you can place HTML select attribute to option a like shown below

Define the attributes like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

What is the simplest way to swap each pair of adjoining chars in a string with Python?

A more general answer... you can do any single pairwise swap with tuples or strings using this approach:

# item can be a string or tuple and swap can be a list or tuple of two
# indices to swap
def swap_items_by_copy(item, swap):
   s0 = min(swap)
   s1 = max(swap)
   if isinstance(item,str):
        return item[:s0]+item[s1]+item[s0+1:s1]+item[s0]+item[s1+1:]
   elif isinstance(item,tuple):
        return item[:s0]+(item[s1],)+item[s0+1:s1]+(item[s0],)+item[s1+1:]
   else:
        raise ValueError("Type not supported")

Then you can invoke it like this:

>>> swap_items_by_copy((1,2,3,4,5,6),(1,2))
(1, 3, 2, 4, 5, 6)
>>> swap_items_by_copy("hello",(1,2))
'hlelo'
>>> 

Thankfully python gives empty strings or tuples for the cases where the indices refer to non existent slices.

Show datalist labels but submit the actual value

When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.

$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+ 
$('#autocomplete_input').val() +'"]').data('value'));
})

Using GroupBy, Count and Sum in LINQ Lambda Expressions

        var q = from b in listOfBoxes
                group b by b.Owner into g
                select new
                           {
                               Owner = g.Key,
                               Boxes = g.Count(),
                               TotalWeight = g.Sum(item => item.Weight),
                               TotalVolume = g.Sum(item => item.Volume)
                           };

How can I limit ngFor repeat to some number of items in Angular?

You can directly apply slice() to the variable. StackBlitz Demo

<li *ngFor="let item of list.slice(0, 10);">
   {{item.text}}
</li>

What does HTTP/1.1 302 mean exactly?

As per the http status code definitions a 302 indicates a (temporary) redirect. "The requested resource resides temporarily under a different URI"

Updating the value of data attribute using jQuery

$('.toggle img').each(function(index) { 
    if($(this).attr('data-id') == '4')
    {
        $(this).attr('data-block', 'something');
        $(this).attr('src', 'something.jpg');
    }
});

or

$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

npm behind a proxy fails with status 403

Due to security violations, organizations may have their own repositories.

set your local repo as below.

npm config set registry https://yourorg-artifactory.com/

I hope this will solve the issue.

How to get Top 5 records in SqLite?

An equivalent statement would be

select * from [TableName] limit 5

http://www.w3schools.com/sql/sql_top.asp

How to install PyQt4 in anaconda?

For windows users, there is an easy fix. Download whl files from:

https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyqt4

run from anaconda prompt pip install PyQt4-4.11.4-cp37-cp37m-win_amd64.whl

Python vs Cpython

Even I had the same problem understanding how are CPython, JPython, IronPython, PyPy are different from each other.

So, I am willing to clear three things before I begin to explain:

  1. Python: It is a language, it only states/describes how to convey/express yourself to the interpreter (the program which accepts your python code).
  2. Implementation: It is all about how the interpreter was written, specifically, in what language and what it ends up doing.
  3. Bytecode: It is the code that is processed by a program, usually referred to as a virtual machine, rather than by the "real" computer machine, the hardware processor.

CPython is the implementation, which was written in C language. It ends up producing bytecode (stack-machine based instruction set) which is Python specific and then executes it. The reason to convert Python code to a bytecode is because it's easier to implement an interpreter if it looks like machine instructions. But, it isn't necessary to produce some bytecode prior to execution of the Python code (but CPython does produce).

If you want to look at CPython's bytecode then you can. Here's how you can:

>>> def f(x, y):                # line 1
...    print("Hello")           # line 2
...    if x:                    # line 3
...       y += x                # line 4
...    print(x, y)              # line 5
...    return x+y               # line 6
...                             # line 7
>>> import dis                  # line 8
>>> dis.dis(f)                  # line 9
  2           0 LOAD_GLOBAL              0 (print)
              2 LOAD_CONST               1 ('Hello')
              4 CALL_FUNCTION            1
              6 POP_TOP

  3           8 LOAD_FAST                0 (x)
             10 POP_JUMP_IF_FALSE       20

  4          12 LOAD_FAST                1 (y)
             14 LOAD_FAST                0 (x)
             16 INPLACE_ADD
             18 STORE_FAST               1 (y)

  5     >>   20 LOAD_GLOBAL              0 (print)
             22 LOAD_FAST                0 (x)
             24 LOAD_FAST                1 (y)
             26 CALL_FUNCTION            2
             28 POP_TOP

  6          30 LOAD_FAST                0 (x)
             32 LOAD_FAST                1 (y)
             34 BINARY_ADD
36 RETURN_VALUE

Now, let's have a look at the above code. Lines 1 to 6 are a function definition. In line 8, we import the 'dis' module which can be used to view the intermediate Python bytecode (or you can say, disassembler for Python bytecode) that is generated by CPython (interpreter).

NOTE: I got the link to this code from #python IRC channel: https://gist.github.com/nedbat/e89fa710db0edfb9057dc8d18d979f9c

And then, there is Jython, which is written in Java and ends up producing Java byte code. The Java byte code runs on Java Runtime Environment, which is an implementation of Java Virtual Machine (JVM). If this is confusing then I suspect that you have no clue how Java works. In layman terms, Java (the language, not the compiler) code is taken by the Java compiler and outputs a file (which is Java byte code) that can be run only using a JRE. This is done so that, once the Java code is compiled then it can be ported to other machines in Java byte code format, which can be only run by JRE. If this is still confusing then you may want to have a look at this web page.

Here, you may ask if the CPython's bytecode is portable like Jython, I suspect not. The bytecode produced in CPython implementation was specific to that interpreter for making it easy for further execution of code (I also suspect that, such intermediate bytecode production, just for the ease the of processing is done in many other interpreters).

So, in Jython, when you compile your Python code, you end up with Java byte code, which can be run on a JVM.

Similarly, IronPython (written in C# language) compiles down your Python code to Common Language Runtime (CLR), which is a similar technology as compared to JVM, developed by Microsoft.

Running Python on Windows for Node.js dependencies

One and/or multiple of those should help:

  1. Add C:\Python27\ to your PATH variable (considering you have Python installed in this directory)
    How to set PATH env variable: http://www.computerhope.com/issues/ch000549.htm
    Restart your console and/or Windows after setting variable.

  2. In the same section as above ("Environment Variables"), add new variable with name PYTHON and value C:\Python27\python.exe
    Restart your console and/or Windows after setting variable.

  3. Open Windows command line (cmd) in Admin mode.
    Change directory to your Python installation path: cd C:\Python27
    Make symlink needed for some installations: mklink python2.7.exe python.exe

Please note that you should have Python 2.x, NOT 3.x, to run node-gyp based installations!

The text below says about Unix, but Windows version also requires Python 2.x:

You can install with npm:

$ npm install -g node-gyp
You will also need to install:

On Unix:
python (v2.7 recommended, v3.x.x is not supported)
make
A proper C/C++ compiler toolchain, like GCC

This article may also help: https://github.com/nodejs/node-gyp#installation

How to move table from one tablespace to another in oracle 11g

Try this:-

ALTER TABLE <TABLE NAME to be moved> MOVE TABLESPACE <destination TABLESPACE NAME>

Very nice suggestion from IVAN in comments so thought to add in my answer

Note: this will invalidate all table's indexes. So this command is usually followed by

alter index <owner>."<index_name>" rebuild;

Adding subscribers to a list using Mailchimp's API v3

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

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

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

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

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

syncMailchimp($data);

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

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

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

    $ch = curl_init($url);

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

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

    return $httpCode;
}

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

Declare and initialize a Dictionary in Typescript

Here is a more general Dictionary implementation inspired by this from @dmck

    interface IDictionary<T> {
      add(key: string, value: T): void;
      remove(key: string): void;
      containsKey(key: string): boolean;
      keys(): string[];
      values(): T[];
    }

    class Dictionary<T> implements IDictionary<T> {

      _keys: string[] = [];
      _values: T[] = [];

      constructor(init?: { key: string; value: T; }[]) {
        if (init) {
          for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
          }
        }
      }

      add(key: string, value: T) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
      }

      remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
      }

      keys(): string[] {
        return this._keys;
      }

      values(): T[] {
        return this._values;
      }

      containsKey(key: string) {
        if (typeof this[key] === "undefined") {
          return false;
        }

        return true;
      }

      toLookup(): IDictionary<T> {
        return this;
      }
    }

How to switch to the new browser window, which opens after click on the button?

Just to add to the content ...

To go back to the main window(default window) .

use driver.switchTo().defaultContent();

ImportError: No module named enum

Please use --user at end of this, it is working fine for me.

pip install enum34 --user

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

In my case, this was caused by custom manifest entries added by the maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Removing the following entries fixed the problem

<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>

element not interactable exception in selenium web automation

Try setting an implicit wait of maybe 10 seconds.

gmail.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Or set an explicit wait. An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. In your case, it is the visibility of the password input field. (Thanks to ainlolcat's comment)

WebDriver gmail= new ChromeDriver();
gmail.get("https://www.gmail.co.in"); 
gmail.findElement(By.id("Email")).sendKeys("abcd");
gmail.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(gmail, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
gmail.findElement(By.id("Passwd")).sendKeys("xyz");

Explanation: The reason selenium can't find the element is because the id of the password input field is initially Passwd-hidden. After you click on the "Next" button, Google first verifies the email address entered and then shows the password input field (by changing the id from Passwd-hidden to Passwd). So, when the password field is still hidden (i.e. Google is still verifying the email id), your webdriver starts searching for the password input field with id Passwd which is still hidden. And hence, an exception is thrown.

Trying to add adb to PATH variable OSX

I use zsh and Android Studio. I use a variable for my Android SDK path and configure in the file ~/.zshrc:

export ANDROID_HOME=/Applications/Android\ Studio.app/sdk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"

Note: Make sure not to include single or double quotes around the specified path. If you do, it won't work.

Decimal number regular expression, where digit after decimal is optional

^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$

should reflect what people usually think of as a well formed decimal number.

The digits before the decimal point can be either a single digit, in which case it can be from 0 to 9, or more than one digits, in which case it cannot start with a 0.

If there are any digits present before the decimal sign, then the decimal and the digits following it are optional. Otherwise, a decimal has to be present followed by at least one digit. Note that multiple trailing 0's are allowed after the decimal point.

grep -E '^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$'

correctly matches the following:

9
0
10
10.
0.
0.0
0.100
0.10
0.01
10.0
10.10
.0
.1
.00
.100
.001

as well as their signed equivalents, whereas it rejects the following:

.
00
01
00.0
01.3

and their signed equivalents, as well as the empty string.

Hexadecimal value 0x00 is a invalid character

In my case, it took some digging, but found it.

My Context

I'm looking at exception/error logs from the website using Elmah. Elmah returns the state of the server at the of time the exception, in the form of a large XML document. For our reporting engine I pretty-print the XML with XmlWriter.

During a website attack, I noticed that some xmls weren't parsing and was receiving this '.', hexadecimal value 0x00, is an invalid character. exception.

NON-RESOLUTION: I converted the document to a byte[] and sanitized it of 0x00, but it found none.

When I scanned the xml document, I found the following:

...
<form>
...
<item name="SomeField">
   <value
     string="C:\boot.ini&#x0;.htm" />
 </item>
...

There was the nul byte encoded as an html entity &#x0; !!!

RESOLUTION: To fix the encoding, I replaced the &#x0; value before loading it into my XmlDocument, because loading it will create the nul byte and it will be difficult to sanitize it from the object. Here's my entire process:

XmlDocument xml = new XmlDocument();
details.Xml = details.Xml.Replace("&#x0;", "[0x00]");  // in my case I want to see it, otherwise just replace with ""
xml.LoadXml(details.Xml);

string formattedXml = null;

// I have this in a helper function, but for this example I have put it in-line
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "\t",
    NewLineHandling = NewLineHandling.None,
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    xml.Save(writer);
    formattedXml = sb.ToString();
}

LESSON LEARNED: sanitize for illegal bytes using the associated html entity, if your incoming data is html encoded on entry.

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

How do you disable browser Autocomplete on web form field / input tag?

Simply try to put attribute autocomplete with value "off" to input type.

<input type="password" autocomplete="off" name="password" id="password" />

How can I find whitespace in a String?

Use this code, was better solution for me.

public static boolean containsWhiteSpace(String line){
    boolean space= false; 
    if(line != null){


        for(int i = 0; i < line.length(); i++){

            if(line.charAt(i) == ' '){
            space= true;
            }

        }
    }
    return space;
}

I just assigned a variable, but echo $variable shows something else

The answer from ks1322 helped me to identify the issue while using docker-compose exec:

If you omit the -T flag, docker-compose exec add a special character that break output, we see b instead of 1b:

$ test=$(/usr/local/bin/docker-compose exec db bash -c "echo 1")
$ echo "${test}b"
b
echo "${test}" | cat -vte
1^M$

With -T flag, docker-compose exec works as expected:

$ test=$(/usr/local/bin/docker-compose exec -T db bash -c "echo 1")
$ echo "${test}b"
1b

How to disable Paste (Ctrl+V) with jQuery?

I tried this in my Angular project and it worked fine without jQuery.

<input type='text' ng-paste='preventPaste($event)'>

And in script part:

$scope.preventPaste = function(e){
   e.preventDefault();
   return false;
};

In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.

How to call a Parent Class's method from Child Class in Python?

Python also has super as well:

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

Example:

class A(object):     # deriving from 'object' declares A as a 'new-style-class'
    def foo(self):
        print "foo"

class B(A):
    def foo(self):
        super(B, self).foo()   # calls 'A.foo()'

myB = B()
myB.foo()

Regex pattern for checking if a string starts with a certain substring?

You could use:

^(mailto|ftp|joe)

But to be honest, StartsWith is perfectly fine to here. You could rewrite it as follows:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

You could also look at the System.Uri class if you are parsing URIs.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

The best option is to use the original LESS version of bootstrap (get it from github).

Open variables.less and look for // Media queries breakpoints

Find this code and change the breakpoint value:

// Large screen / wide desktop
@screen-lg:                  1200px; // change this
@screen-lg-desktop:          @screen-lg;

Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container

Select values of checkbox group with jQuery

I'm not sure about the "@" used in the selector. At least with the latest jQuery, I had to remove the @ to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:

var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});

var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});

Now both, items and about work.

How to store a dataframe using Pandas

pyarrow compatibility across versions

Overall move has been to pyarrow/feather (deprecation warnings from pandas/msgpack). However I have a challenge with pyarrow with transient in specification Data serialized with pyarrow 0.15.1 cannot be deserialized with 0.16.0 ARROW-7961. I'm using serialization to use redis so have to use a binary encoding.

I've retested various options (using jupyter notebook)

import sys, pickle, zlib, warnings, io
class foocls:
    def pyarrow(out): return pa.serialize(out).to_buffer().to_pybytes()
    def msgpack(out): return out.to_msgpack()
    def pickle(out): return pickle.dumps(out)
    def feather(out): return out.to_feather(io.BytesIO())
    def parquet(out): return out.to_parquet(io.BytesIO())

warnings.filterwarnings("ignore")
for c in foocls.__dict__.values():
    sbreak = True
    try:
        c(out)
        print(c.__name__, "before serialization", sys.getsizeof(out))
        print(c.__name__, sys.getsizeof(c(out)))
        %timeit -n 50 c(out)
        print(c.__name__, "zlib", sys.getsizeof(zlib.compress(c(out))))
        %timeit -n 50 zlib.compress(c(out))
    except TypeError as e:
        if "not callable" in str(e): sbreak = False
        else: raise
    except (ValueError) as e: print(c.__name__, "ERROR", e)
    finally: 
        if sbreak: print("=+=" * 30)        
warnings.filterwarnings("default")

With following results for my data frame (in out jupyter variable)

pyarrow before serialization 533366
pyarrow 120805
1.03 ms ± 43.9 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pyarrow zlib 20517
2.78 ms ± 81.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
msgpack before serialization 533366
msgpack 109039
1.74 ms ± 72.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
msgpack zlib 16639
3.05 ms ± 71.7 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
pickle before serialization 533366
pickle 142121
733 µs ± 38.3 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pickle zlib 29477
3.81 ms ± 60.4 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
feather ERROR feather does not support serializing a non-default index for the index; you can .reset_index() to make the index into column(s)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
parquet ERROR Nested column branch had multiple children: struct<x: double, y: double>
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=

feather and parquet do not work for my data frame. I'm going to continue using pyarrow. However I will supplement with pickle (no compression). When writing to cache store pyarrow and pickle serialised forms. When reading from cache fallback to pickle if pyarrow deserialisation fails.

Is java.sql.Timestamp timezone specific?

For Mysql, we have a limitation. In the driver Mysql doc, we have :

The following are some known issues and limitations for MySQL Connector/J: When Connector/J retrieves timestamps for a daylight saving time (DST) switch day using the getTimeStamp() method on the result set, some of the returned values might be wrong. The errors can be avoided by using the following connection options when connecting to a database:

useTimezone=true
useLegacyDatetimeCode=false
serverTimezone=UTC

So, when we do not use this parameters and we call setTimestamp or getTimestamp with calendar or without calendar, we have the timestamp in the jvm timezone.

Example :

The jvm timezone is GMT+2. In the database, we have a timestamp : 1461100256 = 19/04/16 21:10:56,000000000 GMT

Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "");
props.setProperty("useTimezone", "true");
props.setProperty("useLegacyDatetimeCode", "false");
props.setProperty("serverTimezone", "UTC");
Connection con = DriverManager.getConnection(conString, props);
......
Calendar nowGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Calendar nowGMTPlus4 = Calendar.getInstance(TimeZone.getTimeZone("GMT+4"));
......
rs.getTimestamp("timestampColumn");//Oracle driver convert date to jvm timezone and Mysql convert date to GMT (specified in the parameter)
rs.getTimestamp("timestampColumn", nowGMT);//convert date to GMT 
rs.getTimestamp("timestampColumn", nowGMTPlus4);//convert date to GMT+4 timezone

The first method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

The second method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

The third method returns : 1461085856000 = 19/04/2016 - 17:10:56 GMT

Instead of Oracle, when we use the same calls, we have :

The first method returns : 1461093056000 = 19/04/2016 - 19:10:56 GMT

The second method returns : 1461100256000 = 19/04/2016 - 21:10:56 GMT

The third method returns : 1461085856000 = 19/04/2016 - 17:10:56 GMT

NB : It is not necessary to specify the parameters for Oracle.

'LIKE ('%this%' OR '%that%') and something=else' not working

Try something like:

WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else

Nested routes with react router v4 / v5

Using Hooks

The latest update with hooks is to use useRouteMatch.

Main routing component


export default function NestingExample() {
  return (
    <Router>
      <Switch>
       <Route path="/topics">
         <Topics />
       </Route>
     </Switch>
    </Router>
  );
}

Child component

function Topics() {
  // The `path` lets us build <Route> paths 
  // while the `url` lets us build relative links.

  let { path, url } = useRouteMatch();

  return (
    <div>
      <h2>Topics</h2>
      <h5>
        <Link to={`${url}/otherpath`}>/topics/otherpath/</Link>
      </h5>
      <ul>
        <li>
          <Link to={`${url}/topic1`}>/topics/topic1/</Link>
        </li>
        <li>
          <Link to={`${url}/topic2`}>/topics/topic2</Link>
        </li>
      </ul>

      // You can then use nested routing inside the child itself
      <Switch>
        <Route exact path={path}>
          <h3>Please select a topic.</h3>
        </Route>
        <Route path={`${path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={`${path}/otherpath`>
          <OtherPath/>
        </Route>
      </Switch>
    </div>
  );
}

What are WSDL, SOAP and REST?

Wikipedia says "The Web Services Description Language is an XML-based language that provides a model for describing Web services". Put another way, WSDL is to a web service, as javadoc is to a java library.

The really sweet thing about WSDL, though, is that software can generate a client and server using WSDL.

Short description of the scoping rules?

Where is x found?

x is not found as you haven't defined it. :-) It could be found in code1 (global) or code3 (local) if you put it there.

code2 (class members) aren't visible to code inside methods of the same class — you would usually access them using self. code4/code5 (loops) live in the same scope as code3, so if you wrote to x in there you would be changing the x instance defined in code3, not making a new x.

Python is statically scoped, so if you pass ‘spam’ to another function spam will still have access to globals in the module it came from (defined in code1), and any other containing scopes (see below). code2 members would again be accessed through self.

lambda is no different to def. If you have a lambda used inside a function, it's the same as defining a nested function. In Python 2.2 onwards, nested scopes are available. In this case you can bind x at any level of function nesting and Python will pick up the innermost instance:

x= 0
def fun1():
    x= 1
    def fun2():
        x= 2
        def fun3():
            return x
        return fun3()
    return fun2()
print fun1(), x

2 0

fun3 sees the instance x from the nearest containing scope, which is the function scope associated with fun2. But the other x instances, defined in fun1 and globally, are not affected.

Before nested_scopes — in Python pre-2.1, and in 2.1 unless you specifically ask for the feature using a from-future-import — fun1 and fun2's scopes are not visible to fun3, so S.Lott's answer holds and you would get the global x:

0 0

LD_LIBRARY_PATH vs LIBRARY_PATH

LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.

LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.

EDIT: As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH comes into play.

Split data frame string column into multiple columns

Another option is to use the new tidyr package.

library(dplyr)
library(tidyr)

before <- data.frame(
  attr = c(1, 30 ,4 ,6 ), 
  type = c('foo_and_bar', 'foo_and_bar_2')
)

before %>%
  separate(type, c("foo", "bar"), "_and_")

##   attr foo   bar
## 1    1 foo   bar
## 2   30 foo bar_2
## 3    4 foo   bar
## 4    6 foo bar_2

How to open maximized window with Javascript?

If I use Firefox then screen.width and screen.height works fine but in IE and Chrome they don't work properly instead it opens with the minimum size.

And yes I tried giving too large numbers too like 10000 for both height and width but not exactly the maximized effect.

Android dex gives a BufferOverflowException when building

No need to downgrade the build tools back to 18.1.11, this issue is fixed with build tools 19.0.1.

If you can't use 19.0.1 for some reason then:

Make sure that the value of android:targetSdkVersion in AndroidManifest.xml matches target=android-<value> in project.properties. If these two values are not the same, building with build tools version 19.0.0 will end in the BufferOverflowException. Source

There is also some indication from comments on this post that you need to target at least 19 (android-19). Please leave a comment if this solution also works if your target is < 19.

This is how the fix looks for my project. The related AOSP issue is #61710.

1 If you really need to downgrade, you don't need to uninstall build tools 19.0.0, simply install 18.1.1 and add sdk.buildtools=18.1.1 to the local.properties file.

How to simulate a mouse click using JavaScript?

(Modified version to make it work without prototype.js)

function simulate(element, eventName)
{
    var options = extend(defaultOptions, arguments[2] || {});
    var oEvent, eventType = null;

    for (var name in eventMatchers)
    {
        if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
        throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent)
    {
        oEvent = document.createEvent(eventType);
        if (eventType == 'HTMLEvents')
        {
            oEvent.initEvent(eventName, options.bubbles, options.cancelable);
        }
        else
        {
            oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
            options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
            options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
        }
        element.dispatchEvent(oEvent);
    }
    else
    {
        options.clientX = options.pointerX;
        options.clientY = options.pointerY;
        var evt = document.createEventObject();
        oEvent = extend(evt, options);
        element.fireEvent('on' + eventName, oEvent);
    }
    return element;
}

function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
}

var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
}
var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
}

You can use it like this:

simulate(document.getElementById("btn"), "click");

Note that as a third parameter you can pass in 'options'. The options you don't specify are taken from the defaultOptions (see bottom of the script). So if you for example want to specify mouse coordinates you can do something like:

simulate(document.getElementById("btn"), "click", { pointerX: 123, pointerY: 321 })

You can use a similar approach to override other default options.

Credits should go to kangax. Here's the original source (prototype.js specific).

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

How to resolve javax.mail.AuthenticationFailedException issue?

This error is from google security... This Can Be Resolved by Enabling Less Secure .

Go To This Link : "https://www.google.com/settings/security/lesssecureapps" and Make "TURN ON" then your application runs For Sure.

executing shell command in background from script

This works because the it's a static variable. You could do something much cooler like this:

filename="filename"
extension="txt"
for i in {1..20}; do
    eval "filename${i}=${filename}${i}.${extension}"
    touch filename${i}
    echo "this rox" > filename${i}
done

This code will create 20 files and dynamically set 20 variables. Of course you could use an array, but I'm just showing you the feature :). Note that you can use the variables $filename1, $filename2, $filename3... because they were created with evaluate command. In this case I'm just creating files, but you could use to create dynamically arguments to the commands, and then execute in background.

Passing command line arguments from Maven as properties in pom.xml

Inside pom.xml

<project>

.....

<profiles>
    <profile>
        <id>linux64</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build_os>linux</build_os>
            <build_ws>gtk</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>

    <profile>
        <id>win64</id>
        <activation>
            <property>
                <name>env</name>
                <value>win64</value>
            </property>
        </activation>
        <properties>
            <build_os>win32</build_os>
            <build_ws>win32</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>
</profiles>

.....

<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>target-platform-configuration</artifactId>
    <version>${tycho.version}</version>
    <configuration>
        <environments>
            <environment>
                <os>${build_os}</os>
                <ws>${build_ws}</ws>
                <arch>${build_arch}</arch>
            </environment>
        </environments>
    </configuration>
</plugin>

.....

In this example when you run the pom without any argument mvn clean install default profile will execute.

When executed with mvn -Denv=win64 clean install

win64 profile will executed.

Please refer http://maven.apache.org/guides/introduction/introduction-to-profiles.html

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

This code helped find my problem when I had issue with my Entity VAlidation Erros. It told me the exact problem with my Entity Definition. Try following code where you need to cover storeDB.SaveChanges(); in following try catch block.

  try
{
         if (TryUpdateModel(theEvent))
         {
             storeDB.SaveChanges();
             return RedirectToAction("Index");
         }
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
    Exception raise = dbEx;
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            string message = string.Format("{0}:{1}", 
                validationErrors.Entry.Entity.ToString(),
                validationError.ErrorMessage);
            // raise a new exception nesting
            // the current instance as InnerException
            raise = new InvalidOperationException(message, raise);
        }
    }
    throw raise;
}

How to add additional fields to form before submit?

May be useful for some:

(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]

(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])

function addDataToForm(form, data) {
    if(typeof form === 'string') {
        if(form[0] === '#') form = form.slice(1);
        form = document.getElementById(form);
    }

    var keys = Object.keys(data);
    var name;
    var value;
    var input;

    for (var i = 0; i < keys.length; i++) {
        name = keys[i];
        // removing the inputs with the name if already exists [overide]
        // console.log(form);
        Array.prototype.forEach.call(form.elements, function (inpt) {
             if(inpt.name === name) {
                 inpt.parentNode.removeChild(inpt);
             }
        });

        value = data[name];
        input = document.createElement('input');
        input.setAttribute('name', name);
        input.setAttribute('value', value);
        input.setAttribute('type', 'hidden');

        form.appendChild(input);
    }

    return form;
}

Use :

addDataToForm(form, {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can use it like that too

var form = addDataToForm('myFormId', {
    'uri': window.location.href,
     'kpi_val': 150,
     //...
});

you can add # if you like too ("#myformid").

How can I undo git reset --hard HEAD~1?

git reflog and back to the last HEAD 6a56624 (HEAD -> master) HEAD@{0}: reset: moving to HEAD~3 1a9bf73 HEAD@{1}: commit: add changes in model generate binary

How can I check file size in Python?

Strictly sticking to the question, the Python code (+ pseudo-code) would be:

import os
file_path = r"<path to your file>"
if os.stat(file_path).st_size > 0:
    <send an email to somebody>
else:
    <continue to other things>

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I encountered the same error and got stalled with a pyspark dataframe for few days, I was able to resolve it successfully by filling na values with 0 since I was comparing integer values from 2 fields.

Download multiple files as a zip-file using php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

JavaScript property access: dot notation vs. brackets?

(Sourced from here.)

Square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax

including non-ASCII (UTF-8) characters, as in myForm["?"] (more examples).

Secondly, square bracket notation is useful when dealing with property names which vary in a predictable way:

for (var i = 0; i < 10; i++) {
  someFunction(myForm["myControlNumber" + i]);
}

Roundup:

  • Dot notation is faster to write and clearer to read.
  • Square bracket notation allows access to properties containing special characters and selection of properties using variables

Another example of characters that can't be used with dot notation is property names that themselves contain a dot.

For example a json response could contain a property called bar.Baz.

var foo = myResponse.bar.Baz; // incorrect syntax
var foo = myResponse["bar.Baz"]; // correct syntax

How to open a web page from my application?

Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.

Don't forget to check the Troubleshooting section.

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

if you need to add a date-time to your backup file name (Centos7) use the following:

/usr/bin/mysqldump -u USER -pPASSWD DBNAME | gzip > ~/backups/db.$(date +%F.%H%M%S).sql.gz

this will create the file: db.2017-11-17.231537.sql.gz

How to define static property in TypeScript interface

Yes, it is possible. Here is the solution

export interface Foo {

    test(): void;
}

export namespace Foo {

    export function statMethod(): void {
        console.log(2);
    }

}

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Onclick function based on element id

you can try these:

document.getElementById("RootNode").onclick = function(){/*do something*/};

or

$('#RootNode').click(function(){/*do something*/});

or

$(document).on("click", "#RootNode", function(){/*do something*/});

There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:

//in Vanilla JavaScript
window.addEventListener("load", function(){
     document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
    $('#RootNode').click(function(){/*do something*/});
});

JUnit Eclipse Plugin?

You might want to try out Quick JUnit: https://marketplace.eclipse.org/content/quick-junit

The plugin is stable and it allows switching between production and test code. I am currently using Eclipse Mars 4.5 and the plugin is supported for this release as well as for the following:

Luna (4.4), Kepler (4.3), Juno (4.2, 3.8), Previous to Juno (<=4.1)

Location of sqlite database on the device

For this, what I did is

File f=new File("/data/data/your.app.package/databases/your_db.db3");
FileInputStream fis=null;
FileOutputStream fos=null;

try
{
  fis=new FileInputStream(f);
  fos=new FileOutputStream("/mnt/sdcard/db_dump.db");
  while(true)
  {
    int i=fis.read();
    if(i!=-1)
    {fos.write(i);}
    else
    {break;}
  }
  fos.flush();
  Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
  e.printStackTrace();
  Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
}
finally
{
  try
  {
    fos.close();
    fis.close();
  }
  catch(IOException ioe)
  {}
}

And to do this, your app must have permission to access SD card, add following setting to your manifest.xml

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

Not a brilliant way, but works.

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

How to get body of a POST in php?

function getPost()
{
    if(!empty($_POST))
    {
        // when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request
        // NOTE: if this is the case and $_POST is empty, check the variables_order in php.ini! - it must contain the letter P
        return $_POST;
    }

    // when using application/json as the HTTP Content-Type in the request 
    $post = json_decode(file_get_contents('php://input'), true);
    if(json_last_error() == JSON_ERROR_NONE)
    {
        return $post;
    }

    return [];
}

print_r(getPost());

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

I used Identity2 then Scripts didn't load for anonymous user then I add this code in webconfig and Sloved.

<location path="bundles">
<system.web>
  <authorization>
    <allow users="*" />
  </authorization>  
</system.web>
 </location>

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

hasOwnProperty in JavaScript

hasOwnProperty is a normal JavaScript function that takes a string argument.

When you call shape1.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).

You need to call hasOwnProperty with a string containing name, like this: shape1.hasOwnProperty("name").

How do you create nested dict in Python?

It is important to remember when using defaultdict and similar nested dict modules such as nested_dict, that looking up a nonexistent key may inadvertently create a new key entry in the dict and cause a lot of havoc.

Here is a Python3 example with nested_dict module:

import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
    nest['outer1']['wrong_key1']
except KeyError as e:
    print('exception missing key', e)
print('nested dict after lookup with missing key.  no exception raised:\n', nest)

# Instead, convert back to normal dict...
nest_d = nest.to_dict(nest)
try:
    print('converted to normal dict. Trying to lookup Wrong_key2')
    nest_d['outer1']['wrong_key2']
except KeyError as e:
    print('exception missing key', e)
else:
    print(' no exception raised:\n')

# ...or use dict.keys to check if key in nested dict
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):

    print('found wrong_key3')
else:
    print(' did not find wrong_key3')

Output is:

original nested dict:   {"outer1": {"inner2": "v12", "inner1": "v11"}}

nested dict after lookup with missing key.  no exception raised:  
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 

converted to normal dict. 
Trying to lookup Wrong_key2 

exception missing key 'wrong_key2' 

checking with dict.keys 

['wrong_key1', 'inner2', 'inner1']  
did not find wrong_key3

How do the post increment (i++) and pre increment (++i) operators work in Java?

Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.

Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.

Create database from command line

Change the user to postgres :

su - postgres

Create User for Postgres

$ createuser testuser

Create Database

$ createdb testdb

Acces the postgres Shell

psql ( enter the password for postgressql)

Provide the privileges to the postgres user

$ alter user testuser with encrypted password 'qwerty';
$ grant all privileges on database testdb to testuser;

How to prevent a file from direct URL Access?

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteCond %{REQUEST_URI} !^http://(www\.)?localhost/(.*)\.(gif|jpg|png|jpeg|mp4)$ [NC] 
RewriteRule . - [F]

Set transparent background of an imageview on Android

use RelativeLayout which has 2 imageViews in . and set transparency code on the top imageView.

transparency code :

<solid android:color="@color/white"/>
<gradient android:startColor="#40000000"   android:endColor="#FFFFFFFF" android:angle="270"/>

How to compare two JSON have the same properties without order?

I adapted and modified the code from this tutorial to write a function that does a deep comparison of two JS objects.

const isEqual = function(obj1, obj2) {
    const obj1Keys = Object.keys(obj1);
    const obj2Keys = Object.keys(obj2);

    if(obj1Keys.length !== obj2Keys.length) {
        return false;
    }

    for (let objKey of obj1Keys) {
        if (obj1[objKey] !== obj2[objKey]) {
            if(typeof obj1[objKey] == "object" && typeof obj2[objKey] == "object") {
                if(!isEqual(obj1[objKey], obj2[objKey])) {
                    return false;
                }
            } 
            else {
                return false;
            }
        }
    }

    return true;
};

The function compares the respective values of the same keys for the two objects. Further, if the two values are objects, it uses recursion to execute deep comparison on them as well.

Hope this helps.

Android - Launcher Icon Size

I had the same problem but then realized the arrangement of my icon graphic within the square allowed (512 x 512 in my case) was not maximized. So I rotated the image and was able to scale it up to fill the corners better. Then I right clicked on my res folder in my project in Android Studio, then choose New then Image Asset, it took me through a wizard where I got to select my image file to use. Then if you check the box that says "Trim surrounding blank space", it makes sure all edges, that are able, touch the sides of your square. These steps got it much bigger than the original.

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

How do I include a JavaScript file in another JavaScript file?

Better use the jQuery way. To delay the ready event, first call $.holdReady(true). Example (source):

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});

ImportError: No module named 'selenium'

I had a similar problem. It turned out that I had an alias defined for python like so:

alias python=/usr/bin/python3

Apparently virtualenv does not check or update your aliases.

So the solution for me was to remove the alias:

unalias python

Now when I run python, I get the one from the virtual environment. Problem solved.

Changing ImageView source

You're supposed to use setImageResource instead of setBackgroundResource.

regex to remove all text before a character

I learned all my Regex from this website: http://www.zytrax.com/tech/web/regex.htm. Google on 'Regex tutorials' and you'll find loads of helful articles.

String regex = "[a-zA-Z]*\.jpg";
System.out.println ("somthing.jpg".matches (regex));

returns true.

Extension mysqli is missing, phpmyadmin doesn't work

You need the MySQLi module. This error usually occurs when manually installing phpMyAdmin.

sudo apt-get install php7.3-mysql

It will return you with.

[Creating config file /etc/php/7.3/mods-available/mysqlnd.ini with new version]

[Creating config file /etc/php/7.3/mods-available/mysqli.ini with new version]

Then.

sudo service apache2 restart.

Then.

Press F5 on your browser.

Sending Arguments To Background Worker?

You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:

Public (Class or Structure) MyPerson
                public string FirstName { get; set; }
                public string LastName { get; set; }
                public string Address { get; set; }
                public int ZipCode { get; set; }
End Class

And then:

Dim person as new MyPerson With { .FirstName = “Joe”,
                                  .LastName = "Smith”,
                                  ...
                                 }
backgroundWorker1.RunWorkerAsync(person)

and then:

private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
        MyPerson person = e.Argument as MyPerson
        string firstname = person.FirstName;
        string lastname = person.LastName;
        int zipcode = person.ZipCode;                                 
}

Get mouse wheel events in jQuery?

I was stuck in this issue today and found this code is working fine for me

$('#content').on('mousewheel', function(event) {
    //console.log(event.deltaX, event.deltaY, event.deltaFactor);
    if(event.deltaY > 0) {
      console.log('scroll up');
    } else {
      console.log('scroll down');
    }
});

List comprehension on a nested list?

Since i am little late here but i wanted to share how actually list comprehension works especially nested list comprehension :

New_list= [[float(y) for x in l]

is actually same as :

New_list=[]
for x in l:
    New_list.append(x)

And now nested list comprehension :

[[float(y) for y in x] for x in l]

is same as ;

new_list=[]
for x in l:
    sub_list=[]
    for y in x:
        sub_list.append(float(y))

    new_list.append(sub_list)

print(new_list)

output:

[[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0], [30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0], [100.0, 100.0], [100.0, 100.0, 100.0, 100.0, 100.0], [100.0, 100.0, 100.0, 100.0]]

Error in spring application context schema

I have solved it by doing 3 things:

  1. Added this repository to my POM:

    <repository>
        <id>spring-milestone</id>
        <name>Spring Maven MILESTONE Repository</name>
        <url>http://repo.springsource.org/libs-milestone</url>
    </repository>
    
  2. I'm using this version of spring-jpa:

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.2.0.RELEASE</version>
    </dependency>
    
  3. I removed the xsd versions from my context (although I'm not sure it is necessary):

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
      xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
       http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
    

I hope this helps.

Is it possible to send an array with the Postman Chrome extension?

It is important to know, that the VALUE box is only allowed to contain a numeral value (no specifiers).

If you want to send e.g. an array of "messages" with Postman, each having a list of key/value pairs, enter e.g. messages[][reason] into the KEY box and the value of reason into the VALUE box:

enter image description here

The server will receive:

{"messages"=>[{"reason"=>"scrolled", "tabid"=>"2"}, {"reason"=>"reload", "tabid"=>"1"}], "endpoint"=>{}}

How do I collapse sections of code in Visual Studio Code for Windows?

I wish Visual Studio Code could handle:

#region Function Write-Log
Function Write-Log {
    ...
}
#endregion Function Write-Log

Right now Visual Studio Code just ignores it and will not collapse it. Meanwhile Notepad++ and PowerGUI handle this just fine.

Update: I just noticed an update for Visual Studio Code. This is now supported!

What is a "slug" in Django?

It's a descriptive part of the URL that is there to make it more human descriptive, but without necessarily being required by the web server - in What is a "slug" in Django? the slug is 'in-django-what-is-a-slug', but the slug is not used to determine the page served (on this site at least)

Generate your own Error code in swift 3

protocol CustomError : Error {

    var localizedTitle: String
    var localizedDescription: String

}

enum RequestError : Int, CustomError {

    case badRequest         = 400
    case loginFailed        = 401
    case userDisabled       = 403
    case notFound           = 404
    case methodNotAllowed   = 405
    case serverError        = 500
    case noConnection       = -1009
    case timeOutError       = -1001

}

func anything(errorCode: Int) -> CustomError? {

      return RequestError(rawValue: errorCode)
}

Extracting Path from OpenFileDialog path/filename

how about this:

string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

Custom Adapter for List View

public class CustomAdapter extends BaseAdapter{

    ArrayList<BookPojo> data;
    Context ctx;
    int index=0;

    public CustomAdapter(ArrayList<BookPojo> data, Context ctx) {
        super();
        this.data = data;
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertview, ViewGroup parent) {
        // TODO Auto-generated method stub
        View v=convertview;

        if(v==null){
            LayoutInflater vi=LayoutInflater.from(ctx);
            v=vi.inflate(R.layout.messgeview,null);

        }

        RelativeLayout rlmessage=(RelativeLayout)v.findViewById(R.id.rlmessgeview);

        TextView tvisdn=(TextView)v.findViewById(R.id.tvisdn);
        TextView tvtitle=(TextView)v.findViewById(R.id.tvtitle);
        TextView tvauthor=(TextView)v.findViewById(R.id.tvauthor);
        TextView tvprice=(TextView)v.findViewById(R.id.tvprice);

        BookPojo bpj=data.get(position);

        tvisdn.setText(bpj.isdn+"");
        tvtitle.setText(bpj.title);
        tvauthor.setText(bpj.author);
        tvprice.setText(bpj.price+"");

        if(index%2==0)
        {
            rlmessage.setBackgroundColor(Color.BLUE);
        }
        else
        {
            rlmessage.setBackgroundColor(Color.YELLOW);

        }

        index++;

        return v;
    }
}

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

Angular2 router (@angular/router), how to set default route?

V2.0.0 and later

See also see https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

There is also the catch-all route

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

which redirects "invalid" urls.

V3-alpha (vladivostok)

Use path / and redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @angular/router

The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

In the root component

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

for other components

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}

MySQL Insert into multiple tables? (Database normalization?)

For PDO You may do this

$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')"; 
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";

$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);

BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;

Convert International String to \u Codes in java

There is an Open Source java library MgntUtils that has a Utility that converts Strings to unicode sequence and vise versa:

result = "Hello World";
result = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(result);
System.out.println(result);
result = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString(result);
System.out.println(result);

The output of this code is:

\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064
Hello World

The library can be found at Maven Central or at Github It comes as maven artifact and with sources and javadoc

Here is javadoc for the class StringUnicodeEncoderDecoder

Open a new tab on button click in AngularJS

You can do this all within your controller by using the $window service here. $window is a wrapper around the global browser object window.

To make this work inject $window into you controller as follows

.controller('exampleCtrl', ['$scope', '$window',
    function($scope, $window) {
        $scope.redirectToGoogle = function(){
            $window.open('https://www.google.com', '_blank');
        };
    }
]);

this works well when redirecting to dynamic routes

Java: Add elements to arraylist with FOR loop where element name has increasing number

If you simply need a list, you could use:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

If you specifically require an ArrayList, you could use:

ArrayList<Answer> answers = new ArrayList(Arrays.asList(answer1, answer2, answer3));

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

Finding all cycles in a directed graph

If what you want is to find all elementary circuits in a graph you can use the EC algorithm, by JAMES C. TIERNAN, found on a paper since 1970.

The very original EC algorithm as I managed to implement it in php (hope there are no mistakes is shown below). It can find loops too if there are any. The circuits in this implementation (that tries to clone the original) are the non zero elements. Zero here stands for non-existence (null as we know it).

Apart from that below follows an other implementation that gives the algorithm more independece, this means the nodes can start from anywhere even from negative numbers, e.g -4,-3,-2,.. etc.

In both cases it is required that the nodes are sequential.

You might need to study the original paper, James C. Tiernan Elementary Circuit Algorithm

<?php
echo  "<pre><br><br>";

$G = array(
        1=>array(1,2,3),
        2=>array(1,2,3),
        3=>array(1,2,3)
);


define('N',key(array_slice($G, -1, 1, true)));
$P = array(1=>0,2=>0,3=>0,4=>0,5=>0);
$H = array(1=>$P, 2=>$P, 3=>$P, 4=>$P, 5=>$P );
$k = 1;
$P[$k] = key($G);
$Circ = array();


#[Path Extension]
EC2_Path_Extension:
foreach($G[$P[$k]] as $j => $child ){
    if( $child>$P[1] and in_array($child, $P)===false and in_array($child, $H[$P[$k]])===false ){
    $k++;
    $P[$k] = $child;
    goto EC2_Path_Extension;
}   }

#[EC3 Circuit Confirmation]
if( in_array($P[1], $G[$P[$k]])===true ){//if PATH[1] is not child of PATH[current] then don't have a cycle
    $Circ[] = $P;
}

#[EC4 Vertex Closure]
if($k===1){
    goto EC5_Advance_Initial_Vertex;
}
//afou den ksana theoreitai einai asfales na svisoume
for( $m=1; $m<=N; $m++){//H[P[k], m] <- O, m = 1, 2, . . . , N
    if( $H[$P[$k-1]][$m]===0 ){
        $H[$P[$k-1]][$m]=$P[$k];
        break(1);
    }
}
for( $m=1; $m<=N; $m++ ){//H[P[k], m] <- O, m = 1, 2, . . . , N
    $H[$P[$k]][$m]=0;
}
$P[$k]=0;
$k--;
goto EC2_Path_Extension;

#[EC5 Advance Initial Vertex]
EC5_Advance_Initial_Vertex:
if($P[1] === N){
    goto EC6_Terminate;
}
$P[1]++;
$k=1;
$H=array(
        1=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        2=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        3=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        4=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        5=>array(1=>0,2=>0,3=>0,4=>0,5=>0)
);
goto EC2_Path_Extension;

#[EC5 Advance Initial Vertex]
EC6_Terminate:
print_r($Circ);
?>

then this is the other implementation, more independent of the graph, without goto and without array values, instead it uses array keys, the path, the graph and circuits are stored as array keys (use array values if you like, just change the required lines). The example graph start from -4 to show its independence.

<?php

$G = array(
        -4=>array(-4=>true,-3=>true,-2=>true),
        -3=>array(-4=>true,-3=>true,-2=>true),
        -2=>array(-4=>true,-3=>true,-2=>true)
);


$C = array();


EC($G,$C);
echo "<pre>";
print_r($C);
function EC($G, &$C){

    $CNST_not_closed =  false;                          // this flag indicates no closure
    $CNST_closed        = true;                         // this flag indicates closure
    // define the state where there is no closures for some node
    $tmp_first_node  =  key($G);                        // first node = first key
    $tmp_last_node  =   $tmp_first_node-1+count($G);    // last node  = last  key
    $CNST_closure_reset = array();
    for($k=$tmp_first_node; $k<=$tmp_last_node; $k++){
        $CNST_closure_reset[$k] = $CNST_not_closed;
    }
    // define the state where there is no closure for all nodes
    for($k=$tmp_first_node; $k<=$tmp_last_node; $k++){
        $H[$k] = $CNST_closure_reset;   // Key in the closure arrays represent nodes
    }
    unset($tmp_first_node);
    unset($tmp_last_node);


    # Start algorithm
    foreach($G as $init_node => $children){#[Jump to initial node set]
        #[Initial Node Set]
        $P = array();                   // declare at starup, remove the old $init_node from path on loop
        $P[$init_node]=true;            // the first key in P is always the new initial node
        $k=$init_node;                  // update the current node
                                        // On loop H[old_init_node] is not cleared cause is never checked again
        do{#Path 1,3,7,4 jump here to extend father 7
            do{#Path from 1,3,8,5 became 2,4,8,5,6 jump here to extend child 6
                $new_expansion = false;
                foreach( $G[$k] as $child => $foo ){#Consider each child of 7 or 6
                    if( $child>$init_node and isset($P[$child])===false and $H[$k][$child]===$CNST_not_closed ){
                        $P[$child]=true;    // add this child to the path
                        $k = $child;        // update the current node
                        $new_expansion=true;// set the flag for expanding the child of k
                        break(1);           // we are done, one child at a time
            }   }   }while(($new_expansion===true));// Do while a new child has been added to the path

            # If the first node is child of the last we have a circuit
            if( isset($G[$k][$init_node])===true ){
                $C[] = $P;  // Leaving this out of closure will catch loops to
            }

            # Closure
            if($k>$init_node){                  //if k>init_node then alwaya count(P)>1, so proceed to closure
                $new_expansion=true;            // $new_expansion is never true, set true to expand father of k
                unset($P[$k]);                  // remove k from path
                end($P); $k_father = key($P);   // get father of k
                $H[$k_father][$k]=$CNST_closed; // mark k as closed
                $H[$k] = $CNST_closure_reset;   // reset k closure
                $k = $k_father;                 // update k
        }   } while($new_expansion===true);//if we don't wnter the if block m has the old k$k_father_old = $k;
        // Advance Initial Vertex Context
    }//foreach initial


}//function

?>

I have analized and documented the EC but unfortunately the documentation is in Greek.

Excel VBA - Range.Copy transpose paste

Worksheets("Sheet1").Range("A1:A5").Copy
Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True

Bootstrap 4 datapicker.js not included

Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.

Excel is not updating cells, options > formula > workbook calculation set to automatic

On Excel 2016, using Alt+Ctrl+F9 work well.

This combination call Application.CalculateFull() VBA Excel function.

This can be time consuming if other Excel files are loaded because all Excel sheets of all opened workbooks will be calculated again!

I have searched a function to calculate a specific sheet but I don't have found something!

did you register the component correctly? For recursive components, make sure to provide the "name" option

i ran into this problem and below is a different solution. I were export my components as

export default {
    MyComponent1,
    MyComponent2
}

and I imported like this:

import { MyComponent1, MyComponent2} from '@/index'

export default {
  name: 'App',
  components: {
    MyComponent1,
    MyComponent2
  },
};

And it gave this error.

The solution is:

Just use export { ... } don't use export default

How can I run an external command asynchronously from Python?

The accepted answer is very old.

I found a better modern answer here:

https://kevinmccarthy.org/2016/07/25/streaming-subprocess-stdin-and-stdout-with-asyncio-in-python/

and made some changes:

  1. make it work on windows
  2. make it work with multiple commands
import sys
import asyncio

if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())


async def _read_stream(stream, cb):
    while True:
        line = await stream.readline()
        if line:
            cb(line)
        else:
            break


async def _stream_subprocess(cmd, stdout_cb, stderr_cb):
    try:
        process = await asyncio.create_subprocess_exec(
            *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
        )

        await asyncio.wait(
            [
                _read_stream(process.stdout, stdout_cb),
                _read_stream(process.stderr, stderr_cb),
            ]
        )
        rc = await process.wait()
        return process.pid, rc
    except OSError as e:
        # the program will hang if we let any exception propagate
        return e


def execute(*aws):
    """ run the given coroutines in an asyncio loop
    returns a list containing the values returned from each coroutine.
    """
    loop = asyncio.get_event_loop()
    rc = loop.run_until_complete(asyncio.gather(*aws))
    loop.close()
    return rc


def printer(label):
    def pr(*args, **kw):
        print(label, *args, **kw)

    return pr


def name_it(start=0, template="s{}"):
    """a simple generator for task names
    """
    while True:
        yield template.format(start)
        start += 1


def runners(cmds):
    """
    cmds is a list of commands to excecute as subprocesses
    each item is a list appropriate for use by subprocess.call
    """
    next_name = name_it().__next__
    for cmd in cmds:
        name = next_name()
        out = printer(f"{name}.stdout")
        err = printer(f"{name}.stderr")
        yield _stream_subprocess(cmd, out, err)


if __name__ == "__main__":
    cmds = (
        [
            "sh",
            "-c",
            """echo "$SHELL"-stdout && sleep 1 && echo stderr 1>&2 && sleep 1 && echo done""",
        ],
        [
            "bash",
            "-c",
            "echo 'hello, Dave.' && sleep 1 && echo dave_err 1>&2 && sleep 1 && echo done",
        ],
        [sys.executable, "-c", 'print("hello from python");import sys;sys.exit(2)'],
    )

    print(execute(*runners(cmds)))

It is unlikely that the example commands will work perfectly on your system, and it doesn't handle weird errors, but this code does demonstrate one way to run multiple subprocesses using asyncio and stream the output.

Java string replace and the NUL (NULL, ASCII 0) character?

I think it should be the case. To erase the character, you should use replace(".", "") instead.

What does "select 1 from" do?

SELECT COUNT(*) in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will always return true irrespective of CONDITIONS are met or not.

NOT EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will always return false irrespective of CONDITIONS are met or not.

SELECT COUNT 1 in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will return true if CONDITIONS are met. Else false.

NOT EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will return false if CONDITIONS are met. Else true.

Java 8 stream map on entry set

Please make the following part of the Collectors API:

<K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
  return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}

Reading a plain text file in Java

You can use readAllLines and the join method to get whole file content in one line:

String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));

It uses UTF-8 encoding by default, which reads ASCII data correctly.

Also you can use readAllBytes:

String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);

I think readAllBytes is faster and more precise, because it does not replace new line with \n and also new line may be \r\n. It is depending on your needs which one is suitable.

To draw an Underline below the TextView in Android

just surround your text with < u > tag in your string.xml resource file

<string name="your_string"><u>Underlined text</u></string>

and in your Activity/Fragment

mTextView.setText(R.string.your_string);

Content Type text/xml; charset=utf-8 was not supported by service

In my case, I had to specify messageEncoding to Mtom in app.config of the client application like that:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="IntegrationServiceSoap" messageEncoding="Mtom"/>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:29495/IntegrationService.asmx"
                binding="basicHttpBinding" bindingConfiguration="IntegrationServiceSoap"
                contract="IntegrationService.IntegrationServiceSoap" name="IntegrationServiceSoap" />
        </client>
    </system.serviceModel>
</configuration>

Both my client and server use basicHttpBinding. I hope this helps the others :)

React Native TextInput that only accepts numeric characters

if (!/^[0-9]+$/.test('123456askm')) {
  consol.log('Enter Only Number');
} else {
    consol.log('Sucess');
}

Saving data to a file in C#

I think you might want something like this

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

Get the current file name in gulp.src()

I found this plugin to be doing what I was expecting: gulp-using

Simple usage example: Search all files in project with .jsx extension

gulp.task('reactify', function(){
        gulp.src(['../**/*.jsx']) 
            .pipe(using({}));
        ....
    });

Output:

[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx

How to vertically center a <span> inside a div?

Quick answer for single line span

Make the child (in this case a span) the same line-height as the parent <div>'s height

<div class="parent">
  <span class="child">Yes mom, I did my homework lol</span>
</div>

You should then add the CSS rules

.parent { height: 20px; }
.child { line-height: 20px; vertical-align: middle; }



Or you can target it with a child selector

.parent { height: 20px; }
.parent > span { line-height: 20px; vertical-align: middle; }

Background on my own use of this

I ran into this similar issue where I needed to vertically center items in a mobile menu. I made the div and spans inside the same line height. Note that this is for a meteor project and therefore not using inline css ;)

HTML

<div class="international">        
  <span class="intlFlag">
    {{flag}}        
  </span>

  <span class="intlCurrent">
    {{country}}
  </span>

  <span class="intlButton">
    <i class="fa fa-globe"></i>
  </span> 
</div>

CSS (option for multiple spans in a div)

.international {
  height: 42px;
}

.international > span {
  line-height: 42px;
}

In this case if I just had one span I could have added the CSS rule directly to that span.

CSS (option for one specific span)

.intlFlag { line-height: 42px; }

Here is how it displayed for me

enter image description here

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

In addition of Stack: to avoid floating container on keyboard, use this

return Scaffold(
    appBar: getAppBar(title),
    resizeToAvoidBottomInset: false,
    body:

How to combine two lists in R

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

# you can do
c(l1, l2)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with do.call, eg:

do.call(c, list(l1, l2))

Requery a subform from another form?

Just discovered that if the source table for a subform is updated using adodb, it takes a while until the requery can find the updated information.

In my case, I was adding some records with 'dbconn.execute "sql" ' and wondered why the requery command in vba doesn't seem to work. When I was debugging, the requery worked. Added a 2-3 second wait in the code before requery just to test made a difference.

But changing to 'currentdb.execute "sql" ' fixed the problem immediately.

How to open new browser window on button click event?

You can use some code like this, you can adjust a height and width as per your need

    protected void button_Click(object sender, EventArgs e)
    {
        // open a pop up window at the center of the page.
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
    }

Image convert to Base64

Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!

Usage: input is your nameId input has file image

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

  if (image && image[0]) {
    const reader = new FileReader();

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

Example: converImageToBase64('yourFileInputId')

https://codepen.io/mariohandsome/pen/yLadmVb

How to remove a Gitlab project?

  • Click on Project you want to delete.
  • Click Setting on right buttom corner.
  • click general than go to advance
  • than remove project

How to print full stack trace in exception?

1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.

public string GetAllFootprints(Exception x)
{
        var st = new StackTrace(x, true);
        var frames = st.GetFrames();
        var traceString = new StringBuilder();

        foreach (var frame in frames)
        {
            if (frame.GetFileLineNumber() < 1)
                continue;

            traceString.Append("File: " + frame.GetFileName());
            traceString.Append(", Method:" + frame.GetMethod().Name);
            traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
            traceString.Append("  -->  ");
        }

        return traceString.ToString();
}

2. Call Method: You can call the method like this.

try
{
    // code part which you want to catch exception on it
}
catch(Exception ex)
{
    Debug.Writeline(GetAllFootprints(ex));
}

3. Get the Result:

File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29  -->  
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16  --> 

how to add script inside a php code?

One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.

  <script type="text/javascript" src="menu_1.0.17.js"></script>

An alternative in PHP would be to create a function called insertScript.

  <?php insertScript("menu.js") ?>

RSA: Get exponent and modulus given a public key

Apart from the above answers, we can use asn1parse to get the values

$ openssl asn1parse -i -in pub0.der -inform DER -offset 24
0:d=0  hl=4 l= 266 cons: SEQUENCE
4:d=1  hl=4 l= 257 prim:  INTEGER           :C9131430CCE9C42F659623BDC73A783029A23E4BA3FAF74FE3CF452F9DA9DAF29D6F46556E423FB02610BC4F84E19F87333EAD0BB3B390A3EFA7FB392E935065D80A27589A21CA051FA226195216D8A39F151BD0334965551744566AD3DAEB53EBA27783AE08BAAACA406C27ED8BE614518C8CD7D14BBE7AFEBE1D8D03374DAE7B7564CF1182A7B3BA115CD9416AB899C5803388EE66FA3676750A77AC870EDA027DC95E57B9B4E864A3C98F1BA99A4726C085178EA8FC6C549BE5EDF970CCB8D8F9AEDEE3F5CFDE574327D05ED04060B2525FB6711F1D78254FF59089199892A9ECC7D4E4950E0CD2246E1E613889722D73DB56B24E57F3943E11520776BC4F
265:d=1  hl=2 l= 3 prim:  INTEGER           :010001

Now, to get to this offset,we try the default asn1parse

$ openssl asn1parse -i -in pub0.der -inform DER
 0:d=0  hl=4 l= 290 cons: SEQUENCE
 4:d=1  hl=2 l=  13 cons:  SEQUENCE
 6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
17:d=2  hl=2 l=   0 prim:   NULL
19:d=1  hl=4 l= 271 prim:  BIT STRING

We need to get to the BIT String part, so we add the sizes

depth_0_header(4) + depth_1_full_size(2 + 13) + Container_1_EOC_bit + BIT_STRING_header(4) = 24

This can be better visialized at: ASN.1 Parser, if you hover at tags, you will see the offsets

Another amazing resource: Microsoft's ASN.1 Docs

Why is setTimeout(fn, 0) sometimes useful?

Preface:

Some of the other answers are correct but don't actually illustrate what the problem being solved is, so I created this answer to present that detailed illustration.

As such, I am posting a detailed walk-through of what the browser does and how using setTimeout() helps. It looks longish but is actually very simple and straightforward - I just made it very detailed.

UPDATE: I have made a JSFiddle to live-demonstrate the explanation below: http://jsfiddle.net/C2YBE/31/ . Many thanks to @ThangChung for helping to kickstart it.

UPDATE2: Just in case JSFiddle web site dies, or deletes the code, I added the code to this answer at the very end.


DETAILS:

Imagine a web app with a "do something" button and a result div.

The onClick handler for "do something" button calls a function "LongCalc()", which does 2 things:

  1. Makes a very long calculation (say takes 3 min)

  2. Prints the results of calculation into the result div.

Now, your users start testing this, click "do something" button, and the page sits there doing seemingly nothing for 3 minutes, they get restless, click the button again, wait 1 min, nothing happens, click button again...

The problem is obvious - you want a "Status" DIV, which shows what's going on. Let's see how that works.


So you add a "Status" DIV (initially empty), and modify the onclick handler (function LongCalc()) to do 4 things:

  1. Populate the status "Calculating... may take ~3 minutes" into status DIV

  2. Makes a very long calculation (say takes 3 min)

  3. Prints the results of calculation into the result div.

  4. Populate the status "Calculation done" into status DIV

And, you happily give the app to users to re-test.

They come back to you looking very angry. And explain that when they clicked the button, the Status DIV never got updated with "Calculating..." status!!!


You scratch your head, ask around on StackOverflow (or read docs or google), and realize the problem:

The browser places all its "TODO" tasks (both UI tasks and JavaScript commands) resulting from events into a single queue. And unfortunately, re-drawing the "Status" DIV with the new "Calculating..." value is a separate TODO which goes to the end of the queue!

Here's a breakdown of the events during your user's test, contents of the queue after each event:

  • Queue: [Empty]
  • Event: Click the button. Queue after event: [Execute OnClick handler(lines 1-4)]
  • Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: [Execute OnClick handler(lines 2-4), re-draw Status DIV with new "Calculating" value]. Please note that while the DOM changes happen instantaneously, to re-draw the corresponding DOM element you need a new event, triggered by the DOM change, that went at the end of the queue.
  • PROBLEM!!! PROBLEM!!! Details explained below.
  • Event: Execute second line in handler (calculation). Queue after: [Execute OnClick handler(lines 3-4), re-draw Status DIV with "Calculating" value].
  • Event: Execute 3rd line in handler (populate result DIV). Queue after: [Execute OnClick handler(line 4), re-draw Status DIV with "Calculating" value, re-draw result DIV with result].
  • Event: Execute 4th line in handler (populate status DIV with "DONE"). Queue: [Execute OnClick handler, re-draw Status DIV with "Calculating" value, re-draw result DIV with result; re-draw Status DIV with "DONE" value].
  • Event: execute implied return from onclick handler sub. We take the "Execute OnClick handler" off the queue and start executing next item on the queue.
  • NOTE: Since we already finished the calculation, 3 minutes already passed for the user. The re-draw event didn't happen yet!!!
  • Event: re-draw Status DIV with "Calculating" value. We do the re-draw and take that off the queue.
  • Event: re-draw Result DIV with result value. We do the re-draw and take that off the queue.
  • Event: re-draw Status DIV with "Done" value. We do the re-draw and take that off the queue. Sharp-eyed viewers might even notice "Status DIV with "Calculating" value flashing for fraction of a microsecond - AFTER THE CALCULATION FINISHED

So, the underlying problem is that the re-draw event for "Status" DIV is placed on the queue at the end, AFTER the "execute line 2" event which takes 3 minutes, so the actual re-draw doesn't happen until AFTER the calculation is done.


To the rescue comes the setTimeout(). How does it help? Because by calling long-executing code via setTimeout, you actually create 2 events: setTimeout execution itself, and (due to 0 timeout), separate queue entry for the code being executed.

So, to fix your problem, you modify your onClick handler to be TWO statements (in a new function or just a block within onClick):

  1. Populate the status "Calculating... may take ~3 minutes" into status DIV

  2. Execute setTimeout() with 0 timeout and a call to LongCalc() function.

    LongCalc() function is almost the same as last time but obviously doesn't have "Calculating..." status DIV update as first step; and instead starts the calculation right away.

So, what does the event sequence and the queue look like now?

  • Queue: [Empty]
  • Event: Click the button. Queue after event: [Execute OnClick handler(status update, setTimeout() call)]
  • Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: [Execute OnClick handler(which is a setTimeout call), re-draw Status DIV with new "Calculating" value].
  • Event: Execute second line in handler (setTimeout call). Queue after: [re-draw Status DIV with "Calculating" value]. The queue has nothing new in it for 0 more seconds.
  • Event: Alarm from the timeout goes off, 0 seconds later. Queue after: [re-draw Status DIV with "Calculating" value, execute LongCalc (lines 1-3)].
  • Event: re-draw Status DIV with "Calculating" value. Queue after: [execute LongCalc (lines 1-3)]. Please note that this re-draw event might actually happen BEFORE the alarm goes off, which works just as well.
  • ...

Hooray! The Status DIV just got updated to "Calculating..." before the calculation started!!!



Below is the sample code from the JSFiddle illustrating these examples: http://jsfiddle.net/C2YBE/31/ :

HTML code:

<table border=1>
    <tr><td><button id='do'>Do long calc - bad status!</button></td>
        <td><div id='status'>Not Calculating yet.</div></td>
    </tr>
    <tr><td><button id='do_ok'>Do long calc - good status!</button></td>
        <td><div id='status_ok'>Not Calculating yet.</div></td>
    </tr>
</table>

JavaScript code: (Executed on onDomReady and may require jQuery 1.9)

function long_running(status_div) {

    var result = 0;
    // Use 1000/700/300 limits in Chrome, 
    //    300/100/100 in IE8, 
    //    1000/500/200 in FireFox
    // I have no idea why identical runtimes fail on diff browsers.
    for (var i = 0; i < 1000; i++) {
        for (var j = 0; j < 700; j++) {
            for (var k = 0; k < 300; k++) {
                result = result + i + j + k;
            }
        }
    }
    $(status_div).text('calculation done');
}

// Assign events to buttons
$('#do').on('click', function () {
    $('#status').text('calculating....');
    long_running('#status');
});

$('#do_ok').on('click', function () {
    $('#status_ok').text('calculating....');
    // This works on IE8. Works in Chrome
    // Does NOT work in FireFox 25 with timeout =0 or =1
    // DOES work in FF if you change timeout from 0 to 500
    window.setTimeout(function (){ long_running('#status_ok') }, 0);
});

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

Please check this fiddle and let me know if you get an alert of null value. I have copied your code there and added a couple of alerts. Just like others, I also dont see a null being returned, I get an empty string. Which browser are you using?

Docker can't connect to docker daemon

Try adding the current user to docker group:

sudo usermod -aG docker $USER

Then log out and login.

Type.GetType("namespace.a.b.ClassName") returns null

Type.GetType("namespace.qualified.TypeName") only works when the type is found in either mscorlib.dll or the currently executing assembly.

If neither of those things are true, you'll need an assembly-qualified name:

Type.GetType("namespace.qualified.TypeName, Assembly.Name")

How to set an button align-right with Bootstrap?

This worked for me:

<div class="text-right">
    <button type="button">Button 1</button>
    <button type="button">Button 2</button>
</div>

Popup Message boxes

first you have to import: import javax.swing.JOptionPane; then you can call it using this:

JOptionPane.showMessageDialog(null, 
                              "ALERT MESSAGE", 
                              "TITLE", 
                              JOptionPane.WARNING_MESSAGE);

the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE. it works pretty well in a lot of ways mostly for errors.

Putting an if-elif-else statement on one line?

If you only need different expressions for different cases then this may work for you:

expr1 if condition1 else expr2 if condition2 else expr

For example:

a = "neg" if b<0 else "pos" if b>0 else "zero"

HTML - how to make an entire DIV a hyperlink?

You can add the onclick for JavaScript into the div.

<div onclick="location.href='newurl.html';">&nbsp;</div>

EDIT: for new window

<div onclick="window.open('newurl.html','mywindow');" style="cursor: pointer;">&nbsp;</div>

[Vue warn]: Property or method is not defined on the instance but referenced during render

Should anybody land with the same silly problem I had, make sure your component has the 'data' property spelled correctly. (eg. data, and not date)

<template>
    <span>{{name}}</span>
</template>

<script>
export default {
  name: "MyComponent",
  data() {
    return {
      name: ""
    };
  }
</script>

How to get the first non-null value in Java?

Object coalesce(Object... objects)
{
    for(Object o : object)
        if(o != null)
            return o;
    return null;
}

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

Overlaying a DIV On Top Of HTML 5 Video

Here is a stripped down example, using as little HTML markup as possible.

The Basics

  • The overlay is provided by the :before pseudo element on the .content container.

  • No z-index is required, :before is naturally layered over the video element.

  • The .content container is position: relative so that the position: absolute overlay is positioned in relation to it.

  • The overlay is stretched to cover the entire .content div width with left / right / bottom and left set to 0.

  • The width of the video is controlled by the width of its container with width: 100%

The Demo

_x000D_
_x000D_
.content {
  position: relative;
  width: 500px;
  margin: 0 auto;
  padding: 20px;
}
.content video {
  width: 100%;
  display: block;
}
.content:before {
  content: '';
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
_x000D_
<div class="content">
  <video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
_x000D_
_x000D_

MySQL IF ELSEIF in select query

IF() in MySQL is a ternary function, not a control structure -- if the condition in the first argument is true, it returns the second argument; otherwise, it returns the third argument. There is no corresponding ELSEIF() function or END IF keyword.

The closest equivalent to what you've got would be something like:

IF(qty_1<='23', price,
  IF('23'>qty_1 && qty_2<='23', price_2,
    IF('23'>qty_2 && qty_3<='23', price_3,
      IF('23'>qty_3, price_4, 1)
    )
  )
)

The conditions don't all make sense to me (it looks as though some of them may be inadvertently reversed?), but without knowing what exactly you're trying to accomplish, it's hard for me to fix that.

How to output (to a log) a multi-level array in a format that is human-readable?

Drupal's Devel module has other useful functions including ones that can print formatted arrays and objects to log files. See the guide at http://ratatosk.net/drupal/tutorials/debugging-drupal.html

dd()

Logs any variable to a file named “drupal_debug.txt” in the site’s temp directory. All output from this function is appended to the log file, making it easy to see how the contents of a variable change as you modify your code.

If you’re using Mac OS X you can use the Logging Console to monitor the contents of the log file.

If you’re using a flavor of Linux you can use the command “tail -f drupal_debug.txt” to watch the data being logged to the file.

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

There can be one more reason for such behavior - you delete current working directory.

For example:

# in terminal #1
cd /home/user/myJavaApp

# in terminal #2
rm -rf /home/user/myJavaApp

# in terminal #1
java -jar myJar.jar

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

python-pandas and databases like mysql

The same syntax works for Ms SQL server using podbc also.

import pyodbc
import pandas.io.sql as psql

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=mydb;UID=username;PWD=password') 
cursor = cnxn.cursor()
sql = ("""select * from mytable""")

df = psql.frame_query(sql, cnxn)
cnxn.close()

What is the Linux equivalent to DOS pause?

Try this:

function pause(){
   read -p "$*"
}

Runnable with a parameter?

You could put it in a function.

String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);

private Runnable createRunnable(final String paramStr){

    Runnable aRunnable = new Runnable(){
        public void run(){
            someFunc(paramStr);
        }
    };

    return aRunnable;

}

(When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)

Checking if jquery is loaded using Javascript

if ('undefined' == typeof window.jQuery) {
    // jQuery not present
} else {
    // jQuery present
}

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

Check if element is clickable in Selenium Java

the class attribute contains disabled when the element is not clickable.

WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
    webElement.click();
}

How to skip to next iteration in jQuery.each() util?

What they mean by non-false is:

return true;

So this code:

_x000D_
_x000D_
var arr = ["one", "two", "three", "four", "five"];_x000D_
$.each(arr, function(i) {_x000D_
  if (arr[i] == 'three') {_x000D_
    return true;_x000D_
  }_x000D_
  console.log(arr[i]);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

will log one, two, four, five.

How to calculate the difference between two dates using PHP?

I'd like to bring a slightly different perspective, which seemingly hasn't been mentioned.

You could solve this problem (just like any other) in a declarative way. The point is asking what you need, not how to get there.

Here, you need a difference. But what is that difference? It's an interval, as already mentioned in the most upvoted answer. The thing is how to get it. Instead of explicitly invoking diff() method, you could just create an interval by start date and finish date, that is, by date range:

$startDate = '2007-03-24';
$endDate = '2009-06-26';
$range = new FromRange(new ISO8601DateTime($startDate), new ISO8601DateTime($endDate));

All the intricacies such as a leap year and all are already taken care of. Now when you have an interval with fixed start datetime, you can get a human-readable version:

var_dump((new HumanReadable($range))->value());

It outputs exactly what you need.

If you need some customized format, it's not a problem either. You can use a ISO8601Formatted class which accepts a callable with six arguments: year, month, day, hour, minute, and second:

(new ISO8601Formatted(
    new FromRange(
        new ISO8601DateTime('2017-07-03T14:27:39+00:00'),
        new ISO8601DateTime('2018-07-05T14:27:39.235487+00:00')
    ),
    function (int $years, int $months, int $days, int $hours, int $minutes, int $seconds) {
        return $years >= 1 ? 'More than a year' : 'Less than a year';
    }
))
    ->value();

It outputs More than a year.

For more about this approach, take a look at a quick start entry.

How to compare two date values with jQuery

Once you are able to parse those strings into a Date object comparing them is easy (Using the < operator). Parsing the dates will depend on the format. You may take a look at Datejs which might simplify this task.

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Swift 4.x

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        let writingDirection = UIApplication.shared.userInterfaceLayoutDirection
        let factor: CGFloat = writingDirection == .leftToRight ? 1 : -1

        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount*factor, bottom: 0, right: insetAmount*factor)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount*factor, bottom: 0, right: -insetAmount*factor)
        self.contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}

Usage:

button.centerTextAndImage(spacing: 10.0)

WHERE Clause to find all records in a specific month

As an alternative to the MONTH and YEAR functions, a regular WHERE clause will work too:

select *
from yourtable
where '2009-01-01' <= datecolumn and datecolumn < '2009-02-01'

How do I write data to csv file in columns and rows from a list in python?

>>> import csv
>>> with open('test.csv', 'wb') as f:
...     wtr = csv.writer(f, delimiter= ' ')
...     wtr.writerows( [[1, 2], [2, 3], [4, 5]])
...
>>> with open('test.csv', 'r') as f:
...     for line in f:
...         print line,
...
1 2 <<=== Exactly what you said that you wanted.
2 3
4 5
>>>

To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.

What does $@ mean in a shell script?

From the manual:

@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Android: How do I get string from resources using its name?

Verify if your packageName is correct. You have to refer for the root package of your Android application.

private String getStringResourceByName(String aString) {
      String packageName = getPackageName();
      int resId = getResources().getIdentifier(aString, "string", packageName);
      return getString(resId);
    }

How to retrieve the last autoincremented ID from a SQLite table?

According to Android Sqlite get last insert row id there is another query:

SELECT rowid from your_table_name order by ROWID DESC limit 1

Android Studio: Gradle: error: cannot find symbol variable

If you are using a String build config field in your project, this might be the case:

buildConfigField "String", "source", "play"

If you declare your String like above it will cause the error to happen. The fix is to change it to:

buildConfigField "String", "source", "\"play\""

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also change the index name in column definitions within a create_table block (such as you get from the migration generator).

create_table :studies do |t|
  t.references :user, index: {:name => "index_my_shorter_name"}
end

Android Emulator sdcard push error: Read-only file system

I guess, you didn't insert memory size at the time of creating avd. you can do that by editing the avd. screenshot

PHP mysql insert date format

Try Something like this..

echo "The time is " . date("2:50:20");
$d=strtotime("3.00pm july 28 2014");
echo "Created date is " . date("d-m-y h:i:sa",$d);

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

The application that you are running is blocked because the application does not comply with security guidelines implemented in Java 7 Update 51

Add one day to date in javascript

I think what you are looking for is:

startDate.setDate(startDate.getDate() + 1);

Also, you can have a look at Moment.js

A javascript date library for parsing, validating, manipulating, and formatting dates.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Probably, you need to insert schema identifier here:

in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");

How to find the path of Flutter SDK

The Flutter SDK path is certainly defined in a place where you can check it or change it, whether you created the project or not. Under Settings > Languages & Frameworks there should be a Flutter section. I found it by using the handy search bar in the Settings menu.

At the top of the Languages & Frameworks > Flutter is the Flutter SDK Path.

This is assuming that Flutter/Dart have already been installed under Plugins.

How to define an empty object in PHP

Here an example with the iteration:

<?php
$colors = (object)[];
$colors->red = "#F00";
$colors->slateblue = "#6A5ACD";
$colors->orange = "#FFA500";

foreach ($colors as $key => $value) : ?>
    <p style="background-color:<?= $value ?>">
        <?= $key ?> -> <?= $value ?>
    </p>
<?php endforeach; ?>

Get Time from Getdate()

Let's try this

select convert(varchar, getdate(), 108) 

Just try a few moment ago

How to know if .keyup() is a character key (jQuery)

This helped for me:

$("#input").keyup(function(event) {
        //use keyup instead keypress because:
        //- keypress will not work on backspace and delete
        //- keypress is called before the character is added to the textfield (at least in google chrome) 
        var searchText = $.trim($("#input").val());

        var c= String.fromCharCode(event.keyCode);
        var isWordCharacter = c.match(/\w/);
        var isBackspaceOrDelete = (event.keyCode == 8 || event.keyCode == 46);

        // trigger only on word characters, backspace or delete and an entry size of at least 3 characters
        if((isWordCharacter || isBackspaceOrDelete) && searchText.length > 2)
        { ...

difference between throw and throw new Exception()

throw re-throws the caught exception, retaining the stack trace, while throw new Exception loses some of the details of the caught exception.

You would normally use throw by itself to log an exception without fully handling it at that point.

BlackWasp has a good article sufficiently titled Throwing Exceptions in C#.

JPA and Hibernate - Criteria vs. JPQL or HQL

This post is quite old. Most answers talk about Hibernate criteria, not JPA criteria. JPA 2.1 added CriteriaDelete/CriteriaUpdate, and EntityGraph that controls what exactly to fetch. Criteria API is better since Java is OO. That is why JPA is created. When JPQL is compiled, it will be translated to AST tree(OO model) before translated to SQL.

Convert object to JSON in Android

Most people are using gson : check this

Gson gson = new Gson();
String json = gson.toJson(myObj);

Specifying ssh key in ansible playbook file

You can use the ansible.cfg file, it should look like this (There are other parameters which you might want to include):

[defaults]
inventory = <PATH TO INVENTORY FILE>
remote_user = <YOUR USER>
private_key_file =  <PATH TO KEY_FILE>

Hope this saves you some typing

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.