Programs & Examples On #Scandir

List files and directories inside the specified path

ERROR in ./node_modules/css-loader?

I am also facing the same problem, but I resolve.

npm install node-sass  

Above command work for me. As per your synario you can use the blow command.

Try 1

 npm install node-sass

Try 2

remove node_modules folder and run npm install

Try 3

npm rebuild node-sass

Try 4

npm install --save node-sass

For your ref you can go through this github link

List all the files and folders in a Directory with PHP recursive function

here I have example for that

List all the files and folders in a Directory csv(file) read with PHP recursive function

<?php

/** List all the files and folders in a Directory csv(file) read with PHP recursive function */
function getDirContents($dir, &$results = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            //$results[] = $path;
        }
    }

    return $results;
}





$files = getDirContents('/xampp/htdocs/medifree/lab');//here folder name where your folders and it's csvfile;


foreach($files as $file){
$csv_file =$file;
$foldername =  explode(DIRECTORY_SEPARATOR,$file);
//using this get your folder name (explode your path);
print_r($foldername);

if (($handle = fopen($csv_file, "r")) !== FALSE) {

fgetcsv($handle); 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
}
fclose($handle);
}

}

?>

http://myphpinformation.blogspot.in/2016/05/list-all-files-and-folders-in-directory-csv-file-read-with-php-recursive.html

How to display images from a folder using php - PHP

You had a mistake on the statement below. Use . not ,

echo '<img src="', $dir, '/', $file, '" alt="', $file, $

to

echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $

and

echo 'Directory \'', $dir, '\' not found!';

to

echo 'Directory \''. $dir. '\' not found!';

Pull all images from a specified directory and then display them

In case anyone is looking for recursive.

<?php

echo scanDirectoryImages("images");

/**
 * Recursively search through directory for images and display them
 * 
 * @param  array  $exts
 * @param  string $directory
 * @return string
 */
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
    if (substr($directory, -1) == '/') {
        $directory = substr($directory, 0, -1);
    }
    $html = '';
    if (
        is_readable($directory)
        && (file_exists($directory) || is_dir($directory))
    ) {
        $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;
                if (is_readable($path)) {
                    if (is_dir($path)) {
                        return scanDirectoryImages($path, $exts);
                    }
                    if (
                        is_file($path)
                        && in_array(end(explode('.', end(explode('/', $path)))), $exts)
                    ) {
                        $html .= '<a href="' . $path . '"><img src="' . $path
                            . '" style="max-height:100px;max-width:100px" /></a>';
                    }
                }
            }
        }
        closedir($directoryList);
    }
    return $html;
}

How to get directory size in PHP

Regarding Johnathan Sampson's Linux example, watch out when you are doing an intval on the outcome of the "du" function, if the size is >2GB, it will keep showing 2GB.

Replace:

$totalSize = intval(fgets($io, 80));

by:

strtok(fgets($io, 80), " ");

supposed your "du" function returns the size separated with space followed by the directory/file name.

How to make a div have a fixed size?

<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60 

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });    

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>

How can I make my own event in C#?

Here's an example of creating and using an event with C#

using System;

namespace Event_Example
{
    //First we have to define a delegate that acts as a signature for the
    //function that is ultimately called when the event is triggered.
    //You will notice that the second parameter is of MyEventArgs type.
    //This object will contain information about the triggered event.
    public delegate void MyEventHandler(object source, MyEventArgs e);

    //This is a class which describes the event to the class that recieves it.
    //An EventArgs class must always derive from System.EventArgs.
    public class MyEventArgs : EventArgs
    {
        private string EventInfo;
        public MyEventArgs(string Text)
        {
            EventInfo = Text;
        }
        public string GetInfo()
        {
            return EventInfo;
        }
    }

    //This next class is the one which contains an event and triggers it
    //once an action is performed. For example, lets trigger this event
    //once a variable is incremented over a particular value. Notice the
    //event uses the MyEventHandler delegate to create a signature
    //for the called function.
    public class MyClass
    {
        public event MyEventHandler OnMaximum;
        private int i;
        private int Maximum = 10;
        public int MyValue
        {
            get
            {
                return i;
            }
            set
            {
                if(value <= Maximum)
                {
                    i = value;
                }
                else
                {
                    //To make sure we only trigger the event if a handler is present
                    //we check the event to make sure it's not null.
                    if(OnMaximum != null)
                    {
                        OnMaximum(this, new MyEventArgs("You've entered " +
                            value.ToString() +
                            ", but the maximum is " +
                            Maximum.ToString()));
                    }
                }
            }
        }
    }

    class Program
    {
        //This is the actual method that will be assigned to the event handler
        //within the above class. This is where we perform an action once the
        //event has been triggered.
        static void MaximumReached(object source, MyEventArgs e)
        {
            Console.WriteLine(e.GetInfo());
        }

        static void Main(string[] args)
        {
            //Now lets test the event contained in the above class.
            MyClass MyObject = new MyClass();
            MyObject.OnMaximum += new MyEventHandler(MaximumReached);

            for(int x = 0; x <= 15; x++)
            {
                MyObject.MyValue = x;
            }

            Console.ReadLine();
        }
    }
}

jQuery if Element has an ID?

Like this:

var $aWithId = $('.parent a[id]');

Following OP's comment, test it like this:

if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)

Will return all anchor tags inside elements with class parent which have an attribute ID specified

Selecting multiple columns with linq query and lambda expression

        Object AccountObject = _dbContext.Accounts
                                   .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
                                   .Where(x => x.usr.EmailAddress == key1)
                                   .Where(x => x.usr.Hash == key2)
                                   .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
                                   .SingleOrDefault();

Why should a Java class implement comparable?

Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method compareTo in order to know how (attributes) we want to compare instances.

Dog class:

package test;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Dog d1 = new Dog("brutus");
        Dog d2 = new Dog("medor");
        Dog d3 = new Dog("ara");
        Dog[] dogs = new Dog[3];
        dogs[0] = d1;
        dogs[1] = d2;
        dogs[2] = d3;

        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * brutus
         * medor
         * ara
         */

        Arrays.sort(dogs, Dog.NameComparator);
        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * ara
         * medor
         * brutus
         */

    }
}

Main class:

package test;

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Dog d1 = new Dog("brutus");
        Dog d2 = new Dog("medor");
        Dog d3 = new Dog("ara");
        Dog[] dogs = new Dog[3];
        dogs[0] = d1;
        dogs[1] = d2;
        dogs[2] = d3;

        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * brutus
         * medor
         * ara
         */

        Arrays.sort(dogs, Dog.NameComparator);
        for (int i = 0; i < 3; i++) {
            System.out.println(dogs[i].getName());
        }
        /**
         * Output:
         * ara
         * medor
         * brutus
         */

    }
}

Here is a good example how to use comparable in Java:

http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The IEnumerable<T> interface does not include an indexer, you're probably confusing it with IList<T>

If the object really is an IList<T> (e.g. List<T> or an array T[]), try making the reference to it of type IList<T> too.

Otherwise, you can use myEnumerable.ElementAt(index) which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>s . Note that unless the (run-time) object implements IList<T>, this will cause all of the first index + 1 items to be enumerated, with all but the last being discarded.

EDIT: As an explanation, IEnumerable<T> is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T> must support all these cases, indexers are excluded from its definition.

How to get column by number in Pandas?

One is a column (aka Series), while the other is a DataFrame:

In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])

In [2]: df
Out[2]:
   a  b
0  1  2
1  3  4

The column 'b' (aka Series):

In [3]: df['b']
Out[3]:
0    2
1    4
Name: b, dtype: int64

The subdataframe with columns (position) in [1]:

In [4]: df[[1]]
Out[4]:
   b
0  2
1  4

Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:

In [5]: df.iloc[:, [1]]
Out[5]:
   b
0  2
1  4

In [6]: df.loc[:, ['b']]
Out[6]:
   b
0  2
1  4

In [7]: df.loc[:, 'b']
Out[7]:
0    2
1    4
Name: b, dtype: int64

Are PHP short tags acceptable to use?

If you care about XSS then you should use <?= htmlspecialchars(…) ?> most of the time, so a short tag doesn't make a big difference.

Even if you shorten echo htmlspecialchars() to h(), it's still a problem that you have to remember to add it almost every time (and trying to keep track which data is pre-escaped, which is unescaped-but-harmless only makes mistakes more likely).

I use a templating engine that is secure by default and writes <?php tags for me.

URL Encoding using C#

Since .NET Framework 4.5 and .NET Standard 1.0 you should use WebUtility.UrlEncode. Advantages over alternatives:

  1. It is part of .NET Framework 4.5+, .NET Core 1.0+, .NET Standard 1.0+, UWP 10.0+ and all Xamarin platforms as well. HttpUtility, while being available in .NET Framework earlier (.NET Framework 1.1+), becomes available on other platforms much later (.NET Core 2.0+, .NET Standard 2.0+) and it still unavailable in UWP (see related question).

  2. In .NET Framework, it resides in System.dll, so it does not require any additional references, unlike HttpUtility.

  3. It properly escapes characters for URLs, unlike Uri.EscapeUriString (see comments to drweb86's answer).

  4. It does not have any limits on the length of the string, unlike Uri.EscapeDataString (see related question), so it can be used for POST requests, for example.

Display exact matches only with grep

Try this:

Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

For usages of Write-Host, PSScriptAnalyzer produces the following diagnostic:

Avoid using Write-Host because it might not work in all hosts, does not work when there is no host, and (prior to PS 5.0) cannot be suppressed, captured, or redirected. Instead, use Write-Output, Write-Verbose, or Write-Information.

See the documentation behind that rule for more information. Excerpts for posterity:

The use of Write-Host is greatly discouraged unless in the use of commands with the Show verb. The Show verb explicitly means "show on the screen, with no other possibilities".

Commands with the Show verb do not have this check applied.

Jeffrey Snover has a blog post Write-Host Considered Harmful in which he claims Write-Host is almost always the wrong thing to do because it interferes with automation and provides more explanation behind the diagnostic, however the above is a good summary.

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

How to use a typescript enum value in an Angular2 ngSwitch statement

You can create a reference to the enum in your component class (I just changed the initial character to be lower-case) and then use that reference from the template (plunker):

import {Component} from 'angular2/core';

enum CellType {Text, Placeholder}
class Cell {
  constructor(public text: string, public type: CellType) {}
}
@Component({
  selector: 'my-app',
  template: `
    <div [ngSwitch]="cell.type">
      <div *ngSwitchCase="cellType.Text">
        {{cell.text}}
      </div>
      <div *ngSwitchCase="cellType.Placeholder">
        Placeholder
      </div>
    </div>
    <button (click)="setType(cellType.Text)">Text</button>
    <button (click)="setType(cellType.Placeholder)">Placeholder</button>
  `,
})
export default class AppComponent {

  // Store a reference to the enum
  cellType = CellType;
  public cell: Cell;

  constructor() {
    this.cell = new Cell("Hello", CellType.Text)
  }

  setType(type: CellType) {
    this.cell.type = type;
  }
}

Reorder / reset auto increment primary key

The best choice is to alter the column and remove the auto_increment attribute. Then issue another alter statement and put auto_increment back onto the column. This will reset the count to the max+1 of the current rows and thus preserve foreign key references back to this table, from other tables in your database, or any other key usage for that column.

react-native: command not found

In case anyone has this problem, I had a similar problem to qix, but more nuanced.

New shell terminals would default to a different version of node. I would change my terminal to the node I wanted, but when the bundle script run, it ran in a new shell, and it got the default version which did not have react-native installed.

I used nvm alias default x.x.x so that new shells would inherit the default version I wanted.

Why does "return list.sort()" return None, not the list?

Python has two kinds of sorts: a sort method (or "member function") and a sort function. The sort method operates on the contents of the object named -- think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.

Given a list of integers named l the list itself will be reordered if we call l.sort():

>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]

This method has no return value. But what if we try to assign the result of l.sort()?

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None

r now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don't forget again).

The function sorted(), on the other hand, will not do anything to the contents of l, but will return a new, sorted list with the same contents as l:

>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]

Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:

>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]

How to create separate AngularJS controller files?

What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:

app.js

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

myCtrl.js

app.controller("myCtrl", function($scope) { ..});

html

<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.

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

To avoid hyphenation in already hyphenated word I used non-breaking space ~ in combination with backward space \!. For example, command

3~\!\!\!\!-~\!\!\!D

used in the text, suppress hyphenation in word 3-D. Probably not the best solution, but it worked for me!

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

Disable ScrollView Programmatically?

As you can see in the documentation, you cannot set the visibility to false. In your case you should probably use:

scrollview.setVisibility(Visibility.GONE);

Read user input inside a loop

Read from the controlling terminal device:

read input </dev/tty

more info: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

Where are my postgres *.conf files?

Run

sudo updatedb

followed by

locate postgresql.conf

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

Color a table row with style="color:#fff" for displaying in an email

Try to use the <font> tag

?<table> 
    <thead> 
        <tr> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

But I think this should work, too:

?<table> 
    <thead> 
        <tr> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

EDIT:

Crossbrowser solution:

use capitals in HEX-color.

<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

Create an empty list in python with certain size

Not technically a list but similar to a list in terms of functionality and it's a fixed length

from collections import deque
my_deque_size_10 = deque(maxlen=10)

If it's full, ie got 10 items then adding another item results in item @index 0 being discarded. FIFO..but you can also append in either direction. Used in say

  • a rolling average of stats
  • piping a list through it aka sliding a window over a list until you get a match against another deque object.

If you need a list then when full just use list(deque object)

Releasing memory in Python

I'm guessing the question you really care about here is:

Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?

No, there is not. But there is an easy workaround: child processes.

If you need 500MB of temporary storage for 5 minutes, but after that you need to run for another 2 hours and won't touch that much memory ever again, spawn a child process to do the memory-intensive work. When the child process goes away, the memory gets released.

This isn't completely trivial and free, but it's pretty easy and cheap, which is usually good enough for the trade to be worthwhile.

First, the easiest way to create a child process is with concurrent.futures (or, for 3.1 and earlier, the futures backport on PyPI):

with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
    result = executor.submit(func, *args, **kwargs).result()

If you need a little more control, use the multiprocessing module.

The costs are:

  • Process startup is kind of slow on some platforms, notably Windows. We're talking milliseconds here, not minutes, and if you're spinning up one child to do 300 seconds' worth of work, you won't even notice it. But it's not free.
  • If the large amount of temporary memory you use really is large, doing this can cause your main program to get swapped out. Of course you're saving time in the long run, because that if that memory hung around forever it would have to lead to swapping at some point. But this can turn gradual slowness into very noticeable all-at-once (and early) delays in some use cases.
  • Sending large amounts of data between processes can be slow. Again, if you're talking about sending over 2K of arguments and getting back 64K of results, you won't even notice it, but if you're sending and receiving large amounts of data, you'll want to use some other mechanism (a file, mmapped or otherwise; the shared-memory APIs in multiprocessing; etc.).
  • Sending large amounts of data between processes means the data have to be pickleable (or, if you stick them in a file or shared memory, struct-able or ideally ctypes-able).

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

How to get the current taxonomy term ID (not the slug) in WordPress?

See wp_get_post_terms(), you'd do something like so:

global $post;
$terms = wp_get_post_terms( $post->ID, 'YOUR_TAXONOMY_NAME',array('fields' => 'ids') );

print_r($terms);

Loop through checkboxes and count each one checked or unchecked

Using Selectors

You can get all checked checkboxes like this:

var boxes = $(":checkbox:checked");

And all non-checked like this:

var nboxes = $(":checkbox:not(:checked)");

You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.

Serialize

jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:

single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2

This will enable you to keep the information for which elements were checked as well.

event.preventDefault() function not working in IE

if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}

Tested on IE 9 and Chrome.

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

 TimeZone tz = TimeZone.getDefault();  
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

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

Android Studio - debug keystore

Android Studio debug.keystore file path depend on environment variable ANDROID_SDK_HOME.

If ANDROID_SDK_HOME defined, then file placed in SDK's subfolder named .android .
When not defined, then keystore placed at user home path in same subfolder:
- %HOMEPATH%\.android\ on Windows
- $HOME/.android/ on Linux

Database Diagram Support Objects cannot be Installed ... no valid owner

1.Right click on your Database , 2.Then select properties . 3.Select the option in compatibility levels choose sql 2008[100] if you are working with Microsoft sql 2008.

4.Then select the file and write ( sa ) in owner`s textbox

100% works for me.

Remove multiple objects with rm()

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

How to make sure docker's time syncs with that of the host?

Docker Usage

Here's a complete example which builds a docker image for a go app in a multistage build. It shows how to include the timezone in your image.

FROM golang:latest as builder

WORKDIR /app

ENV GO111MODULE=on \
    CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

COPY go.mod .
COPY go.sum .

RUN go mod download

COPY . .

RUN go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o main

### Certs
FROM alpine:latest as locals

RUN apk --update --no-cache add ca-certificates

RUN apk add --no-cache tzdata

### App
FROM scratch 

WORKDIR /root/

COPY --from=locals /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt

COPY --from=builder app/main .

COPY --from=builder app/templates ./templates

COPY --from=locals /usr/share/zoneinfo /usr/share/zoneinfo

ENV TZ=Asia/Singapore

EXPOSE 8000

CMD ["./main"]

Get name of current class?

You can access it by the class' private attributes:

cls_name = self.__class__.__name__

EDIT:

As said by Ned Batcheler, this wouldn't work in the class body, but it would in a method.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
FROM
(......)SA
WHERE......

How do I override nested NPM dependency versions?

You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.

I've just done this in a grunt project of ours. We needed a newer version of connect, since 2.7.3. was causing trouble for us. So I created a file named npm-shrinkwrap.json:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

npm should automatically pick it up while doing the install for the project.

(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)

How to get .pem file from .key and .crt files?

I was trying to go from godaddy to app engine. What did the trick was using this line:

openssl req -new -newkey rsa:2048 -nodes -keyout name.unencrypted.priv.key -out name.csr

Exactly as is, but replacing name with my domain name (not that it really even mattered)

And I answered all the questions pertaining to common name / organization as www.name.com

Then I opened the csr, copied it, pasted it in go daddy, then downloaded it, unzipped it, navigated to the unzipped folder with the terminal and entered:

cat otherfilegodaddygivesyou.crt gd_bundle-g2-g1.crt > name.crt

Then I used these instructions from Trouble with Google Apps Custom Domain SSL, which were:

openssl rsa -in privateKey.key -text > private.pem
openssl x509 -inform PEM -in www_mydomain_com.crt > public.pem

exactly as is, except instead of privateKey.key I used name.unencrypted.priv.key, and instead of www_mydomain_com.crt, I used name.crt

Then I uploaded the public.pem to the admin console for the "PEM encoded X.509 certificate", and uploaded the private.pem for the "Unencrypted PEM encoded RSA private key"..

.. And that finally worked.

change <audio> src with javascript

Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution. Using componentWillReceiveProps I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.

@propTypes =
    element: React.PropTypes.shape({
         version: React.PropTypes.number
         params:
             React.PropTypes.shape(
                 url: React.PropTypes.string.isRequired
                 filename: React.PropTypes.string.isRequired
                 title: React.PropTypes.string.isRequired
                 ext: React.PropTypes.string.isRequired
             ).isRequired
     }).isRequired

componentWillReceiveProps: (nextProps) ->
    element = ReactDOM.findDOMNode(this)
    audio = element.querySelector('audio')
    source = audio.querySelector('source')

    # When the url changes, we refresh the component manually so it reloads the loaded file
    if nextProps.element.params?.filename? and
    nextProps.element.params.url isnt @props.element.params.url
        source.src = nextProps.element.params.url
        audio.load()

I had to do it this way, because even a change of state or a force redraw didn't work.

dropping infinite values from dataframes in pandas?

The above solution will modify the infs that are not in the target columns. To remedy that,

lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Get top 1 row of each group

I've done some timings over the various recommendations here, and the results really depend on the size of the table involved, but the most consistent solution is using the CROSS APPLY These tests were run against SQL Server 2008-R2, using a table with 6,500 records, and another (identical schema) with 137 million records. The columns being queried are part of the primary key on the table, and the table width is very small (about 30 bytes). The times are reported by SQL Server from the actual execution plan.

Query                                  Time for 6500 (ms)    Time for 137M(ms)

CROSS APPLY                                    17.9                17.9
SELECT WHERE col = (SELECT MAX(COL)…)           6.6               854.4
DENSE_RANK() OVER PARTITION                     6.6               907.1

I think the really amazing thing was how consistent the time was for the CROSS APPLY regardless of the number of rows involved.

String.equals versus ==

equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.

== operator checks if the references of both the objects are the same.

Consider the programs

String abc = "Awesome" ;
String xyz =  abc;

if(abc == xyz)
     System.out.println("Refers to same string");

Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is true.

String abc = "Hello World";
String xyz = "Hello World";

if(abc == xyz)
    System.out.println("Refers to same string");
else
    System.out.println("Refers to different strings");

if(abc.equals(xyz))
     System.out.prinln("Contents of both strings are same");
else
     System.out.prinln("Contents of strings are different");

Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.

Hope you understood the difference between == and <Object>.equals()

Thanks.

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

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

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

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

Will iOS launch my app into the background if it was force-quit by the user?

Actually if you need to test background fetch you need to enable one option in scheme:

enabling bg fetch

Another way how you can test it: simulate bg fetch

Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html

Golang read request body

I could use the GetBody from Request package.

Look this comment in source code from request.go in net/http:

GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."

GetBody func() (io.ReadCloser, error)

This way you can get the body request without make it empty.

Sample:

getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
    // Do something return err
}
http.DefaultClient.Do(request)

String contains another two strings

I just checked for a space in contains to check if the string has 2 or more words.

string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";

bool a = ?(d.contains(" ")):true:false;

if(a)
{
 Console.WriteLine(" " + d);
}

Console.Read();

How to get all elements inside "div" that starts with a known text

i have tested a sample and i would like to share this sample and i am sure it's quite help full. I have done all thing in body, first creating an structure there on click of button you will call a function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens. I have given alerts here on different level so u can test where r u now in the coding .

    <body>
    <h1>javascript to count the number of children of given child</h1>

    <div id="count">
    <span>a</span>
    <span>s</span>
    <span>d</span>
    <span>ff</span>
    <div>fsds</div>
    <p>fffff</p>
    </div>
   <button type="button" onclick="selectallelement('count')">click</button>
   <p>total element no.</p>
    <p id="sho">here</p>
  <script>

  function selectallelement(divid)
  {
 alert(divid);
 var ele = document.getElementById(divid).children;
 var match = new Array();
  var i = fillArray(ele,match);
  alert(i);
   document.getElementById('sho').innerHTML = i;
  }
 function fillArray(e1,a1)
  {
 alert("we are here");
   for(var i =0;i<e1.length;i++)
{
  if(e1[i].id.indexOf('count') == 0)
    a1.push(e1[i]);
}
return i;
   }
   </script>

 </body>

  USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS 

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

What does "select count(1) from table_name" on any database tables mean?

Difference between count(*) and count(1) in oracle?

count(*) means it will count all records i.e each and every cell BUT

count(1) means it will add one pseudo column with value 1 and returns count of all records

PowerShell: Store Entire Text File Contents in Variable

One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:

$content = ${C:file.txt}

This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:

 ${D:\path\to\file.txt} = $content

Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:

${C:file.txt} = ${C:file.txt} | select -skip 1

I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.

One final note on using this: you must use a drive designation, i.e. ${drive:filespec} as I have done in all the examples above. Without the drive (e.g. ${file.txt}) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.

How to compute the similarity between two text documents?

It's an old question, but I found this can be done easily with Spacy. Once the document is read, a simple api similarity can be used to find the cosine similarity between the document vectors.

import spacy
nlp = spacy.load('en')
doc1 = nlp(u'Hello hi there!')
doc2 = nlp(u'Hello hi there!')
doc3 = nlp(u'Hey whatsup?')

print doc1.similarity(doc2) # 0.999999954642
print doc2.similarity(doc3) # 0.699032527716
print doc1.similarity(doc3) # 0.699032527716

How to create an infinite loop in Windows batch file?

read help GOTO

and try

:again
do it
goto again

What do the different readystates in XMLHttpRequest mean, and how can I use them?

onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

status 200: "OK"

404: Page not found

What is the syntax to insert one list into another list in python?

foo = [1, 2, 3]
bar = [4, 5, 6]

foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]

http://docs.python.org/tutorial/datastructures.html

Where can I find php.ini?

There are several valid ways already mentioned for locating the php.ini file, but if you came across this page because you want to do something with it in a bash script:

path_php_ini="$(php -i | grep 'Configuration File (php.ini) Path' | grep -oP '(?<=\=\>\s).*')" echo ${path_php_ini}

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

for Laravel 5.4
for gmail


in .env file

MAIL_DRIVER=mail
MAIL_HOST=mail.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<username>@gmail.com
MAIL_PASSWORD=<password>
MAIL_ENCRYPTION=tls

in config/mail.php

'driver' => env('MAIL_DRIVER', 'mail'),

'from' => [
    'address' => env(
        'MAIL_FROM_ADDRESS', '<username>@gmail.com'
    ),
    'name' => env(
        'MAIL_FROM_NAME', '<from_name>'
    ),
],

Why does "pip install" inside Python raise a SyntaxError?

you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this

>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])

this is calling pip like pip <commands> in terminal. The commands will be seperated by spaces that you are doing there to.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

Code offset dynamic for dynamic page

var pos=$('#send').offset().top;
$('#loading').offset({ top : pos-220});

MySQL default datetime through phpmyadmin

Set the type of the field as TIMESTAMP too.

enter image description here

In Python How can I declare a Dynamic Array

In python, A dynamic array is an 'array' from the array module. E.g.

from array import array
x = array('d')          #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop()                 # returns 2.2

This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.

However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.

See https://docs.python.org/2/library/array.html for details.

How to deploy a React App on Apache web server

As said in the post, React is a browser based technology. It only renders a view in an HTML document.

To be able to have access to your "React App", you need to:

  1. Bundle your React app in a bundle
  2. Have Apache pointing to your html file in your server, and allowing access externally.

You might have all the informations here: https://httpd.apache.org/docs/trunk/getting-started.html for the Apache server, and here to make your javascript bundle https://www.codementor.io/tamizhvendan/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack-du107r9zr

Assign one struct to another in C

Yes, assignment is supported for structs. However, there are problems:

struct S {
   char * p;
};

struct S s1, s2;
s1.p = malloc(100);
s2 = s1;

Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.

Use PHP to create, edit and delete crontab jobs?

We recently prepared a mini project (PHP>=5.3) to manage the cron files for private and individual tasks. This tool connects and manages the cron files so you can use them, for example per project. Unit Tests available :-)

Sample from command line:

bin/cronman --enable /var/www/myproject/.cronfile --user www-data

Sample from API:

use php\manager\crontab\CrontabManager;

$crontab = new CrontabManager();
$crontab->enableOrUpdate('/tmp/my/crontab.txt');
$crontab->save();

Managing individual tasks from API:

use php\manager\crontab\CrontabManager;

$crontab = new CrontabManager();
$job = $crontab->newJob();
$job->on('* * * * *');
$job->onMinute('20-30')->doJob("echo foo");
$crontab->add($job);
$job->onMinute('35-40')->doJob("echo bar");
$crontab->add($job);
$crontab->save();

github: php-crontab-manager

Python Timezone conversion

# Program
import time
import os

os.environ['TZ'] = 'US/Eastern'
time.tzset()
print('US/Eastern in string form:',time.asctime()) 

os.environ['TZ'] = 'Australia/Melbourne'
time.tzset()
print('Australia/Melbourne in string form:',time.asctime())

os.environ['TZ'] = 'Asia/Kolkata'
time.tzset()
print('Asia/Kolkata in string form:',time.asctime()) 

Launch custom android application from android browser

Yeah, Chrome searches instead of looking for scheme. If you want to launch your App through URI scheme, use this cool utility App on the Play store. It saved my day :) https://play.google.com/store/apps/details?id=com.naosim.urlschemesender

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = preg_replace('/\s+/', '_', $journalName);

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).

CardView not showing Shadow in Android L

After going through the docs again, I finally found the solution.

Just add card_view:cardUseCompatPadding="true" to your CardView and shadows will appear on Lollipop devices.

What happens is, the content area in a CardView take different sizes on pre-lollipop and lollipop devices. So in lollipop devices the shadow is actually covered by the card so its not visible. By adding this attribute the content area remains the same across all devices and the shadow becomes visible.

My xml code is like :

<android.support.v7.widget.CardView
    android:id="@+id/media_card_view"
    android:layout_width="match_parent"
    android:layout_height="130dp"
    card_view:cardBackgroundColor="@android:color/white"
    card_view:cardElevation="2dp"
    card_view:cardUseCompatPadding="true"
    >
...
</android.support.v7.widget.CardView>

Is floating point math broken?

I just saw this interesting issue around floating points:

Consider the following results:

error = (2**53+1) - int(float(2**53+1))
>>> (2**53+1) - int(float(2**53+1))
1

We can clearly see a breakpoint when 2**53+1 - all works fine until 2**53.

>>> (2**53) - int(float(2**53))
0

Enter image description here

This happens because of the double-precision binary: IEEE 754 double-precision binary floating-point format: binary64

From the Wikipedia page for Double-precision floating-point format:

Double-precision binary floating-point is a commonly used format on PCs, due to its wider range over single-precision floating point, in spite of its performance and bandwidth cost. As with single-precision floating-point format, it lacks precision on integer numbers when compared with an integer format of the same size. It is commonly known simply as double. The IEEE 754 standard specifies a binary64 as having:

  • Sign bit: 1 bit
  • Exponent: 11 bits
  • Significant precision: 53 bits (52 explicitly stored)

Enter image description here

The real value assumed by a given 64-bit double-precision datum with a given biased exponent and a 52-bit fraction is

Enter image description here

or

Enter image description here

Thanks to @a_guest for pointing that out to me.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I had the same problem. Manually removing and adding the dlls did not help. ClassLibraries did not compile for all the projects and were missing in the ...\bin\Debug folder for the project [because I cleaned solution by mistake]. Since the class library did not compile that means there may be some errors somewhere in one of those sub projects.

Solution: Since my dlls were there for the ...\bin\Release folder, I tried to rebuild on Release mode and found an error on one line in one of the sub projects. Solving the error and rebuilding the solution got rid off the build error.

JPA & Criteria API - Select only specific columns

cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION")));  // HERE IS NO ERROR

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria#Constructors

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Simple URL GET/POST function in Python

Even easier: via the requests module.

import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)

To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):

import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

You can use $timeout to prevent the error.

$timeout(function () {
    var scope = angular.element($("#myController")).scope();
    scope.myMethod(); 
    scope.$scope();
}, 1);

How to restore SQL Server 2014 backup in SQL Server 2008

It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

Permission denied for relation

To grant permissions to all of the existing tables in the schema use:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema> TO <role>

To specify default permissions that will be applied to future tables use:

ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> 
  GRANT <privileges> ON TABLES TO <role>;

e.g.

ALTER DEFAULT PRIVILEGES IN SCHEMA public 
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO admin;

If you use SERIAL or BIGSERIAL columns then you will probably want to do the same for SEQUENCES, or else your INSERT will fail (Postgres 10's IDENTITY doesn't suffer from that problem, and is recommended over the SERIAL types), i.e.

ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT ALL ON SEQUENCES TO <role>;

See also my answer to PostgreSQL Permissions for Web App for more details and a reusable script.

Ref:

GRANT

ALTER DEFAULT PRIVILEGES

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

You are missing the dot on the selector, and you can use toggleClass method on jquery:

$(".result").hover(
  function () {
    $(this).toggleClass("result_hover")      
  }
);

Convert MySql DateTime stamp into JavaScript's Date format

From Andy's Answer, For AngularJS - Filter

angular
    .module('utils', [])
.filter('mysqlToJS', function () {
            return function (mysqlStr) {
                var t, result = null;

                if (typeof mysqlStr === 'string') {
                    t = mysqlStr.split(/[- :]/);

                    //when t[3], t[4] and t[5] are missing they defaults to zero
                    result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
                }

                return result;
            };
        });

How to change font size in Eclipse for Java text editors?

General ? Appearance ? Colors and Fonts ? Java Editor text font

See the image:

enter image description here

How To fix white screen on app Start up?

Just mention the transparent theme to the starting activity in the AndroidManifest.xml file.

Like:

<activity
        android:name="first Activity Name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" >
 <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
 </activity>

and extend that screen with Activity class in place of AppCompatActivity.

like :

public class SplashScreenActivity extends Activity{

  ----YOUR CODE GOES HERE----
}

How to execute powershell commands from a batch file?

untested.cmd

;@echo off
;Findstr -rbv ; %0 | powershell -c - 
;goto:sCode

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD

;:sCode 
;echo done
;pause & goto :eof

Concatenate multiple node values in xpath

If you need to join xpath-selected text nodes but can not use string-join (when you are stuck with XSL 1.0) this might help:

<xsl:variable name="x">
    <xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>

<xsl:template match="*" mode="string-join-mode">
    <xsl:apply-templates mode="string-join-mode"/>
</xsl:template>    

<xsl:template match="text()" mode="string-join-mode">
    <xsl:value-of select="."/>
</xsl:template>    

Can one do a for each loop in java in reverse order?

You can use the Collections class to reverse the list then loop.

What is the most efficient way to loop through dataframes with pandas?

Pandas is based on NumPy arrays. The key to speed with NumPy arrays is to perform your operations on the whole array at once, never row-by-row or item-by-item.

For example, if close is a 1-d array, and you want the day-over-day percent change,

pct_change = close[1:]/close[:-1]

This computes the entire array of percent changes as one statement, instead of

pct_change = []
for row in close:
    pct_change.append(...)

So try to avoid the Python loop for i, row in enumerate(...) entirely, and think about how to perform your calculations with operations on the entire array (or dataframe) as a whole, rather than row-by-row.

Difference between setTimeout with and without quotes and parentheses

What happens in reality in case you pass string as a first parameter of function

setTimeout('string',number)

is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

setTimeout(eval('string'), number)

This is

an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

So samples which you refer are not good samples, and may be given in different context or just simple typo.

If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if something is string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

LINQ query to select top five

The solution:

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

jquery get all form elements: input, textarea & select

For the record: The following snippet can help you to get details about input, textarea, select, button, a tags through a temp title when hover them.

enter image description here

$( 'body' ).on( 'mouseover', 'input, textarea, select, button, a', function() {
    var $tag = $( this );
    var $form = $tag.closest( 'form' );
    var title = this.title;
    var id = this.id;
    var name = this.name;
    var value = this.value;
    var type = this.type;
    var cls = this.className;
    var tagName = this.tagName;
    var options = [];
    var hidden = [];
    var formDetails = '';

    if ( $form.length ) {
        $form.find( ':input[type="hidden"]' ).each( function( index, el ) {
            hidden.push( "\t" + el.name + ' = ' + el.value );
        } );

        var formName = $form.prop( 'name' );
        var formTitle = $form.prop( 'title' );
        var formId = $form.prop( 'id' );
        var formClass = $form.prop( 'class' );

        formDetails +=
            "\n\nFORM NAME: " + formName +
            "\nFORM TITLE: " + formTitle +
            "\nFORM ID: " + formId +
            "\nFORM CLASS: " + formClass +
            "\nFORM HIDDEN INPUT:\n" + hidden.join( "\n" );
    }

    var tempTitle =
        "TAG: " + tagName +
        "\nTITLE: " + title +
        "\nID: " + id +
        "\nCLASS: " + cls;

    if ( 'SELECT' === tagName ) {
        $tag.find( 'option' ).each( function( index, el ) {
            options.push( el.value );
        } );

        tempTitle +=
            "\nNAME: " + name +
            "\nVALUE: " + value +
            "\nTYPE: " + type +
            "\nSELECT OPTIONS:\n\t" + options;

    } else if ( 'A' === tagName ) {
        tempTitle +=
            "\nHTML: " + $tag.html();

    } else {
        tempTitle +=
            "\nNAME: " + name +
            "\nVALUE: " + value +
            "\nTYPE: " + type;
    }

    tempTitle += formDetails;

    $tag.prop( 'title', tempTitle );
    $tag.on( 'mouseout', function() {
        $tag.prop( 'title', title );
    } )
} );

How do I get monitor resolution in Python?

To get bits per pixel:

import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32

screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);

screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))

parameters in gdi32:

#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,

How to remove duplicates from a list?

Does Customer implement the equals() contract?

If it doesn't implement equals() and hashCode(), then listCustomer.contains(customer) will check to see if the exact same instance already exists in the list (By instance I mean the exact same object--memory address, etc). If what you are looking for is to test whether or not the same Customer( perhaps it's the same customer if they have the same customer name, or customer number) is in the list already, then you would need to override equals() to ensure that it checks whether or not the relevant fields(e.g. customer names) match.

Note: Don't forget to override hashCode() if you are going to override equals()! Otherwise, you might get trouble with your HashMaps and other data structures. For a good coverage of why this is and what pitfalls to avoid, consider having a look at Josh Bloch's Effective Java chapters on equals() and hashCode() (The link only contains iformation about why you must implement hashCode() when you implement equals(), but there is good coverage about how to override equals() too).

By the way, is there an ordering restriction on your set? If there isn't, a slightly easier way to solve this problem is use a Set<Customer> like so:

Set<Customer> noDups = new HashSet<Customer>();
noDups.addAll(tmpListCustomer);
return new ArrayList<Customer>(noDups);

Which will nicely remove duplicates for you, since Sets don't allow duplicates. However, this will lose any ordering that was applied to tmpListCustomer, since HashSet has no explicit ordering (You can get around that by using a TreeSet, but that's not exactly related to your question). This can simplify your code a little bit.

Escape double quotes for JSON in Python

i know this question is old, but hopefully it will help someone. i found a great plugin for those who are using PyCharm IDE: string-manipulation that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be. for other cases, using json.dumps(string) will be the recommended solution

str_to_escape = 'my string with "double quotes" blablabla'

after_escape = 'my string with \"double quotes\" blablabla'

Git: how to reverse-merge a commit?

If you don't want to commit, or want to commit later (commit message will still be prepared for you, which you can also edit):

git revert -n <commit>

Writing Unicode text to a text file?

In Python 2.6+, you could use io.open() that is default (builtin open()) on Python 3:

import io

with io.open(filename, 'w', encoding=character_encoding) as file:
    file.write(unicode_text)

It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding) multiple times). Unlike codecs module, io module has a proper universal newlines support.

Laravel 5 route not defined, while it is?

when you execute the command

php artisan route:list

You will see all your registered routes in there in table format . Well there you see many columns like Method , URI , Name , Action .. etc.

So basically if you are using route() method that means it will accept only name column values and if you want to use URI column values you should go with url() method of laravel.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

FLAG_ACTIVITY_NEW_TASK is the problem here which initiates a new task .Just remove it & you are done.

Well I recommend you to read what every Flag does before working with them

Read this & Intent Flags here

How do I decode a string with escaped unicode?

Note that the use of unescape() is deprecated and doesn't work with the TypeScript compiler, for example.

Based on radicand's answer and the comments section below, here's an updated solution:

var string = "http\\u00253A\\u00252F\\u00252Fexample.com";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));

http://example.com

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

How can I convert a hex string to a byte array?

The following code changes the hexadecimal string to a byte array by parsing the string byte-by-byte.

public static byte[] ConvertHexStringToByteArray(string hexString)
{
    if (hexString.Length % 2 != 0)
    {
        throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
    }

    byte[] data = new byte[hexString.Length / 2];
    for (int index = 0; index < data.Length; index++)
    {
        string byteValue = hexString.Substring(index * 2, 2);
        data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
    }

    return data; 
}

Define a struct inside a class in C++

declare class & nested struct probably in some header file

class C {
    // struct will be private without `public:` keyword
    struct S {
        // members will be public without `private:` keyword
        int sa;
        void func();
    };
    void func(S s);
};

if you want to separate the implementation/definition, maybe in some CPP file

void C::func(S s) {
    // implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
    // implementation here
}

if you want to inline the implementation, other answers will do fine.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Command /usr/bin/codesign failed with exit code 1

I went to Key Access, selected the private key, and added XCode to the list of apps that can access it. That worked for me

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Bootstrap datepicker disabling past dates without current date

Please refer to the fiddle http://jsfiddle.net/Ritwika/gsvh83ry/

**With three fields having date greater than the **
<input type="text" type="text" class="form-control datepickstart" />
<input type="text" type="text" class="form-control datepickend" />
<input type="text" type="text" class="form-control datepickthird" />

var date = new Date();
 date.setDate(date.getDate()-1);
$('.datepickstart').datepicker({
 autoclose: true,
 todayHighlight: true,
 format: 'dd/mm/yyyy',
  startDate: date
});
$('.datepickstart').datepicker().on('changeDate', function() {
    var temp = $(this).datepicker('getDate');
    var d = new Date(temp);
  d.setDate(d.getDate() + 1);
  $('.datepickend').datepicker({
 autoclose: true,
 format: 'dd/mm/yyyy',
 startDate: d
}).on('changeDate', function() {
    var temp1 = $(this).datepicker('getDate');
    var d1 = new Date(temp1);
   d1.setDate(d1.getDate() + 1);
  $('.datepickthird').datepicker({
 autoclose: true,
 format: 'dd/mm/yyyy',
 startDate: d1
});
});
});

Eloquent Collection: Counting and Detect Empty

When using ->get() you cannot simply use any of the below:

if (empty($result)) { }
if (!$result) { }
if ($result) { }

Because if you dd($result); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.

To determine if there are any results you can do any of the following:

if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }

You could also use ->first() instead of ->get() on the query builder which will return an instance of the first found model, or null otherwise. This is useful if you need or are expecting only one result from the database.

$result = Model::where(...)->first();
if ($result) { ... }

Notes / References

Bonus Information

The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all() ->first() ->lists() and others). Those methods also exist on the Collection object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all()) and experimenting to see what classes it's actually returning (with help of get_class(...)). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.

How to escape a JSON string containing newline characters using JavaScript?

EDIT: Check if the api you’re interacting with is set to Content-Type: application/json, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”, instead of body: { ...normal payload }). All I had to do was change the api to Content-Type: text/plain, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.

ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

What does "#include <iostream>" do?

# indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.

So, #include is a preprocessor directive that tells the preprocessor to include header files in the program.

< > indicate the start and end of the file name to be included.

iostream is a header file that contains functions for input/output operations (cin and cout).

Now to sum it up C++ to English translation of the command, #include <iostream> is:

Dear preprocessor, please include all the contents of the header file iostream at the very beginning of this program before compiler starts the actual compilation of the code.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

What is the difference between C++ and Visual C++?

C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.

VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.

CodeIgniter - File upload required validation

I found a solution that works exactly how I want.

I changed

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');

To

$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
    $this->form_validation->set_rules('userfile', 'Document', 'required');
}

How do I call a SQL Server stored procedure from PowerShell?

Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.

SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.

http://www.databasejournal.com/features/mssql/article.php/3696731

There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:

http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

How to create a GUID / UUID

Here's a solution dated Oct. 9, 2011 from a comment by user jed at https://gist.github.com/982883:

UUIDv4 = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}

This accomplishes the same goal as the current highest-rated answer, but in 50+ fewer bytes by exploiting coercion, recursion, and exponential notation. For those curious how it works, here's the annotated form of an older version of the function:

UUIDv4 =

function b(
  a // placeholder
){
  return a // if the placeholder was passed, return
    ? ( // a random number from 0 to 15
      a ^ // unless b is 8,
      Math.random() // in which case
      * 16 // a random number from
      >> a/4 // 8 to 11
      ).toString(16) // in hexadecimal
    : ( // or otherwise a concatenated string:
      [1e7] + // 10000000 +
      -1e3 + // -1000 +
      -4e3 + // -4000 +
      -8e3 + // -80000000 +
      -1e11 // -100000000000,
      ).replace( // replacing
        /[018]/g, // zeroes, ones, and eights with
        b // random hex digits
      )
}

Width of input type=text element

The visible width of an element is width + padding + border + outline, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width on the input, or making your div wider.

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

git diff file against its last change

This does exist, but it's actually a feature of git log:

git log -p [--follow] [-1] <path>

Note that -p can also be used to show the inline diff from a single commit:

git log -p -1 <commit>

Options used:

  • -p (also -u or --patch) is hidden deeeeeeeep in the git-log man page, and is actually a display option for git-diff. When used with log, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>. (This behavior is described in the paragraph on --full-diff, which causes the full diff of each commit to be shown.)
  • -1 shows just the most recent change to the specified file (-n 1 can be used instead of -1); otherwise, all non-zero diffs of that file are shown.
  • --follow is required to see changes that occurred prior to a rename.

As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log (or similar) to either count the number of intervening revisions or determine the hash of the commit.

To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)

Credit where credit is due:

  • I discovered log -p thanks to this answer.
  • Credit to FranciscoPuga and this answer for showing me the --follow option.
  • Credit to ChrisBetti for mentioning the -n 1 option and atatko for mentioning the -1 variant.
  • Credit to sweaver2112 for getting me to actually read the documentation and figure out what -p "means" semantically.

Get filename and path from URI from mediastore

Check below method is working awesome also Oreo 8.1 ..

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO ManualMT-generated method stub
    switch (requestCode) {
        case PICKFILE_RESULT_CODE:
            if (resultCode == RESULT_OK) {

                try {
                    FilePath = data.getData().getPath();
                    Uri selectedImageUri = data.getData();

                    if (selectedImageUri.toString().contains("storage/emulated")){
                        String[] split = selectedImageUri.toString().split("storage/");
                        FilePath = "storage/"+split[1];
                    } else {
                        FilePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
                    }

                    recyclerview.setVisibility(View.VISIBLE);

                    if (FilePath == null) {
                        FilePath = "";
                    }
                    File file = new File(FilePath);
                    reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                    image_list.add(FilePath);
                    composeImageAdapter.notifyDataSetChanged();
                } catch (Exception e){
                    Toast.makeText(ClusterCreateNote.this , e.toString(),Toast.LENGTH_SHORT).show();
                }
            }
            break;
    }

}

URI path Class:

public static class ImageFilePath {

    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri) {
        String selection = null;
        String[] selectionArgs = null;

        // DocumentProvider
        if (DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.wifAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Log.e("typetype",type);

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };

                Log.e("gddhjf",getDataColumn(context, contentUri, selection, selectionArgs));

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        if ("content".equalsIgnoreCase(uri.getScheme())) {


            if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment();
            }

            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                        .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return
                "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return
                "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

android: changing option menu items programmatically

using the following lines i have done to add the values in menu

getActivity().invalidateOptionsMenu();

try this work like a charm to me.

Splitting a dataframe string column into multiple different columns

We could use tidyr::extract()

x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)


library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#>    A     B     C     D    
#>    <chr> <chr> <chr> <chr>
#>  1 F     US    CLE   V13  
#>  2 F     US    CA6   U13  
#>  3 F     US    CA6   U13  
#>  4 F     US    CA6   U13  
#>  5 F     US    CA6   U13  
#>  6 F     US    CA6   U13  
#>  7 F     US    CA6   U13  
#>  8 F     US    CA6   U13  
#>  9 F     US    DL    U13  
#> 10 F     US    DL    U13  
#> 11 F     US    DL    U13  
#> 12 F     US    DL    Z13  
#> 13 F     US    DL    Z13

Another option is to use unglue::unglue_data()

# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#>    A  B   C   D
#> 1  F US CLE V13
#> 2  F US CA6 U13
#> 3  F US CA6 U13
#> 4  F US CA6 U13
#> 5  F US CA6 U13
#> 6  F US CA6 U13
#> 7  F US CA6 U13
#> 8  F US CA6 U13
#> 9  F US  DL U13
#> 10 F US  DL U13
#> 11 F US  DL U13
#> 12 F US  DL Z13
#> 13 F US  DL Z13

Created on 2019-09-14 by the reprex package (v0.3.0)

open read and close a file in 1 line of code

I think the most natural way for achieving this is to define a function.

def read(filename):
    f = open(filename, 'r')
    output = f.read()
    f.close()
    return output

Then you can do the following:

output = read('pagehead.section.htm')

How to get all of the IDs with jQuery?

My suggestion?

var arr = $.map($("#mydiv [id]"), function(n, i) {
  return n.id;
});

you could also do this as:

var arr = $.map($("#mydiv span"), function(n, i) {

or

var arr = $.map($("#mydiv span[id]"), function(n, i) {

or even just:

var arr = $("#mydiv [id]").map(function() {
  return this.id;
});

Lots of ways basically.

How to open an Excel file in C#?

Is this a commercial application or some hobbyist / open source software?

I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.

REST API Best practices: Where to put parameters?

One "dimension" of this topic has been left out yet it's very important: there are times when the "best practices" have to come into terms with the plaform we are implementing or augmenting with REST capabilities.

Practical example:

Many web applications nowadays implement the MVC (Model, View, Controller) architecture. They assume a certain standard path is provided, even more so when those web applications come with an "Enable SEO URLs" option.

Just to mention a fairly famous web application: an OpenCart e-commerce shop. When the admin enables the "SEO URLs" it expects said URLs to come in a quite standard MVC format like:

http://www.domain.tld/special-offers/list-all?limit=25

Where

  • special-offers is the MVC controller that shall process the URL (showing the special-offers page)

  • list-all is the controller's action or function name to call. (*)

  • limit=25 is an option, stating that 25 items will be shown per page.

(*) list-all is a fictious function name I used for clarity. In reality, OpenCart and most MVC frameworks have a default, implied (and usually omitted in the URL) index function that gets called when the user wants a default action to be performed. So the real world URL would be:

http://www.domain.tld/special-offers?limit=25

With a now fairly standard application or frameworkd structure similar to the above, you'll often get a web server that is optimized for it, that rewrites URLs for it (the true "non SEOed URL" would be: http://www.domain.tld/index.php?route=special-offers/list-all&limit=25).

Therefore you, as developer, are faced into dealing with the existing infrastructure and adapt your "best practices", unless you are the system admin, know exactly how to tweak an Apache / NGinx rewrite configuration (the latter can be nasty!) and so on.

So, your REST API would often be much better following the referring web application's standards, both for consistency with it and ease / speed (and thus budget saving).

To get back to the practical example above, a consistent REST API would be something with URLs like:

http://www.domain.tld/api/special-offers-list?from=15&limit=25

or (non SEO URLs)

http://www.domain.tld/index.php?route=api/special-offers-list?from=15&limit=25

with a mix of "paths formed" arguments and "query formed" arguments.

Disable firefox same origin policy

I realized my older answer is downvoted because I didn't specify how to disable FF's same origin policy specifically. Here I will give a more detailed answer:

Warning: This requires a re-compilation of FF, and the newly compiled version of Firefox will not be able to enable SOP again.

Check out Mozilla's Firefox's source code, find nsScriptSecurityManager.cpp in the src directory. I will use the one listed here as example: http://mxr.mozilla.org/aviarybranch/source/caps/src/nsScriptSecurityManager.cpp

Go to the function implementation nsScriptSecurityManager::CheckSameOriginURI, which is line 568 as of date 03/02/2016.

Make that function always return NS_OK.

This will disable SOP for good.

The browser addon answer by @Giacomo should be useful for most people and I have accepted that answer, however, for my personal research needs (TL;won't explain here) it is not enough and I figure other researchers may need to do what I did here to fully kill SOP.

Make footer stick to bottom of page correctly

The model being shared here is very similar to Ryan Fait's StickyFooter http://ryanfait.com/sticky-footer

Just one div is missing so far in this discussion (the model proposed here by Kenneth Palanganas worked fine for local Win81 design for about 48 hours and then in ie/chrome collapsed for unknown reason). Ryan's "push" div will satisfy some reluctant browsers. Note that px is usual, however, for liquid layout consistency, em may be preferred.

* { border: 0; margin: 0; padding: 0; }
html, body { height: 100%; }
.wrapper { height: auto !important; height: 100%; margin: 0 auto -1em; min-height: 100%; }
.footer, .push { height: 1em; }

<div class="wrapper"><p>Your website content here.</p>
<div class="push"></div>
</div>
<div class="footer"><p>This is a footer</p>
</div>

How do I access the $scope variable in browser's console using AngularJS?

To improve on jm's answer...

// Access whole scope
angular.element(myDomElement).scope();

// Access and change variable in scope
angular.element(myDomElement).scope().myVar = 5;
angular.element(myDomElement).scope().myArray.push(newItem);

// Update page to reflect changed variables
angular.element(myDomElement).scope().$apply();

Or if you're using jQuery, this does the same thing...

$('#elementId').scope();
$('#elementId').scope().$apply();

Another easy way to access a DOM element from the console (as jm mentioned) is to click on it in the 'elements' tab, and it automatically gets stored as $0.

angular.element($0).scope();

Java8: sum values from specific field of the objects in a list

In Java 8 for an Obj entity with field and getField() method you can use:

List<Obj> objs ...

Stream<Obj> notNullObjs =
  objs.stream().filter(obj -> obj.getValue() != null);

Double sum = notNullObjs.mapToDouble(Obj::getField).sum();

React-Native: Module AppRegistry is not a registered callable module

If you are using some of the examples they might not work

Here is my version for scroll view

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image
} from 'react-native';

class AwesomeProject extends Component {
  render() {
    return (
        <View>
          <ScrollView
            ref={(scrollView) => { _scrollView = scrollView; }}
            automaticallyAdjustContentInsets={false}
            onScroll={() => { console.log('onScroll!'); }}
            scrollEventThrottle={200}
            style={styles.scrollView}>
            {THUMBS.map(createThumbRow)}
          </ScrollView>
          <TouchableOpacity
            style={styles.button}
            onPress={() => { _scrollView.scrollTo({y: 0}); }}>
            <Text>Scroll to top</Text>
          </TouchableOpacity>
        </View>
    );
  }
}

var Thumb = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
    return false;
  },
  render: function() {
    return (
      <View style={styles.button}>
        <Image style={styles.img} source={{uri:this.props.uri}} />
      </View>
    );
  }
});

var THUMBS = [
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1,
'http://loremflickr.com/320/240?random='+Math.round(Math.random()*10000) + 1
];

THUMBS = THUMBS.concat(THUMBS); // double length of THUMBS
var createThumbRow = (uri, i) => <Thumb key={i} uri={uri} />;

var styles = StyleSheet.create({
  scrollView: {
    backgroundColor: '#6A85B1',
    height: 600,
  },
  horizontalScrollView: {
    height: 120,
  },
  containerPage: {
    height: 50,
    width: 50,
    backgroundColor: '#527FE4',
    padding: 5,
  },
  text: {
    fontSize: 20,
    color: '#888888',
    left: 80,
    top: 20,
    height: 40,
  },
  button: {
    margin: 7,
    padding: 5,
    alignItems: 'center',
    backgroundColor: '#eaeaea',
    borderRadius: 3,
  },
  buttonContents: {
    flexDirection: 'row',
    width: 64,
    height: 64,
  },
  img: {
    width: 321,
    height: 200,
  }
});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

mailto link with HTML body

Some things are possible, but not all, say for example you want line breaks, instead of using <br />use %0D%0A

Example:

<a href="mailto:?subject=&body=Hello,%0D%0A%0D%0AHere is the link to the PDF Brochure.%0D%0A%0D%0ATo view the brochure please click the following link: http://www.uyslist.com/yachts/brochure.pdf"><img src="images/email.png" alt="EMail PDF Brochure" /></a>                        

Can someone explain how to implement the jQuery File Upload plugin?

it's 2021 and here's a fantastically easy plugin to upload anything:

https://pqina.nl/filepond/?ref=pqina

add your element:

<input type="file" 
class="filepond"
name="filepond" 
multiple 
data-allow-reorder="true"
data-max-file-size="3MB"
data-max-files="3">

Register any additional plugins:

  FilePond.registerPlugin(
FilePondPluginImagePreview,  
FilePondPluginImageExifOrientation,  
FilePondPluginFileValidateSize,  
FilePondPluginImageEdit);

Then wire in the element:

// Select the file input and use 
// create() to turn it into a pond
FilePond.create(
  document.querySelector('input'),

  // Use Doka.js as image editor
  imageEditEditor: Doka.create({
    utils: ['crop', 'filter', 'color']
  })
);

I use this with the additional Doka image editor to upload and transform images at https://www.yoodu.co.uk

crazy simple to setup and the guys who run it are great at support.

As you can tell I'm a fanboy.

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:

FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'

(You may need something different - I guessed which user is which, but the SQL engine won't guess.)

Also, maybe you only needed one "user". Who knows?

Maintain aspect ratio of div but fill screen width and height in CSS?

There is now a new CSS property specified to address this: object-fit.

http://docs.webplatform.org/wiki/css/properties/object-fit

Browser support is still somewhat lacking (http://caniuse.com/#feat=object-fit) - currently works to some extent in most browsers except Microsoft - but given time it is exactly what was required for this question.

How to dump a table to console?

I use my own function to print the contents of a table but not sure how well it translates to your environment:

---A helper function to print a table's contents.
---@param tbl table @The table to print.
---@param depth number @The depth of sub-tables to traverse through and print.
---@param n number @Do NOT manually set this. This controls formatting through recursion.
function PrintTable(tbl, depth, n)
  n = n or 0;
  depth = depth or 5;

  if (depth == 0) then
      print(string.rep(' ', n).."...");
      return;
  end

  if (n == 0) then
      print(" ");
  end

  for key, value in pairs(tbl) do
      if (key and type(key) == "number" or type(key) == "string") then
          key = string.format("[\"%s\"]", key);

          if (type(value) == "table") then
              if (next(value)) then
                  print(string.rep(' ', n)..key.." = {");
                  PrintTable(value, depth - 1, n + 4);
                  print(string.rep(' ', n).."},");
              else
                  print(string.rep(' ', n)..key.." = {},");
              end
          else
              if (type(value) == "string") then
                  value = string.format("\"%s\"", value);
              else
                  value = tostring(value);
              end

              print(string.rep(' ', n)..key.." = "..value..",");
          end
      end
  end

  if (n == 0) then
      print(" ");
  end
end

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

Generating random numbers with normal distribution in Excel

Use the NORMINV function together with RAND():

=NORMINV(RAND(),10,7)

To keep your set of random values from changing, select all the values, copy them, and then paste (special) the values back into the same range.


Sample output (column A), 500 numbers generated with this formula:

enter image description here

Fatal error: Call to undefined function mysqli_connect()

If you host the server yourself, and that server happens to be Apache, you can also get this error even if you have uncommented extension=php_mysqli.dll in php.ini.

You also need to tell Apache where to find php.ini by using the PHPIniDir directive in Apache's httpd.conf

AddHandler application/x-httpd-php .php
PHPIniDir "<path-to-folder-where-php-ini-lives>"

Extract the first (or last) n characters of a string

You can easily obtain Right() and Left() functions starting from the Rbase package:

  • right function

    right = function (string, char) {
        substr(string,nchar(string)-(char-1),nchar(string))
    }
    
  • left function

    left = function (string,char) {
        substr(string,1,char)
    }
    

you can use those two custom-functions exactly as left() and right() in excel. Hope you will find it useful

Get a list of URLs from a site

Write a spider which reads in every html from disk and outputs every "href" attribute of an "a" element (can be done with a parser). Keep in mind which links belong to a certain page (this is common task for a MultiMap datastructre). After this you can produce a mapping file which acts as the input for the 404 handler.

Why is my toFixed() function not working?

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});

How to remove all .svn directories from my application directories

You almost had it. If you want to pass the output of a command as parameters to another one, you'll need to use xargs. Adding -print0 makes sure the script can handle paths with whitespace:

find . -type d -name .svn -print0|xargs -0 rm -rf

Greyscale Background Css Images

I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.

You can use background-blend-mode property to achieve a greyscale image:

#something {
  background-color: #fff;
  background-image: url("yourimage");
  background-blend-mode: luminosity;
}

If you want to remove the effect, just change the blend-mode to initial.

You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something.

You can also use two images, one with color and the other without and set both as background and play with other blend modes.

https://www.w3schools.com/cssref/pr_background-blend-mode.asp

It won't work on Edge though.

EDIT: I've miss the "fade" part of the question.

If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:

#something {
  background-color: rgba(255,255,255,1);
  background-image: url("yourimage");
  background-blend-mode: luminosity;
  transition: background-color 1s ease-out;
}
#something:hover {
  background-color: rgba(255,255,255,0);
}

I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

How to sort the letters in a string alphabetically in Python

You can use reduce

>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Had issues using most of the mentioned methods since textfield had not accepted keyboard input, and the mouse solution seem not complete.

This worked for to simulate a click in the field, selecting the content and replacing it with new.

     Actions actionList = new Actions(driver);
     actionList.clickAndHold(WebElement).sendKeys(newTextFieldString).
     release().build().perform();

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

Showing percentages above bars on Excel column graph

In Excel for Mac 2016 at least,if you place the labels in any spot on the graph and are looking to move them anywhere else (in this case above the bars), select:

Chart Design->Add Chart Element->Data Labels -> More Data Label Options

then you can grab each individual label and pull it where you would like it.

Splitting String and put it on int array

Something like this:

  public static void main(String[] args) {
   String N = "ABCD";
   char[] array = N.toCharArray();

   // and as you can see:
    System.out.println(array[0]);
    System.out.println(array[1]);
    System.out.println(array[2]);
  }

How to list only top level directories in Python?

You could also use os.scandir:

with os.scandir(os.getcwd()) as mydir:
    dirs = [i.name for i in mydir if i.is_dir()]

In case you want the full path you can use i.path.

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory.

How do I get a reference to the app delegate in Swift?

SWIFT < 3

Create a method in AppDelegate Class for ex

func sharedInstance() -> AppDelegate{
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }

and call it some where else for ex

let appDelegate : AppDelegate = AppDelegate().sharedInstance()

SWIFT >= 3.0

func sharedInstance() -> AppDelegate{
    return UIApplication.shared.delegate as! AppDelegate
}

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Best way to generate xml?

Using lxml:

from lxml import etree

# create XML 
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
child = etree.Element('child')
child.text = 'some text'
root.append(child)

# pretty string
s = etree.tostring(root, pretty_print=True)
print s

Output:

<root>
  <child/>
  <child>some text</child>
</root>

See the tutorial for more information.

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

How to access environment variable values?

The original question (first part) was "how to check environment variables in Python."

Here's how to check if $FOO is set:

try:  
   os.environ["FOO"]
except KeyError: 
   print "Please set the environment variable FOO"
   sys.exit(1)

Python datetime to string without microsecond component

This is the way I do it. ISO format:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'

You can replace the 'T' if you don't want ISO format:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

localhost refused to connect Error in visual studio

I was having this issue and solved it by closing all open instances of Visual Studio.

c# open a new form then close the current form?

//if Form1 is old form and Form2 is the current form which we want to open, then
{
Form2 f2 = new Form1();

this.Hide();// To hide old form i.e Form1
f2.Show();
}

Android: making a fullscreen application

Adding current working solution for 'FLAG_FULLSCREEN' is deprecated

Add the following to your theme in themes.xml

<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>

Worked perfectly for me.

Why is jquery's .ajax() method not sending my session cookie?

After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

$.ajax(fullUrl, {
    type: "GET",
    contentType: "text/plain",
    xhrFields: {
         withCredentials: true
    },
    crossDomain: true
});

How to replace blank (null ) values with 0 for all records?

If you're trying to do this with a query, then here is your answer:

SELECT ISNULL([field], 0) FROM [table]

Edit

ISNULL function was used incorrectly - this modified version uses IIF

SELECT IIF(ISNULL([field]), 0, [field]) FROM [table]

If you want to replace the actual values in the table, then you'll need to do it this way:

UPDATE [table] SET [FIELD] = 0 WHERE [FIELD] IS NULL

Single quotes vs. double quotes in Python

If the string you have contains one, then you should use the other. For example, "You're able to do this", or 'He said "Hi!"'. Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).

If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using '' for single-character strings, and "" for longer strings might help ease the transition. (Likewise for following other languages where they are not interchangeable).

The Python code I've seen in the wild tends to favour " over ', but only slightly. The one exception is that """these""" are much more common than '''these''', from what I have seen.

How do I fit an image (img) inside a div and keep the aspect ratio?

Try CSS:

img {
  object-fit: cover;
  height: 48px;
}

How to use "/" (directory separator) in both Linux and Windows in Python?

Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')

What is "Advanced" SQL?

At my previous job, we had a technical test which all candidates were asked to sit. 10ish questions, took about an hour. In all honesty though, 90% of failures could be screened out because they couldn't write an INNER JOIN statement. Not even an outer.

I'd consider that a prerequisite for any job description involving SQL and would leave well alone until that was mastered. From there though, talk to them - any further info on what they're actually looking for will, worst case scenario, be a useful list of things to learn as part of your professional development.

How to select all instances of a variable and edit variable name in Sublime

The Magic is, you have to start with an empty selection, so put your cursor in front of the word/character you want to multi-select and press Ctrl+D .

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

Jquery Value match Regex

Change it to this:

var email = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

This is a regular expression literal that is passed the i flag which means to be case insensitive.

Keep in mind that email address validation is hard (there is a 4 or 5 page regular expression at the end of Mastering Regular Expressions demonstrating this) and your expression certainly will not capture all valid e-mail addresses.

powershell - extract file name and extension

PS C:\Windows\System32\WindowsPowerShell\v1.0>split-path "H:\Documents\devops\tp-mkt-SPD-38.4.10.msi" -leaf
tp-mkt-SPD-38.4.10.msi

PS C:\Windows\System32\WindowsPowerShell\v1.0> $psversiontable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5477
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

Converting JSON to XLS/CSV in Java

You could only convert a JSON array into a CSV file.

Lets say, you have a JSON like the following :

{"infile": [{"field1": 11,"field2": 12,"field3": 13},
            {"field1": 21,"field2": 22,"field3": 23},
            {"field1": 31,"field2": 32,"field3": 33}]}

Lets see the code for converting it to csv :

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

import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSON2CSV {
    public static void main(String myHelpers[]){
        String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";

        JSONObject output;
        try {
            output = new JSONObject(jsonString);


            JSONArray docs = output.getJSONArray("infile");

            File file=new File("/tmp2/fromJSON.csv");
            String csv = CDL.toString(docs);
            FileUtils.writeStringToFile(file, csv);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }

}

Now you got the CSV generated from JSON.

It should look like this:

field1,field2,field3
11,22,33
21,22,23
31,32,33

The maven dependency was like,

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Update Dec 13, 2019:

Updating the answer, since now we can support complex JSON Arrays as well.

import java.nio.file.Files;
import java.nio.file.Paths;

import com.github.opendevl.JFlat;

public class FlattenJson {

    public static void main(String[] args) throws Exception {
        String str = new String(Files.readAllBytes(Paths.get("path_to_imput.json")));

        JFlat flatMe = new JFlat(str);

        //get the 2D representation of JSON document
        flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();

        //write the 2D representation in csv format
        flatMe.write2csv("path_to_output.csv");
    }

}

dependency and docs details are in link

Difference between JSONObject and JSONArray

The difference is the same as a (Hash)Map vs List.

JSONObject:

  • Contains named values (key->value pairs, tuples or whatever you want to call them)
    • like {ID : 1}
  • Order of elements is not important
    • a JSONObject of {id: 1, name: 'B'} is equal to {name: 'B', id: 1}.

JSONArray:

  • Contains only series values
    • like [1, 'value']
  • Order of values is important
    • array of [1,'value'] is not the same as ['value',1]

Example

JSON Object --> { "":""}

JSON Array --> [ , , , ]

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

Window vs Page vs UserControl for WPF navigation?

All depends on the app you're trying to build. Use Windows if you're building a dialog based app. Use Pages if you're building a navigation based app. UserControls will be useful regardless of the direction you go as you can use them in both Windows and Pages.

A good place to start exploring is here: http://windowsclient.net/learn

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

What is a .pid file and what does it contain?

Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>

How to change the default port of mysql from 3306 to 3360

You need to edit your my.cnf file and make sure you have the port set as in the following line:

port = 3360

Then restart your MySQL service and you should be good to go. There is no query you can run to make this change because the port is not a dynamic variable (q.v. here for MySQL documentation showing a table of all system variables).

How to list the contents of a package using YUM?

currently reopquery is integrated into dnf and yum, so typing:

dnf repoquery -l <pkg-name>

will list package contents from a remote repository (even for the packages that are not installed yet)

meaning installing a separate dnf-utils or yum-utils package is no longer required for the functionality as it is now being supported natively.


for listing installed or local (*.rpm files) packages' contents there is rpm -ql

i don't think it is possible with yum org dnf (not repoquery subcommand)

please correct me if i am wrong

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Python executable not finding libpython shared library

I installed Python 3.5 by Software Collections on CentOS 7 minimal. It all worked fine on its own, but I saw the shared library error mentioned in this question when I tried running a simple CGI script:

tail /var/log/httpd/error_log
AH01215: /opt/rh/rh-python35/root/usr/bin/python: error while loading shared libraries: libpython3.5m.so.rh-python35-1.0: cannot open shared object file: No such file or directory

I wanted a systemwide permanent solution that works for all users, so that excluded adding export statements to .profile or .bashrc files. There is a one-line solution, based on the Red Hat solutions page. Thanks for the comment that points it out:

echo 'source scl_source enable rh-python35' | sudo tee --append /etc/profile.d/python35.sh

After a restart, it's all good on the shell, but sometimes my web server still complains. There's another approach that always worked for both the shell and the server, and is more generic. I saw the solution here and then realized it's actually mentioned in one of the answers here as well! Anyway, on CentOS 7, these are the steps:

 vim /etc/ld.so.conf

Which on my machine just had:

include ld.so.conf.d/*.conf

So I created a new file:

vim /etc/ld.so.conf.d/rh-python35.conf

And added:

/opt/rh/rh-python35/root/usr/lib64/

And to manually rebuild the cache:

sudo ldconfig

That's it, scripts work fine!

This was a temporary solution, which didn't work across reboots:

sudo ldconfig /opt/rh/rh-python35/root/usr/lib64/ -v

The -v (verbose) option was just to see what was going on. I saw that it did: /opt/rh/rh-python35/root/usr/lib64: libpython3.so.rh-python35 -> libpython3.so.rh-python35 libpython3.5m.so.rh-python35-1.0 -> libpython3.5m.so.rh-python35-1.0

This particular error went away. Incidentally, I had to chown the user to apache to get rid of a permission error after that.

Note that I used find to locate the directory for the library. You could also do:

sudo yum install mlocate
sudo updatedb
locate libpython3.5m.so.rh-python35-1.0

Which on my VM returns:

/opt/rh/rh-python35/root/usr/lib64/libpython3.5m.so.rh-python35-1.0

Which is the path I need to give to ldconfig, as shown above.

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

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

see Singleton in PHP

retrieve data from db and display it in table in php .. see this code whats wrong with it?

<html>
    <head>
        <meta charset="UTF-8">
        <title>LoginDB</title>
    </head>
    <body>

        <?php
        $con=  mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
        if(!$con)
       {
           die('not connected');
       }
            $con=  mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
       ?>
        <div>
            <td>Login Page Database</td>
         <table border="1">
            <th> First Name</th>
                    <th>Last Name</th>
                    <th>UserName</th>
                     <th>Password</th>
                    <th>Gender</th>
                    <th>D.O.B.</th>
                    <th>Phone Number</th>
                    <th>Address</th>

            </tr>

        <?php

             while($row=  mysqli_fetch_array($con))
<!-- Fetch each row from signup Table  -->
             {
                 ?>
            <tr>
                <td><?php echo $row['FirstName']; ?></td>
                <td><?php echo $row['LastName']; ?></td>
                <td><?php echo $row['Username']; ?></td>
                <td><?php echo $row['Password'] ;?></td>
                <td><?php echo $row['Gender'] ;?></td>
                <td><?php echo $row['DOB'] ;?></td>
                <td><?php echo $row['PhoneNumber'] ;?></td>
                <td><?php echo $row['Address'] ;?></td>
            </tr>
        <?php
             }
             ?>
             </table>
            </div>
    </body>
</html>

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

How do I get and set Environment variables in C#?

This will work for an environment variable that is machine setting. For Users, just change to User instead.

String EnvironmentPath = System.Environment
                .GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);

Java 'file.delete()' Is not Deleting Specified File

I suspect that the problem is that the path is incorrect. Try this:

UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
    file.delete();
} else {
    System.err.println(
        "I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}

PHP Unset Array value effect on other indexes

The keys are maintained with the removed key missing but they can be rearranged by doing this:

$array = array(1,2,3,4,5);
unset($array[2]);
$arranged = array_values($array);
print_r($arranged);

Outputs:

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
)

Notice that if we do the following without rearranging:

unset($array[2]);
$array[]=3;

The index of the value 3 will be 5 because it will be pushed to the end of the array and will not try to check or replace missing index. This is important to remember when using FOR LOOP with index access.

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

how to change the default positioning of modal in bootstrap?

If you need to change the bottom position of the modal, you need to modify the max-height of the modal-body:

.modal-body {
  max-height: 75vh;
}

As other answers have said, you can adjust the right and top on the modal-dialog :

.modal-dialog {
  top: 10vh;
  right: 5vw;
}
  • "vh" means "% of view height"
  • "vw" means "% of view width"

appending list but error 'NoneType' object has no attribute 'append'

You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.

How to run a cron job on every Monday, Wednesday and Friday?

Here's my example crontab I always use as a template:

    # Use the hash sign to prefix a comment
    # +---------------- minute (0 - 59)
    # |  +------------- hour (0 - 23)
    # |  |  +---------- day of month (1 - 31)
    # |  |  |  +------- month (1 - 12)
    # |  |  |  |  +---- day of week (0 - 7) (Sunday=0 or 7)
    # |  |  |  |  |
    # *  *  *  *  *  command to be executed
    #--------------------------------------------------------------------------

To run my cron job every Monday, Wednesady and Friday at 7:00PM, the result will be:

      0 19 * * 1,3,5 nohup /home/lathonez/script.sh > /tmp/script.log 2>&1

source

What does it mean to inflate a view from an xml file?

Inflating is the process of adding a view (.xml) to activity on runtime. When we create a listView we inflate each of its items dynamically. If we want to create a ViewGroup with multiple views like buttons and textview, we can create it like so:

Button but = new Button();
but.setText ="button text";
but.background ...
but.leftDrawable.. and so on...

TextView txt = new TextView();
txt.setText ="button text";
txt.background ... and so on...

Then we have to create a layout where we can add above views:

RelativeLayout rel = new RelativeLayout();

rel.addView(but);

And now if we want to add a button in the right-corner and a textview on the bottom, we have to do a lot of work. First by instantiating the view properties and then applying multiple constraints. This is time consuming.

Android makes it easy for us to create a simple .xml and design its style and attributes in xml and then simply inflate it wherever we need it without the pain of setting constraints programatically.

LayoutInflater inflater = 
              (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View menuLayout = inflater.inflate(R.layout.your_menu_layout, mainLayout, true);
//now add menuLayout to wherever you want to add like

(RelativeLayout)findViewById(R.id.relative).addView(menuLayout);

How to remove specific session in asp.net?

Session.Remove("name of your session here");

Launch Failed. Binary not found. CDT on Eclipse Helios

First you need to make sure that the project has been built. You can build a project with the hammer icon in the toolbar. You can choose to build either a Debug or Release version. If you cannot build the project then the problem is that you either don't have a compiler installed or that the IDE does not find the compiler.

To see if you have a compiler installed in a Mac you can run the following command from the command line:

g++ --version

If you have it already installed (it gets installed when you install the XCode tools) you can see its location running:

which g++

If you were able to build the project but you still get the "binary not found" message then the issue might be that a default launch configuration is not being created for the project. In that case do this:

Right click project > Run As > Run Configurations... > 

Then create a new configuration under the "C/C++ Application" section > Enter the full path to the executable file (the file that was created in the build step and that will exist in either the Debug or Release folder). Your launch configuration should look like this:

enter image description here