Programs & Examples On #Subtraction

How to subtract X days from a date using Java calendar?

You could use the add method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar class such as the following

public static void addDays(Date d, int days)
{
    d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}

This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:

public static void addDays(Date d, int days)
{
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.add(Calendar.DATE, days);
    d.setTime( c.getTime().getTime() );
}

Note that both of these solutions change the Date object passed as a parameter rather than returning a completely new Date. Either function could be easily changed to do it the other way if desired.

Removing elements from an array in C

You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.

If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.

In C, you have two simple ways to declare an array.

  1. On the stack, as a static array

    int myArray[16]; // Static array of 16 integers
    
  2. On the heap, as a dynamically allocated array

    // Dynamically allocated array of 16 integers
    int* myArray = calloc(16, sizeof(int));
    

Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).

NOT IN vs NOT EXISTS

Database table model

Let’s assume we have the following two tables in our database, that form a one-to-many table relationship.

SQL EXISTS tables

The student table is the parent, and the student_grade is the child table since it has a student_id Foreign Key column referencing the id Primary Key column in the student table.

The student table contains the following two records:

| id | first_name | last_name | admission_score |
|----|------------|-----------|-----------------|
| 1  | Alice      | Smith     | 8.95            |
| 2  | Bob        | Johnson   | 8.75            |

And, the student_grade table stores the grades the students received:

| id | class_name | grade | student_id |
|----|------------|-------|------------|
| 1  | Math       | 10    | 1          |
| 2  | Math       | 9.5   | 1          |
| 3  | Math       | 9.75  | 1          |
| 4  | Science    | 9.5   | 1          |
| 5  | Science    | 9     | 1          |
| 6  | Science    | 9.25  | 1          |
| 7  | Math       | 8.5   | 2          |
| 8  | Math       | 9.5   | 2          |
| 9  | Math       | 9     | 2          |
| 10 | Science    | 10    | 2          |
| 11 | Science    | 9.4   | 2          |

SQL EXISTS

Let’s say we want to get all students that have received a 10 grade in Math class.

If we are only interested in the student identifier, then we can run a query like this one:

SELECT
    student_grade.student_id
FROM
    student_grade
WHERE
    student_grade.grade = 10 AND
    student_grade.class_name = 'Math'
ORDER BY
    student_grade.student_id

But, the application is interested in displaying the full name of a student, not just the identifier, so we need info from the student table as well.

In order to filter the student records that have a 10 grade in Math, we can use the EXISTS SQL operator, like this:

SELECT
    id, first_name, last_name
FROM
    student
WHERE EXISTS (
    SELECT 1
    FROM
        student_grade
    WHERE
        student_grade.student_id = student.id AND
        student_grade.grade = 10 AND
        student_grade.class_name = 'Math'
)
ORDER BY id

When running the query above, we can see that only the Alice row is selected:

| id | first_name | last_name |
|----|------------|-----------|
| 1  | Alice      | Smith     |

The outer query selects the student row columns we are interested in returning to the client. However, the WHERE clause is using the EXISTS operator with an associated inner subquery.

The EXISTS operator returns true if the subquery returns at least one record and false if no row is selected. The database engine does not have to run the subquery entirely. If a single record is matched, the EXISTS operator returns true, and the associated other query row is selected.

The inner subquery is correlated because the student_id column of the student_grade table is matched against the id column of the outer student table.

SQL NOT EXISTS

Let’s consider we want to select all students that have no grade lower than 9. For this, we can use NOT EXISTS, which negates the logic of the EXISTS operator.

Therefore, the NOT EXISTS operator returns true if the underlying subquery returns no record. However, if a single record is matched by the inner subquery, the NOT EXISTS operator will return false, and the subquery execution can be stopped.

To match all student records that have no associated student_grade with a value lower than 9, we can run the following SQL query:

SELECT
    id, first_name, last_name
FROM
    student
WHERE NOT EXISTS (
    SELECT 1
    FROM
        student_grade
    WHERE
        student_grade.student_id = student.id AND
        student_grade.grade < 9
)
ORDER BY id

When running the query above, we can see that only the Alice record is matched:

| id | first_name | last_name |
|----|------------|-----------|
| 1  | Alice      | Smith     |

So, the advantage of using the SQL EXISTS and NOT EXISTS operators is that the inner subquery execution can be stopped as long as a matching record is found.

How to use document.getElementByName and getElementByTag?

  • document.getElementById('frmMain').elements
    assumes the form has an ID and that the ID is unique as IDs should be. Although it also accesses a name attribute in IE, please add ID to the element if you want to use getElementById



A great alternative is


In all of the above, the .elements can be replaced by for example .querySelectorAll("[type=text]") to get all text elements

How can I get the session object if I have the entity-manager?

See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:

Session session = entityManager.unwrap(Session.class);

How can I use console logging in Internet Explorer?

Extremely important if using console.log() in production:

if you end up releasing console.log() commands to production you need to put in some kind of fix for IE - because console is only defined when in F12 debugging mode.

if (typeof console == "undefined") {
    this.console = { log: function (msg) { alert(msg); } };
}

[obviously remove the alert(msg); statement once you've verified it works]

See also 'console' is undefined error for Internet Explorer for other solutions and more details

How can I get the length of text entered in a textbox using jQuery?

var myLength = $("#myTextbox").val().length;

What is the iOS 5.0 user agent string?

fixed my agent string evaluation by scrubbing the string for LOWERCASE "iphone os 5_0" as opposed to "iPhone OS 5_0." now i am properly assigning iOS 5 specific classes to my html, when the uppercase scrub failed.

Open directory dialog

Ookii folder dialog can be found at Nuget.

PM> Install-Package Ookii.Dialogs.Wpf

And, example code is as below.

var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
    textBoxFolderPath.Text = dialog.SelectedPath;
}

More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Perhaps a better way of handling errors in MVC is to apply the HandleError attribute to your controller or action and update the Shared/Error.aspx file to do what you want. The Model object on that page includes an Exception property as well as ControllerName and ActionName.

End-line characters from lines read from text file, using Python

What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a '\n' as the last character, and therefore doing line = line[:-1] would incorrectly strip off the last character of the line.

The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:

def strip_trailing_newlines(file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
    # do something with line

Visual Studio keyboard shortcut to display IntelliSense

If you have arrived at this question because IntelliSense has stopped working properly and you are hoping to force it to show you what you need, then most likely none of these solutions are going to work.

Closing and restarting Visual Studio should fix the problem.

I lose my data when the container exits

You might want to look at docker volumes if you you want to persist the data in your container. Visit https://docs.docker.com/engine/tutorials/dockervolumes/. The docker documentation is a very good place to start

Using FolderBrowserDialog in WPF application

You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog class.

Adding using WinForms = System.Windows.Forms; will be helpful.

Facebook Callback appends '#_=_' to Return URL

I know this reply is late, but if you are using passportjs, you might want to see this.

return (req, res, next) => {
    console.log(req.originalUrl);
    next();
};

I have written this middleware and applied it to express server instance, and the original URL I've got is without the "#_=_". Looks like it when we apply passporJS' instance as middleware to the server instance, it doesn't take those characters, but are only visible on the address bar of our browsers.

Shared-memory objects in multiprocessing

I run into the same problem and wrote a little shared-memory utility class to work around it.

I'm using multiprocessing.RawArray (lockfree), and also the access to the arrays is not synchronized at all (lockfree), be careful not to shoot your own feet.

With the solution I get speedups by a factor of approx 3 on a quad-core i7.

Here's the code: Feel free to use and improve it, and please report back any bugs.

'''
Created on 14.05.2013

@author: martin
'''

import multiprocessing
import ctypes
import numpy as np

class SharedNumpyMemManagerError(Exception):
    pass

'''
Singleton Pattern
'''
class SharedNumpyMemManager:    

    _initSize = 1024

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(SharedNumpyMemManager, cls).__new__(
                                cls, *args, **kwargs)
        return cls._instance        

    def __init__(self):
        self.lock = multiprocessing.Lock()
        self.cur = 0
        self.cnt = 0
        self.shared_arrays = [None] * SharedNumpyMemManager._initSize

    def __createArray(self, dimensions, ctype=ctypes.c_double):

        self.lock.acquire()

        # double size if necessary
        if (self.cnt >= len(self.shared_arrays)):
            self.shared_arrays = self.shared_arrays + [None] * len(self.shared_arrays)

        # next handle
        self.__getNextFreeHdl()        

        # create array in shared memory segment
        shared_array_base = multiprocessing.RawArray(ctype, np.prod(dimensions))

        # convert to numpy array vie ctypeslib
        self.shared_arrays[self.cur] = np.ctypeslib.as_array(shared_array_base)

        # do a reshape for correct dimensions            
        # Returns a masked array containing the same data, but with a new shape.
        # The result is a view on the original array
        self.shared_arrays[self.cur] = self.shared_arrays[self.cnt].reshape(dimensions)

        # update cnt
        self.cnt += 1

        self.lock.release()

        # return handle to the shared memory numpy array
        return self.cur

    def __getNextFreeHdl(self):
        orgCur = self.cur
        while self.shared_arrays[self.cur] is not None:
            self.cur = (self.cur + 1) % len(self.shared_arrays)
            if orgCur == self.cur:
                raise SharedNumpyMemManagerError('Max Number of Shared Numpy Arrays Exceeded!')

    def __freeArray(self, hdl):
        self.lock.acquire()
        # set reference to None
        if self.shared_arrays[hdl] is not None: # consider multiple calls to free
            self.shared_arrays[hdl] = None
            self.cnt -= 1
        self.lock.release()

    def __getArray(self, i):
        return self.shared_arrays[i]

    @staticmethod
    def getInstance():
        if not SharedNumpyMemManager._instance:
            SharedNumpyMemManager._instance = SharedNumpyMemManager()
        return SharedNumpyMemManager._instance

    @staticmethod
    def createArray(*args, **kwargs):
        return SharedNumpyMemManager.getInstance().__createArray(*args, **kwargs)

    @staticmethod
    def getArray(*args, **kwargs):
        return SharedNumpyMemManager.getInstance().__getArray(*args, **kwargs)

    @staticmethod    
    def freeArray(*args, **kwargs):
        return SharedNumpyMemManager.getInstance().__freeArray(*args, **kwargs)

# Init Singleton on module load
SharedNumpyMemManager.getInstance()

if __name__ == '__main__':

    import timeit

    N_PROC = 8
    INNER_LOOP = 10000
    N = 1000

    def propagate(t):
        i, shm_hdl, evidence = t
        a = SharedNumpyMemManager.getArray(shm_hdl)
        for j in range(INNER_LOOP):
            a[i] = i

    class Parallel_Dummy_PF:

        def __init__(self, N):
            self.N = N
            self.arrayHdl = SharedNumpyMemManager.createArray(self.N, ctype=ctypes.c_double)            
            self.pool = multiprocessing.Pool(processes=N_PROC)

        def update_par(self, evidence):
            self.pool.map(propagate, zip(range(self.N), [self.arrayHdl] * self.N, [evidence] * self.N))

        def update_seq(self, evidence):
            for i in range(self.N):
                propagate((i, self.arrayHdl, evidence))

        def getArray(self):
            return SharedNumpyMemManager.getArray(self.arrayHdl)

    def parallelExec():
        pf = Parallel_Dummy_PF(N)
        print(pf.getArray())
        pf.update_par(5)
        print(pf.getArray())

    def sequentialExec():
        pf = Parallel_Dummy_PF(N)
        print(pf.getArray())
        pf.update_seq(5)
        print(pf.getArray())

    t1 = timeit.Timer("sequentialExec()", "from __main__ import sequentialExec")
    t2 = timeit.Timer("parallelExec()", "from __main__ import parallelExec")

    print("Sequential: ", t1.timeit(number=1))    
    print("Parallel: ", t2.timeit(number=1))

Download file from web in Python 3

Motivation

Sometimes, we are want to get the picture but not need to download it to real files,

i.e., download the data and keep it on memory.

For example, If I use the machine learning method, train a model that can recognize an image with the number (bar code).

When I spider some websites and that have those images so I can use the model to recognize it,

and I don't want to save those pictures on my disk drive,

then you can try the below method to help you keep download data on memory.

Points

import requests
from io import BytesIO
response = requests.get(url)
with BytesIO as io_obj:
    for chunk in response.iter_content(chunk_size=4096):
        io_obj.write(chunk)

basically, is like to @Ranvijay Kumar

An Example

import requests
from typing import NewType, TypeVar
from io import StringIO, BytesIO
import matplotlib.pyplot as plt
import imageio

URL = NewType('URL', str)
T_IO = TypeVar('T_IO', StringIO, BytesIO)


def download_and_keep_on_memory(url: URL, headers=None, timeout=None, **option) -> T_IO:
    chunk_size = option.get('chunk_size', 4096)  # default 4KB
    max_size = 1024 ** 2 * option.get('max_size', -1)  # MB, default will ignore.
    response = requests.get(url, headers=headers, timeout=timeout)
    if response.status_code != 200:
        raise requests.ConnectionError(f'{response.status_code}')

    instance_io = StringIO if isinstance(next(response.iter_content(chunk_size=1)), str) else BytesIO
    io_obj = instance_io()
    cur_size = 0
    for chunk in response.iter_content(chunk_size=chunk_size):
        cur_size += chunk_size
        if 0 < max_size < cur_size:
            break
        io_obj.write(chunk)
    io_obj.seek(0)
    """ save it to real file.
    with open('temp.png', mode='wb') as out_f:
        out_f.write(io_obj.read())
    """
    return io_obj


def main():
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': 'statics.591.com.tw',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'
    }
    io_img = download_and_keep_on_memory(URL('http://statics.591.com.tw/tools/showPhone.php?info_data=rLsGZe4U%2FbphHOimi2PT%2FhxTPqI&type=rLEFMu4XrrpgEw'),
                                         headers,  # You may need this. Otherwise, some websites will send the 404 error to you.
                                         max_size=4)  # max loading < 4MB
    with io_img:
        plt.rc('axes.spines', top=False, bottom=False, left=False, right=False)
        plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0))  # same of plt.axis('off')
        plt.imshow(imageio.imread(io_img, as_gray=False, pilmode="RGB"))
        plt.show()


if __name__ == '__main__':
    main()

Dynamically add event listener

I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:

ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }

If i´m adding a listener

this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
    alert('Clicking the document');
})

I´d expect my function to execute what i intended, not the total opposite which is remove the listener.

// I´d expect an alert('Clicking the document'); 
this.listenToClick();
// what you actually get is removing the listener, so nothing...

In the given scenario, It´d actually make to more sense to name it like:

// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
    console.log('Clicking the document', evt);
})

let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
    console.log('Clicking the button', evt);
});

There must be a good reason for this but in my opinion it´s very misleading and not intuitive.

Proper way to make HTML nested list?

What's not mentioned here is that option 1 allows you arbitrarily deep nesting of lists.

This shouldn't matter if you control the content/css, but if you're making a rich text editor it comes in handy.

For example, gmail, inbox, and evernote all allow creating lists like this:

arbitrarily nested list

With option 2 you cannot due that (you'll have an extra list item), with option 1, you can.

How to set a Javascript object values dynamically?

When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.

You can access these dictionaries in two ways:

  • Like an array (e.g. myObj[name]); or
  • Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.

You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.

myObj["name"]

Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.

Selecting only numeric columns from a data frame

The library PCAmixdata has functon splitmix that splits quantitative(Numerical data) and qualitative (Categorical data) of a given dataframe "YourDataframe" as shown below:

install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset) 
X2 <- split$X.quali (Gives categorical columns in the dataset)

Getting the names of all files in a directory with PHP

You could just try the scandir(Path) function. it is fast and easy to implement

Syntax:

$files = scandir("somePath");

This Function returns a list of file into an Array.

to view the result, you can try

var_dump($files);

Or

foreach($files as $file)
{ 
echo $file."< br>";
} 

Align text in a table header

Try:

text-align: center;

You may be familiar with the HTML align attribute (which has been discontinued as of HTML 5). The align attribute could be used with tags such as

<table>, <td>, and <img> 

to specify the alignment of these elements. This attribute allowed you to align elements horizontally. HTML also has/had a valign attribute for aligning elements vertically. This has also been discontinued from HTML5.

These attributes were discontinued in favor of using CSS to set the alignment of HTML elements.

There isn't actually a CSS align or CSS valign property. Instead, CSS has the text-align which applies to inline content of block-level elements, and vertical-align property which applies to inline level and table cells.

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

How to exit from ForEach-Object in PowerShell

Since ForEach-Object is a cmdlet, break and continue will behave differently here than with the foreach keyword. Both will stop the loop but will also terminate the entire script:

break:

0..3 | foreach {
    if ($_ -eq 2) { break }
    $_
}
echo "Never printed"

# OUTPUT:
# 0
# 1

continue:

0..3 | foreach {
    if ($_ -eq 2) { continue }
    $_
}
echo "Never printed"

# OUTPUT:
# 0
# 1

So far, I have not found a "good" way to break a foreach script block without breaking the script, except "abusing" exceptions:

throw:

try {
    0..3 | foreach {
        if ($_ -eq 2) { throw }
        $_
    }
} catch { }
echo "End"

# OUTPUT:
# 0
# 1
# End

The alternative (which is not always possible) would be to use the foreach keyword:

foreach:

foreach ($_ in (0..3)) {
    if ($_ -eq 2) { break }
    $_
}
echo "End"

# OUTPUT:
# 0
# 1
# End

Maven is not working in Java 8 when Javadoc tags are incomplete

As of maven-javadoc-plugin 3.0.0 you should have been using additionalJOption to set an additional Javadoc option, so if you would like Javadoc to disable doclint, you should add the following property.

<properties>
    ...
    <additionalJOption>-Xdoclint:none</additionalJOption>
    ...
<properties>

You should also mention the version of maven-javadoc-plugin as 3.0.0 or higher.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.0.0</version>    
</plugin>

Using Pip to install packages to Anaconda Environment

For others who run into this situation, I found this to be the most straightforward solution:

  1. Run conda create -n venv_name and source activate venv_name, where venv_name is the name of your virtual environment.

  2. Run conda install pip. This will install pip to your venv directory.

  3. Find your anaconda directory, and find the actual venv folder. It should be somewhere like /anaconda/envs/venv_name/.

  4. Install new packages by doing /anaconda/envs/venv_name/bin/pip install package_name.

This should now successfully install packages using that virtual environment's pip!

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

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

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

What is the full path to the Packages folder for Sublime text 2 on Mac OS Lion

/Users/{user}/Library/Application Support/Sublime Text 2/Packages

Get to it quickly from within Sublime via the menu at Sublime Text 2... Preferences... Browse Packages

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

mysql.h file can't be found

You have to let the compiler know where the mysql.h file can be found. This can be done by giving the path to the header before compiling. In IDEs you have a setting where you can give these paths.

This link gives you more info on what options to use while compiling.

To your second problem You need to link the libraries. The linker needs to know where the library files are which has the implementation for the mysql functions that you use.

This link gives you more info on how to link libraries.

PHP decoding and encoding json with unicode characters

To encode an array that contains special characters, ISO 8859-1 to UTF8. (If utf8_encode & utf8_decode is not what is working for you, this might be an option)

Everything that is in ISO-8859-1 should be converted to UTF8:

$utf8 = utf8_encode('? ??? ??? ????!'); //contains UTF8 & ISO 8859-1 characters;    
$iso88591 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$data = $iso88591;

Encode should work after this:

$encoded_data = json_encode($data);

Convert UTF-8 to & from ISO 8859-1

Escape @ character in razor view engine

Instead of HTML entity I prefer the use of @Html.Raw("@").

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }

must appear in the GROUP BY clause or be used in an aggregate function

The problem with specifying non-grouped and non-aggregate fields in group by selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min and max are exceptions).

However, there is a workaround: make the required field aggregated as well. In posgres, this should work:

SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;

Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).

Get width height of remote image from url

Get image size with jQuery
(depending on which formatting method is more suitable for your preferences):

function getMeta(url){
    $('<img/>',{
        src: url,
        on: {
            load: (e) => {
                console.log('image size:', $(e.target).width(), $(e.target).height());
            },
        }
    });
}

or

function getMeta(url){
    $('<img/>',{
        src: url,
    }).on({
        load: (e) => {
            console.log('image size:', $(e.target).width(), $(e.target).height());
        },
    });
}

Is there an easy way to add a border to the top and bottom of an Android View?

The currently accepted answer doesn't work. It creates thin vertical borders on the left and right sides of the view as a result of anti-aliasing.

This version works perfectly. It also allows you to set the border widths independently, and you can also add borders on the left / right sides if you want. The only drawback is that it does NOT support transparency.

Create an xml drawable named /res/drawable/top_bottom_borders.xml with the code below and assign it as a TextView's background property.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#DDDD00" /> <!-- border color -->
        </shape>
    </item>

    <item
        android:bottom="1dp" 
        android:top="1dp">   <!-- adjust borders width here -->
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />  <!-- background color -->
        </shape>
    </item>
</layer-list>

Tested on Android KitKat through Marshmallow

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

How to draw polygons on an HTML5 canvas?

To make a simple hexagon without the need for a loop, Just use the beginPath() function. Make sure your canvas.getContext('2d') is the equal to ctx if not it will not work.

I also like to add a variable called times that I can use to scale the object if I need to.This what I don't need to change each number.

     // Times Variable 

     var times = 1;

    // Create a shape

    ctx.beginPath();
    ctx.moveTo(99*times, 0*times);
    ctx.lineTo(99*times, 0*times);
    ctx.lineTo(198*times, 50*times);
    ctx.lineTo(198*times, 148*times);
    ctx.lineTo(99*times, 198*times);
    ctx.lineTo(99*times, 198*times);
    ctx.lineTo(1*times, 148*times);
    ctx.lineTo(1*times,57*times);
    ctx.closePath();
    ctx.clip();
    ctx.stroke();

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

What is the difference between sed and awk?

1) What is the difference between awk and sed ?

Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.

2) What kind of application are best use cases for sed and awk tools ?

Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.

Determining the size of an Android view at runtime

In Kotlin file, change accordingly

 Handler().postDelayed({

           Your Code

        }, 1)

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

How to vertically center a "div" element for all browsers using CSS?

Centering only vertically

If you don't care about Internet Explorer 6 and 7, you can use a technique that involves two containers.

The outer container:

  • should have display: table;

The inner container:

  • should have display: table-cell;
  • should have vertical-align: middle;

The content box:

  • should have display: inline-block;

You can add any content you want to the content box without caring about its width or height!

Demo:

_x000D_
_x000D_
body {
    margin: 0;
}

.outer-container {
    position: absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
}

.centered-content {
    display: inline-block;
    background: #fff;
    padding: 20px;
    border: 1px solid #000;
}
_x000D_
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Malcolm in the Middle
     </div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!


Centering horizontally and vertically

If you want to center both horizontally and vertically, you also need the following.

The inner container:

  • should have text-align: center;

The content box:

  • should re-adjust the horizontal text-alignment to for example text-align: left; or text-align: right;, unless you want text to be centered

Demo:

_x000D_
_x000D_
body {
    margin: 0;
}

.outer-container {
    position: absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding: 20px;
    border: 1px solid #000;
}
_x000D_
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
         Malcolm in the Middle
     </div>
   </div>
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

open Command line and type lodctr /r The p. counter will be resotred\recreated.

There is no need to skip it. http://technet.microsoft.com/en-us/library/cc774958.aspx

Sorting a list using Lambda/Linq to objects

The solution provided by Rashack does not work for value types (int, enums, etc.) unfortunately.

For it to work with any type of property, this is the solution I found:

public static Expression<Func<T, object>> GetLambdaExpressionFor<T>(this string sortColumn)
    {
        var type = typeof(T);
        var parameterExpression = Expression.Parameter(type, "x");
        var body = Expression.PropertyOrField(parameterExpression, sortColumn);
        var convertedBody = Expression.MakeUnary(ExpressionType.Convert, body, typeof(object));

        var expression = Expression.Lambda<Func<T, object>>(convertedBody, new[] { parameterExpression });

        return expression;
    }

Spring Test & Security: How to mock authentication?

Options to avoid using SecurityContextHolder in tests:

  • Option 1: use mocks - I mean mock SecurityContextHolder using some mock library - EasyMock for example
  • Option 2: wrap call SecurityContextHolder.get... in your code in some service - for example in SecurityServiceImpl with method getCurrentPrincipal that implements SecurityService interface and then in your tests you can simply create mock implementation of this interface that returns the desired principal without access to SecurityContextHolder.

Scanner method to get a char

sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time

example: sc.next().charat(2)------------>>>>>>>>

Local dependency in package.json

Curious.....at least on Windows (my npm is 3.something) I needed to do:

"dependencies": {
 "body-parser": "^1.17.1",
 "module1": "../module1",
 "module2": "../module2",

When I did an npm install ../module1 --save it resulted in absolute paths and not relative per the documentation.

I messed around a little more and determined that ../xxx was sufficient.

Specifically, I have the local node modules checked out to say d:\build\module1, d:\build\module2 and my node project (application) in d:\build\nodeApp.

To 'install', I:

d:\build\module1> rmdir "./node_modules" /q /s && npm install
d:\build\module2> rmdir "./node_modules" /q /s && npm install
d:\build\nodeApp> rmdir "./node_modules" /q /s && npm install

module1's package.json has a dependency of "module2": "../module2"; module2 has no local dependency; nodeApp has dependencies "module1": "../module1" and "module2": "../module2".

Not sure if this only works for me since all 3 folders (module1, module2 and nodeApp) sit on that same level.......

PHP Try and Catch for SQL Insert

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

TypeError: sequence item 0: expected string, int found

String interpolation is a nice way to pass in a formatted string.

values = ', '.join('$%s' % v for v in value_list)

How to import a bak file into SQL Server Express

Restoring a Database from Backup

sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
            DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK

Group dataframe and get sum AND count?

Just in case you were wondering how to rename columns during aggregation, here's how for

pandas >= 0.25: Named Aggregation

df.groupby('Company Name')['Amount'].agg(MySum='sum', MyCount='count')

Or,

df.groupby('Company Name').agg(MySum=('Amount', 'sum'), MyCount=('Amount', 'count'))

                       MySum  MyCount
Company Name                       
Vifor Pharma UK Ltd  4207.93        5

Output (echo/print) everything from a PHP Array

For nice & readable results, use this:

function printVar($var) {
    echo '<pre>';
    var_dump($var); 
    echo '</pre>';
}

The above function will preserve the original formatting, making it (more)readable in a web browser.

All combinations of a list of lists

you need itertools.product:

>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

Mutex example / tutorial?

You are supposed to check the mutex variable before using the area protected by the mutex. So your pthread_mutex_lock() could (depending on implementation) wait until mutex1 is released or return a value indicating that the lock could not be obtained if someone else has already locked it.

Mutex is really just a simplified semaphore. If you read about them and understand them, you understand mutexes. There are several questions regarding mutexes and semaphores in SO. Difference between binary semaphore and mutex, When should we use mutex and when should we use semaphore and so on. The toilet example in the first link is about as good an example as one can think of. All code does is to check if the key is available and if it is, reserves it. Notice that you don't really reserve the toilet itself, but the key.

WPF MVVM ComboBox SelectedItem or SelectedValue not working

Use Loaded event:

private void cmb_Loaded(object sender, RoutedEventArgs e) {
    if (cmb.Items.Count > 0) cmb.SelectedIndex = 0;          
}

It works for me.

How to assign string to bytes array

Besides the methods mentioned above, you can also do a trick as

s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))

Go Play: http://play.golang.org/p/xASsiSpQmC

You should never use this :-)

How to get week number in Python?

datetime.date has a isocalendar() method, which returns a tuple containing the calendar week:

>>> import datetime
>>> datetime.date(2010, 6, 16).isocalendar()[1]
24

datetime.date.isocalendar() is an instance-method returning a tuple containing year, weeknumber and weekday in respective order for the given date instance.

What does IFormatProvider do?

Passing null as the IFormatProvider is not the correct way to do this. If the user has a custom date/time format on their PC you'll have issues in parsing and converting to string. I've just fixed a bug where somebody had passed null as the IFormatProvider when converting to string.

Instead you should be using CultureInfo.InvariantCulture

Wrong:

string output = theDate.ToString("dd/MM/yy HH:mm:ss.fff", null);

Correct:

string output = theDate.ToString("dd/MM/yy HH:mm:ss.fff", CultureInfo.InvariantCulture);

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had a similar problem when I deployed my Flask app in the IIS. Apparently, IIS does not accept route that include an underline ("_"). When I removed the underline, problem was resolved.

How can I do string interpolation in JavaScript?

Expanding on Greg Kindel's second answer, you can write a function to eliminate some of the boilerplate:

var fmt = {
    join: function() {
        return Array.prototype.slice.call(arguments).join(' ');
    },
    log: function() {
        console.log(this.join(...arguments));
    }
}

Usage:

var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');

ISO time (ISO 8601) in Python

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

If you don't need the microseconds, just leave out the .%f part:

>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

For local time:

>>> datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
'20180905T140903'

Edit:

After reading up on this some more, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:

>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'

Using subprocess to run Python script on Windows

For example, to execute following with command prompt or BATCH file we can use this:

C:\Python27\python.exe "C:\Program files(x86)\dev_appserver.py" --host 0.0.0.0 --post 8080 "C:\blabla\"

Same thing to do with Python, we can do this:

subprocess.Popen(['C:/Python27/python.exe', 'C:\\Program files(x86)\\dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:\\blabla'], shell=True)

or

subprocess.Popen(['C:/Python27/python.exe', 'C:/Program files(x86)/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/blabla'], shell=True)

How to go to each directory and execute a command?

If the toplevel folder is known you can just write something like this:

for dir in `ls $YOUR_TOP_LEVEL_FOLDER`;
do
    for subdir in `ls $YOUR_TOP_LEVEL_FOLDER/$dir`;
    do
      $(PLAY AS MUCH AS YOU WANT);
    done
done

On the $(PLAY AS MUCH AS YOU WANT); you can put as much code as you want.

Note that I didn't "cd" on any directory.

Cheers,

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

Add newly created specific folder to .gitignore in Git

Try /public_html/stats/* ?

But since the files in git status reported as to be commited that means you've already added them manually. In which case, of course, it's a bit too late to ignore. You can git rm --cache them (IIRC).

Can't type in React input text field

i'm also facing that problem now solved.Give the onChange to the searchTool. then that problem will solve for you.

How to rotate portrait/landscape Android emulator?

Yes. Thanks

Ctrl + F11 for Portrait

and

Ctrl + F12 for Landscape

HTML5 Canvas: Zooming

If you have a source image or canvas element and your 400x400 canvas you want to draw into you can use the drawImage method to achieve zooming.

So for example, the full view might be like this

ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

And a zoomed view might be like this

ctx.drawImage(img, img.width / 4, img.height / 4, img.width / 2, img.height / 2, 0, 0, canvas.width, canvas.height);

The first parameter to drawImage is the image element or canvas element to draw, the next 4 are the x, y, width and height to sample from the source and the last 4 parameters are the x, y, width and height of the region to draw in the canvas. It will then handle the scaling for you.

You would just need to pick the width and height for the source sample based on the zoom level and the x and y based on where the mouse is clicked minus half the calculated width and height (but you will need to ensure the rectangle isn't out of bounds).

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

Can you 'exit' a loop in PHP?

You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

How do I adb pull ALL files of a folder present in SD Card

if your using jellybean just start cmd, type adb devices to make sure your readable, type adb pull sdcard/ sdcard_(the date or extra) <---this file needs to be made in adb directory beforehand. PROFIT!

In other versions type adb pull mnt/sdcard/ sdcard_(the date or extra)

Remember to make file or your either gonna have a mess or it wont work.

How to drop a unique constraint from table column?

If you know the name of your constraint then you can directly use the command like

alter table users drop constraint constraint_name;

If you don't know the constraint name, you can get the constraint by using this command

select constraint_name,constraint_type from user_constraints where table_name = 'YOUR TABLE NAME';

Installing R with Homebrew

brew install homebrew/science/r

works on OS X 10.11.6.

How to go to a specific element on page?

here is a simple javascript for that

call this when you need to scroll the screen to an element which has id="yourSpecificElementId"

window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));

and you need this function for the working:

//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    return [curtop];
    }
}

the screen will be scrolled to your specific element.

canvas.toDataURL() SecurityError

Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!

EDIT:

As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

This will only work if you have the correct permissions, but will at least allow you to do what you want.

How to disable HTML button using JavaScript?

Since this setting is not an attribute

It is an attribute.

Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).

As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.

The DOM property is also called disabled and is a boolean that takes true or false.

foo.disabled = true;

In theory you can also foo.setAttribute('disabled', 'disabled'); and foo.removeAttribute("disabled"), but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute).

How can I get the current network interface throughput statistics on Linux/UNIX?

  • dstat - Combines vmstat, iostat, ifstat, netstat information and more
  • iftop - Amazing network bandwidth utility to analyse what is really happening on your eth
  • netio - Measures the net throughput of a network via TCP/IP
  • inq - CLI troubleshooting utility that displays info on storage, typically Symmetrix. By default, INQ returns the device name, Symmetrix ID, Symmetrix LUN, and capacity.
  • send_arp - Sends out an arp broadcast on the specified network device (defaults to eth0), reporting an old and new IP address mapping to a MAC address.
  • EtherApe - is a graphical network monitor for Unix modeled after etherman. Featuring link layer, IP and TCP modes, it displays network activity graphically.
  • iptraf - An IP traffic monitor that shows information on the IP traffic passing over your network.

More details: http://felipeferreira.net/?p=1194

Angular cookies

Update: angular2-cookie is now deprecated. Please use my ngx-cookie instead.

Old answer:

Here is angular2-cookie which is the exact implementation of Angular 1 $cookies service (plus a removeAll() method) that I created. It is using the same methods, only implemented in typescript with Angular 2 logic.

You can inject it as a service in the components providers array:

import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-very-cool-app',
    template: '<h1>My Angular2 App with Cookies</h1>',
    providers: [CookieService]
})

After that, define it in the consturctur as usual and start using:

export class AppComponent { 
  constructor(private _cookieService:CookieService){}

  getCookie(key: string){
    return this._cookieService.get(key);
  }
}

You can get it via npm:

npm install angular2-cookie --save

SVN commit command

Command-line SVN

You need to add your files to your working copy, before you commit your changes to the repository:

svn add <file|folder>

Afterwards:

svn commit

See here for detailed information about svn add.

TortoiseSVN

It works with TortoiseSVN, because it adds the file to your working copy automatically (commit dialog):

If you want to include an unversioned file, just check that file to add it to the commit.

See: TortoiseSVN: Committing Your Changes To The Repository

What does the regex \S mean in JavaScript?

\S matches anything but a whitespace, according to this reference.

how to extract only the year from the date in sql server 2008?

---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
insert into Users values(4,'9/10/1991')

select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, 
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, 
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users

Where to get "UTF-8" string literal in Java?

The Google Guava library (which I'd highly recommend anyway, if you're doing work in Java) has a Charsets class with static fields like Charsets.UTF_8, Charsets.UTF_16, etc.

Since Java 7 you should just use java.nio.charset.StandardCharsets instead for comparable constants.

Note that these constants aren't strings, they're actual Charset instances. All standard APIs that take a charset name also have an overload that take a Charset object which you should use instead.

python: iterate a specific range in a list

You want to use slicing.

for item in listOfStuff[1:3]:
    print item

Multiple select in Visual Studio?

In the Visual Studio Shift+Alt+. / Shift+Alt+,

  • Shift+Alt+. - match caret;
  • Shift+Alt+, - remove previous caret;

Same function as on VSCode Ctrl+D.

Much more setting Tool - Options - Environment - keyboard. Next in the Show commands containing enter Edit..

Also, can use keyboard schema Visual Studio Code. Available for Visual Studio 2017

For conclusion, nice link Visual Studio All keyboard shortcuts

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

6 digits regular expression

You can use range quantifier {min,max} to specify minimum of 1 digit and maximum of 6 digits as:

^[0-9]{1,6}$

Explanation:

^     : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$     : End anchor

Why did your regex not work ?

You were almost close on the regex:

^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$

Since you had escaped the ? by preceding it with the \, the ? was no more acting as a regex meta-character ( for 0 or 1 repetitions) but was being treated literally.

To fix it just remove the \ and you are there.

See it on rubular.

The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.

Your second regex:

^[0-999999]$

is equivalent to:

^[0-9]$

which matches strings with exactly one digit. They are equivalent because a character class [aaaab] is same as [ab].

Angular: How to download a file from HttpClient?

Using Blob as a source for an img:

template:

<img [src]="url">

component:

 public url : SafeResourceUrl;

 constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
   this.getImage('/api/image.jpg').subscribe(x => this.url = x)
 }

 public getImage(url: string): Observable<SafeResourceUrl> {
   return this.http
     .get(url, { responseType: 'blob' })
     .pipe(
       map(x => {
         const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
         return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
       }),
     );
 }

Further reference about trusting save values

How to install and use "make" in Windows?

The accepted answer is a bad idea in general because the manually created make.exe will stick around and can potentially cause unexpected problems. It actually breaks RubyInstaller: https://github.com/oneclick/rubyinstaller2/issues/105

An alternative is installing make via Chocolatey (as pointed out by @Vasantha Ganesh K)

Another alternative is installing MSYS2 from Chocolatey and using make from C:\tools\msys64\usr\bin. If make isn't installed automatically with MSYS2 you need to install it manually via pacman -S make (as pointed out by @Thad Guidry and @Luke).

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I tried everything mentioned here and in other posts. Some of the solutions that people proffered were:

  1. Change the output folder for the test
  2. Create a custom builder for the project that would run test-compile from Maven
  3. Move the Maven dependencies higher in the Order and Export list in the project build path

There were many, many more but the one that I found to work was as follows: Close the development environment. Delete the jars used by the project from my local Maven repository. Open the IDE. Build the project. Run the test.

After hours of beating my head against my keyboard and following suggested solutions, this one worked!

Handling Dialogs in WPF with MVVM

I suggest forgoing the 1990's modal dialogs and instead implementing a control as an overlay (canvas+absolute positioning) with visibility tied to a boolean back in the VM. Closer to an ajax type control.

This is very useful:

<BooleanToVisibilityConverter x:Key="booltoVis" />

as in:

<my:ErrorControl Visibility="{Binding Path=ThereWasAnError, Mode=TwoWay, Converter={StaticResource booltoVis}, UpdateSourceTrigger=PropertyChanged}"/>

Here's how I have one implemented as a user control. Clicking on the 'x' closes the control in a line of code in the usercontrol's code behind. (Since I have my Views in an .exe and ViewModels in a dll, I don't feel bad about code that manipulates UI.)

Wpf dialog

Drop-down box dependent on the option selected in another drop-down box

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.

How do I get a list of folders and sub folders without the files?

I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.

dir /b /AD-H

How to ignore the first line of data when processing CSV data?

I would convert csvreader to list, then pop the first element

import csv        

with open(fileName, 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        data = list(csvreader)               # Convert to list
        data.pop(0)                          # Removes the first row

        for row in data:
            print(row)

What are the -Xms and -Xmx parameters when starting JVM?

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.

This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:

java -Xms256m -Xmx2048m

The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k
-Xmx512m
-Xmx8g

The Xms flag has no default value, and Xmx typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

What is the time complexity of indexing, inserting and removing from common data structures?

Amortized Big-O for hashtables:

  • Insert - O(1)
  • Retrieve - O(1)
  • Delete - O(1)

Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.

CSS class for pointer cursor

As of June 2020, adding role='button' to any HTML tag would add cursor: "pointer" to the element styling.

<span role="button">Non-button element button</span>

Official discussion on this feature - https://github.com/twbs/bootstrap/issues/23709

Documentation link - https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons

Is it better to use path() or url() in urls.py for django 2.0?

path is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.

It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.

What is "Advanced" SQL?

SELECT ... HAVING ... is a good start. Not many developers seem to understand how to use it.

HTML5 Audio stop function

This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio> tags with a div (here with an id of "plHolder").

<div id="plHolder">
     <audio controls id="player">
     ...
     </audio>
<div>

Then this javascript should work:

function stopAudio() {
    var savePlayer = $('#plHolder').html(); // Save player code
    $('#player').remove(); // Remove player from DOM
    $('#FlHolder').html(savePlayer); // Restore it
}

How to append elements into a dictionary in Swift?

Up till now the best way I have found to append data to a dictionary by using one of the higher order functions of Swift i.e. "reduce". Follow below code snippet:

newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }

@Dharmesh In your case, it will be,

newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }

Please let me know if you find any issues in using above syntax.

ImportError: No module named scipy

This may be too basic (and perhaps assumable), but -

Fedora users can use:

sudo dnf install python-scipy

and then (For python3.x):

pip3 install scipy

or (For python2.7):

pip2 install scipy

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SVN: Folder already under version control but not comitting?

Copy problematic folder into some backup directory and remove it from your SVN working directory. Remember to delete all .svn hidden directories from the copied folder.

Now update your project, clean-up and commit what has left. Now move your folder back to working directory, add it and commit. Most of the time this workaround works, it seems that basically SVN got confused...

Update: quoting comment by @Mark:

Didn't need to move the folder around, just deleting the .svn folder and then svn-adding it worked.

Convert DataSet to List

Try the above which will run with any list type.

  public DataTable ListToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection props =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }
            table.Rows.Add(values);
        }
        return table;
    }

How to auto resize and adjust Form controls with change in resolution

in the form load event add this line

this.WindowState = FormWindowState.Maximized;

How to calculate the SVG Path for an arc (of a circle)

Expanding on @wdebeaum's great answer, here's a method for generating an arced path:

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

function describeArc(x, y, radius, startAngle, endAngle){

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

    var d = [
        "M", start.x, start.y, 
        "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
    ].join(" ");

    return d;       
}

to use

document.getElementById("arc1").setAttribute("d", describeArc(200, 400, 100, 0, 180));

and in your html

<path id="arc1" fill="none" stroke="#446688" stroke-width="20" />

Live demo

ASP.NET MVC get textbox input value

You may use jQuery:

<input type="text" name="IP" id="IP" value=""/>
@Html.ActionLink(@Resource.ButtonTitleAdd, "Add", "Configure", new { ipValue ="xxx", TypeId = "1" }, new {@class = "link"})

<script>
  $(function () {
    $('.link').click(function () {
      var ipvalue = $("#IP").val();
      this.href = this.href.replace("xxx", ipvalue);
    });
  });
</script>

How to compile Go program consisting of multiple files?

New Way (Recommended):

Please take a look at this answer.

Old Way:

Supposing you're writing a program called myprog :

Put all your files in a directory like this

myproject/go/src/myprog/xxx.go

Then add myproject/go to GOPATH

And run

go install myprog

This way you'll be able to add other packages and programs in myproject/go/src if you want.

Reference : http://golang.org/doc/code.html

(this doc is always missed by newcomers, and often ill-understood at first. It should receive the greatest attention of the Go team IMO)

The result of a query cannot be enumerated more than once

Try replacing this

var query = context.Search(id, searchText);

with

var query = context.Search(id, searchText).tolist();

and everything will work well.

Call ASP.NET function from JavaScript?

Add this line to page load if you are getting object expected error.

ClientScript.GetPostBackEventReference(this, "");

Chrome blocks different origin requests

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

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

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

Convert list to tuple in Python

To add another alternative to tuple(l), as of Python >= 3.5 you can do:

t = *l,  # or t = (*l,) 

short, a bit faster but probably suffers from readability.

This essentially unpacks the list l inside a tuple literal which is created due to the presence of the single comma ,.


P.s: The error you are receiving is due to masking of the name tuple i.e you assigned to the name tuple somewhere e.g tuple = (1, 2, 3).

Using del tuple you should be good to go.

'^M' character at end of lines

The easiest way is to use vi. I know that sounds terrible but its simple and already installed on most UNIX environments. The ^M is a new line from Windows/DOS environment.

from the command prompt: $ vi filename

Then press ":" to get to command mode.

Search and Replace all Globally is :%s/^M//g "Press and hold control then press V then M" which will replace ^M with nothing.

Then to write and quit enter ":wq" Done!

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

You are calling local server with http://localhost:8080/foo/bar. Call it with https://localhost:8080/foo/bar. This solves the problem

Exception of type 'System.OutOfMemoryException' was thrown.

If you're using IIS Express, select Show All Application from IIS Express in the task bar notification area, then select Stop All.

Now re-run your application.

How to trigger HTML button when you press Enter in textbox?

Do not use Javascript for this!

Modern HTML pages automatically allow a form's submit button to submit the page with the ENTER/RETURN key when any form field control in the web page has focus by the user, autofocus attribute is set on a form field or button, or user tab's into any of the form fields.

So instead of Javascripting this, an easier solution is to add tabindex=0 on your form fields and button inside a form element then autofocus on the first input control. The user can then press "ENTER" to submit the form at any point as they enter data:

<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
  <label for="username1">Username</label>
  <input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
  <label for="password1">Password</label>
  <input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
  <button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

How do I tokenize a string sentence in NLTK?

As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)

If your sentence is truly simple enough:

Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y

DataGridView checkbox column - value and functionality

Here's a one liner answer for this question

List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();

adb command not found

In my case with Android Studio 1.1.0 path was this

/Users/wzbozon/Library/Android/sdk/platform-tools

Add the following to ~/.bash_profile

export PATH=~/Library/Android/sdk/tools:$PATH
export PATH=~/Library/Android/sdk/platform-tools:$PATH

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

Turn off warnings and errors on PHP and MySQL

Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.

More information: http://php.net/manual/en/language.operators.errorcontrol.php

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

@fsockopen();

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

On Selenium WebDriver how to get Text from Span Tag

If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's post).

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();

css example:

String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();

HTML: How to center align a form

Being form a block element, you can center-align it by setting its side margins to auto:

form { margin: 0 auto; }

EDIT:
As @moomoochoo correctly pointed out, this rule will only work if the block element (your form, in this case) has been assigned a specific width.
Also, this 'trick' will not work for floating elements.

how to check if string value is in the Enum list?

I know this is an old thread, but here's a slightly different approach using attributes on the Enumerates and then a helper class to find the enumerate that matches.

This way you could have multiple mappings on a single enumerate.

public enum Age
{
    [Metadata("Value", "New_Born")]
    [Metadata("Value", "NewBorn")]
    New_Born = 1,
    [Metadata("Value", "Toddler")]
    Toddler = 2,
    [Metadata("Value", "Preschool")]
    Preschool = 4,
    [Metadata("Value", "Kindergarten")]
    Kindergarten = 8
}

With my helper class like this

public static class MetadataHelper
{
    public static string GetFirstValueFromMetaDataAttribute<T>(this T value, string metaDataDescription)
    {
        return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
    }

    private static IEnumerable<string> GetValueFromMetaDataAttribute<T>(T value, string metaDataDescription)
    {
        var attribs =
            value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (MetadataAttribute), true);
        return attribs.Any()
            ? (from p in (MetadataAttribute[]) attribs
                where p.Description.ToLower() == metaDataDescription.ToLower()
                select p.MetaData).ToList()
            : new List<string>();
    }

    public static List<T> GetEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
                        p => p.ToLower() == value.ToLower())).ToList();
    }

    public static List<T> GetNotEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
                        p => p.ToLower() != value.ToLower())).ToList();
    }

}

you can then do something like

var enumerates = MetadataHelper.GetEnumeratesByMetaData<Age>("Value", "New_Born");

And for completeness here is the attribute:

 [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public class MetadataAttribute : Attribute
{
    public MetadataAttribute(string description, string metaData = "")
    {
        Description = description;
        MetaData = metaData;
    }

    public string Description { get; set; }
    public string MetaData { get; set; }
}

Count indexes using "for" in Python

If you have some given list, and want to iterate over its items and indices, you can use enumerate():

for index, item in enumerate(my_list):
    print index, item

If you only need the indices, you can use range():

for i in range(len(my_list)):
    print i

How can I format a number into a string with leading zeros?

Try:

Key = i.ToString("000000");

Personally, though, I'd see if you can't sort on the integer directly, rather than the string representation.

How to read a CSV file from a URL with Python?

import pandas as pd
url='https://raw.githubusercontent.com/juliencohensolal/BankMarketing/master/rawData/bank-additional-full.csv'
data = pd.read_csv(url,sep=";") # use sep="," for coma separation. 
data.describe()

enter image description here

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

Remove spacing between table cells and rows

It looks like the DOCTYPE is causing the image to display as an inline element. If I add display: block to the image, problem solved.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Error: Cannot find module html

Install ejs if it is not.

npm install ejs

Then after just paste below two lines in your main file. (like app.js, main.js)

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

How to mount a host directory in a Docker container

Had the same problem. Found this in the docker documentation:

Note: The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.

So, mounting a read/write host directory is only possible with the -v parameter in the docker run command, as the other answers point out correctly.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

This answer is an update, circa November 2019. None of the popular pip installs will give you a working setup on MacOS 10.13 (and likely other versions as well). Here is a simple way that I got things working:

brew install mysql
pip install mysqlclient

If you need help installing brew, see this site: https://brew.sh/

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:

using System;
using System.IO;
using System.Web;
using System.Net;

public class Test
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
        try
        {
            using (WebResponse response = request.GetResponse())
            {
                Console.WriteLine("Won't get here");
            }
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse) response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
    }
}

You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)

If the error response may be large (which is unusual) you may want to tweak HttpWebRequest.DefaultMaximumErrorResponseLength to make sure you get the whole error.

Android - how to make a scrollable constraintlayout?

Constraintlayout is the Default for a new app. I am "learning to Android" now and had a very hard time figuring out how to handle the default "sample" code to scroll when a keyboard is up. I have seen many apps where I have to close the keyboard to click "submit" button and sometimes it does not goes away. Using this [ScrollView / ContraintLayout / Fields] hierarchy it is working just fine now. This way we can have the benefits and ease of use from ConstraintLayout in a scrollable view.

Writing a Python list of lists to a csv file

How about dumping the list of list into pickle and restoring it with pickle module? It's quite convenient.

>>> import pickle
>>> 
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
...     pickle.dump(mylist, f) 


>>> with open('mylist', 'rb') as f:
...      mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>> 

Create a dropdown component

This might not exactly you want but I've used jquery smartmenu(https://github.com/vadikom/smartmenus) to build a ng2 dropdown menu.

 $('#main-menu').smartmenus();

http://plnkr.co/edit/wLqLUoBQYgcDwOgSoRfF?p=preview https://github.com/Longfld/DynamicaLoadMultiLevelDropDownMenu

Oracle select most recent date record

i think i'd try with MAX something like this:

SELECT staff_id, max( date ) from owner.table group by staff_id

then link in your other columns:

select staff_id, site_id, pay_level, latest
from owner.table, 
(   SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date

.bashrc: Permission denied

The .bashrc file is in your user home directory (~/.bashrc or ~vagrant/.bashrc both resolve to the same path), inside the VM's filesystem. This file is invisible on the host machine, so you can't use any Windows editors to edit it directly.

You have two simple choices:

  1. Learn how to use a console-based text editor. My favourite is vi (or vim), which takes 15 minutes to learn the basics and is much quicker for simple edits than anything else.

    vi .bashrc

  2. Copy .bashrc out to /vagrant (which is a shared directory) and edit it using your Windows editors. Make sure not to save it back with any extensions.

    cp .bashrc /vagrant ... edit using your host machine ... cp /vagrant/.bashrc .

I'd recommend getting to know the command-line based editors. Once you're working inside the VM, it's best to stay there as otherwise you might just get confused.

You (the vagrant user) are the owner of your home .bashrc so you do have permissions to edit it.

Once edited, you can execute it by typing source .bashrc I prefer to logout and in again (there may be more than one file executed on login).

MySQL Delete all rows from table and reset ID to zero

If you cannot use TRUNCATE (e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

What's the PowerShell syntax for multiple values in a switch statement?

The switch doesn't appear to be case sensitive in PowerShell 5.1. All four of the $someString examples below work.

$someString = "YES"
$someString = "yes"
$someString = "yEs"
$someString = "y"

switch ($someString) {
   {"y","yes"} { "You entered Yes." }
   Default { "You didn't enter Yes."}
}

Here is my $PSVersionTable data.

Name                           Value
----                           -----
PSVersion                      5.1.17763.771
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.771
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



click or change event on radio using jquery

You can specify the name attribute as below:

$( 'input[name="testGroup"]:radio' ).change(

Getting the first and last day of a month, using a given DateTime object

You can do it

DateTime dt = DateTime.Now; 
DateTime firstDayOfMonth = new DateTime(dt.Year, date.Month, 1);
DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

Path.Combine absolute with relative path strings


Path.GetFullPath(@"c:\windows\temp\..\system32")?

Stretch and scale CSS background

An additional tip for SolidSmile's cheat is to scale (the proportionate re-sizing) by setting a width and using auto for height.

Ex:

#background {
    width: 500px;
    height: auto;
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

how to get right offset of an element? - jQuery

Just an addition to what Greg said:

$("#whatever").offset().left + $("#whatever").outerWidth()

This code will get the right position relative to the left side. If the intention was to get the right side position relative to the right (like when using the CSS right property) then an addition to the code is necessary as follows:

$("#parent_container").innerWidth() - ($("#whatever").offset().left + $("#whatever").outerWidth())

This code is useful in animations where you have to set the right side as a fixed anchor when you can't initially set the right property in CSS.

EditText onClickListener in Android

The keyboard seems to pop up when the EditText gains focus. To prevent this, set focusable to false:

<EditText
    ...
    android:focusable="false"
    ... />

This behavior can vary on different manufacturers' Android OS flavors, but on the devices I've tested I have found this to to be sufficient. If the keyboard still pops up, using hints instead of text seems to help as well:

myEditText.setText("My text");    // instead of this...
myEditText.setHint("My text");    // try this

Once you've done this, your on click listener should work as desired:

myEditText.setOnClickListener(new OnClickListener() {...});

trim left characters in sql server?

select substring( field, 1, 5 ) from sometable

Update Jenkins from a war file

To Upgrade Jenkins WAR file, follow the steps below:

  • Stop Jenkins server using command: systemctl stop jenkins
  • Go to Jenkins war location: ex: /usr/lib/jenkins
  • Take a backup from jenkins.war: mv jenkins.war jenkins.war_bkp
  • Download Jenkins using wget or curl command: wget http://updates.jenkinsci.org/download/war/(version)/jenkins.war
  • Starting Jenkins server using command: systemctl start jenkins
  • Check Jenkins server status using command: systemctl status jenkin

Clicking submit button of an HTML form by a Javascript code

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click();

What's an object file in C?

Object files are codes that are dependent on functions, symbols, and text to run the program. Just like old telex machines, which required teletyping to send signals to other telex machine.

In the same way processor's require binary code to run, object files are like binary code but not linked. Linking creates additional files so that the user does not have to have compile the C language themselves. Users can directly open the exe file once the object file is linked with some compiler like c language , or vb etc.

ImportError: No module named mysql.connector using Python2

What worked for me was to download the .deb file directly and install it (dpkg -i mysql-connector-python_2.1.7-1ubuntu16.04_all.deb). Python downloads are located here (you will need to create a free MySQL login to download first). Make sure you choose the correct version, i.e. (python_2.1.7 vs. python-py3_2.1.7). Only the "Architecture Independent" version worked for me.

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

What is monkey patching?

A MonkeyPatch is a piece of Python code which extends or modifies other code at runtime (typically at startup).

A simple example looks like this:

from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "ook ook eee eee eee!"

SomeClass.speak = speak

Source: MonkeyPatch page on Zope wiki.

What is setContentView(R.layout.main)?

public void onCreate(Bundle savedinstanceState) {
            super.onCreate(savedinstanceState);

            Button testButon = new Button(this);

            setContentView(testButon);

            show();

}

Convert MFC CString to integer

If you are using TCHAR.H routine (implicitly, or explicitly), be sure you use _ttoi() function, so that it compiles for both Unicode and ANSI compilations.

More details: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

Run a php app using tomcat?

There this PHP/Java bridge. This is basically running PHP via FastCGI. I have not used it myself.

Execute a batch file on a remote PC using a batch file on local PC

You can use WMIC or SCHTASKS (which means no third party software is needed):

1) SCHTASKS:

SCHTASKS /s remote_machine /U username /P password /create /tn "On demand demo" /tr "C:\some.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /s remote_machine /U username /P password /run /TN "On demand demo" 

2) WMIC (wmic will return the pid of the started process)

WMIC /NODE:"remote_machine" /user user /password password process call create "c:\some.bat","c:\exec_dir"

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Go to the build.gradle(Module App) in your project:

enter image description here

Follow the pic and change those version:

compileSdkVersion: 27
targetSdkVersion: 27

and if android studio version 2: Change the line with this line:

compile 'com.android.support:appcompat-v7:27.1.1'

else Change the line with this line:

implementation 'com.android.support:appcompat-v7:27.1.1'

and hopefully, you will solve your bug.

Display Python datetime without time

print then.date()

What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:

then = datetime.datetime.strptime(when, '%Y-%m-%d').date()

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

HTML5 validation when the input type is not "submit"

HTML5 Validation Work Only When button type will be submit

change --

<button type="button"  onclick="submitform()" id="save">Save</button>

To --

<button type="submit"  onclick="submitform()" id="save">Save</button>

Storing C++ template function definitions in a .CPP file

The problem you describe can be solved by defining the template in the header, or via the approach you describe above.

I recommend reading the following points from the C++ FAQ Lite:

They go into a lot of detail about these (and other) template issues.

Groovy executing shell commands

command = "ls *"

def execute_state=sh(returnStdout: true, script: command)

but if the command failure the process will terminate

Python [Errno 98] Address already in use

$ ps -fA | grep python
501 81211 12368   0  10:11PM ttys000    0:03.12  
python -m SimpleHTTPServer

$ kill 81211

How to insert new cell into UITableView in Swift

Swift 5.0, 4.0, 3.0 Updated Solution

Insert at Bottom

self.yourArray.append(msg)

self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()

Insert at Top of TableView

self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()

Python append() vs. + operator on lists, why do these give different results?

To explain "why":

The + operation adds the array elements to the original array. The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion).

The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element. The append-method however does literally what you ask: append the object on the right-hand side that you give it (the array or any other object), instead of taking its elements.

An alternative

Use extend() if you want to use a function that acts similar to the + operator (as others have shown here as well). It's not wise to do the opposite: to try to mimic append with the + operator for lists (see my earlier link on why).

Little history

For fun, a little history: the birth of the array module in Python in February 1993. it might surprise you, but arrays were added way after sequences and lists came into existence.

generating variable names on fly in python

If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:

globals()['somevar'] = 'someval'
print somevar  # prints 'someval'

But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.

mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']

Learn the python zen; run this and grok it well:

>>> import this

Get the string representation of a DOM node

I have wasted a lot of time figuring out what is wrong when I iterate through DOMElements with the code in the accepted answer. This is what worked for me, otherwise every second element disappears from the document:

_getGpxString: function(node) {
          clone = node.cloneNode(true);
          var tmp = document.createElement("div");
          tmp.appendChild(clone);
          return tmp.innerHTML;
        },

Java Project: Failed to load ApplicationContext

I had the same problem, and I was using the following plugin for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <useFile>true</useFile>
        <includes>
            <include>**/*Tests.java</include>
            <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
        <junitArtifactName>junit:junit</junitArtifactName>
        <parallel>methods</parallel>
        <threadCount>10</threadCount>
    </configuration>
</plugin>

The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.

After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:

    <parallel>methods</parallel>
    <threadCount>10</threadCount>

Hope that this helps someone out!

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

A solution I found in one of the previous answer as:

*Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}"*

...didn't work for me, but the following is a simplified version and works great (add any special character you like, I added # here), and add the number rule as you do with the letters as:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&]){8,}"

Java - removing first character of a string

You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.

String str = "Jamaica";
str = str.substring(1);

Difference between Big-O and Little-O Notation

f ? O(g) says, essentially

For at least one choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) <= k g(x) holds for all x > a.

Note that O(g) is the set of all functions for which this condition holds.

f ? o(g) says, essentially

For every choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) < k g(x) holds for all x > a.

Once again, note that o(g) is a set.

In Big-O, it is only necessary that you find a particular multiplier k for which the inequality holds beyond some minimum x.

In Little-o, it must be that there is a minimum x after which the inequality holds no matter how small you make k, as long as it is not negative or zero.

These both describe upper bounds, although somewhat counter-intuitively, Little-o is the stronger statement. There is a much larger gap between the growth rates of f and g if f ? o(g) than if f ? O(g).

One illustration of the disparity is this: f ? O(f) is true, but f ? o(f) is false. Therefore, Big-O can be read as "f ? O(g) means that f's asymptotic growth is no faster than g's", whereas "f ? o(g) means that f's asymptotic growth is strictly slower than g's". It's like <= versus <.

More specifically, if the value of g(x) is a constant multiple of the value of f(x), then f ? O(g) is true. This is why you can drop constants when working with big-O notation.

However, for f ? o(g) to be true, then g must include a higher power of x in its formula, and so the relative separation between f(x) and g(x) must actually get larger as x gets larger.

To use purely math examples (rather than referring to algorithms):

The following are true for Big-O, but would not be true if you used little-o:

  • x² ? O(x²)
  • x² ? O(x² + x)
  • x² ? O(200 * x²)

The following are true for little-o:

  • x² ? o(x³)
  • x² ? o(x!)
  • ln(x) ? o(x)

Note that if f ? o(g), this implies f ? O(g). e.g. x² ? o(x³) so it is also true that x² ? O(x³), (again, think of O as <= and o as <)

angular2: Error: TypeError: Cannot read property '...' of undefined

Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

How to run a cron job on every Monday, Wednesday and Friday?

Use crontab to add job

0 0 9 ? * MON,WED,FRI *

The above expression will run the job at 9 am on every mon, wed and friday. You can validate this in : http://www.cronmaker.com/

How do you show animated GIFs on a Windows Form (c#)

It's not too hard.

  1. Drop a picturebox onto your form.
  2. Add the .gif file as the image in the picturebox
  3. Show the picturebox when you are loading.

Things to take into consideration:

  • Disabling the picturebox will prevent the gif from being animated.

Animated gifs:

If you are looking for animated gifs you can generate them:

AjaxLoad - Ajax Loading gif generator

Another way of doing it:

Another way that I have found that works quite well is the async dialog control that I found on the code project

Using jQuery to build table rows from AJAX response(json)

You could do it something like this:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


    <script>
    $(function(){

    $.ajax({
    url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
    data: '<any parameters you want to send as the Request body or query string>',
    dataType: json,
    async: true,
    method: "GET"
    success: function(data){

    //If the REST API returned a successful response it'll be stored in data, 
    //just parse that field using jQuery and you're all set

    var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';

    $.each(data, function(idx, obj){

    //Outer .each loop is for traversing the JSON rows
    tblSomething += '<tr>';

    //Inner .each loop is for traversing JSON columns
    $.each(obj, function(key, value){
    tblSomething += '<td>' + value + '</td>';
    });
    tblSomething += '</tr>';
    });

    tblSomething += '</tbody>';

    $('#tblSomething').html(tblSomething);
    },
    error: function(jqXHR, textStatus, errorThrown){
    alert('Hey, something went wrong because: ' + errorThrown);
    }
    });


    });
    </script>


    <table id = "tblSomething" class = "table table-hover"></table>

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

In iOS 5, the Manifest.mbdx file was eliminated. For the purpose of this article, it was redundant anyway, because the domain and path are in Manifest.mbdb and the ID hash can be generated with SHA1.

Here is my update of galloglass's code so it works with backups of iOS 5 devices. The only changes are elimination of process_mbdx_file() and addition of a few lines in process_mbdb_file().

Tested with backups of an iPhone 4S and an iPad 1, both with plenty of apps and files.

#!/usr/bin/env python
import sys
import hashlib

mbdx = {}

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
        fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
        id = hashlib.sha1(fullpath)
        mbdx[fileinfo['start_offset']] = id.hexdigest()
    return mbdb

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

What is the difference between --save and --save-dev?

--save-dev saves semver spec into "devDependencies" array in your package descriptor file, --save saves it into "dependencies" instead.

Where is Java Installed on Mac OS X?

For :

  • OS X : 10.11.6

  • Java : 8

I confirm the answer of @Morrie .

   export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home;

But if you are running containers your life will be easier

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

jQuery window scroll event does not fire up

To whom its just not working to (like me) no matter what you tried: <element onscroll="myFunction()"></element> works like a charm

exactly as they explain in W3 schools https://www.w3schools.com/tags/ev_onscroll.asp

how to concat two columns into one with the existing column name in mysql?

Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.

You can use the SQL statement something like:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;

BTW, why couldn't you use FullName instead of FirstName? Like this:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;

Error during installing HAXM, VT-X not working

BIOS -> Overclockong -> CPU Features -> Intel Virtualization Tech -> Enabled

Reload a DIV without reloading the whole page

Your code works, but the fadeIn doesn't, because it's already visible. I think the effect you want to achieve is: fadeOutloadfadeIn:

var auto_refresh = setInterval(function () {
    $('.View').fadeOut('slow', function() {
        $(this).load('/echo/json/', function() {
            $(this).fadeIn('slow');
        });
    });
}, 15000); // refresh every 15000 milliseconds

Try it here: http://jsfiddle.net/kelunik/3qfNn/1/

Additional notice: As Khanh TO mentioned, you may need to get rid of the browser's internal cache. You can do so using $.ajax and $.ajaxSetup ({ cache: false }); or the random-hack, he mentioned.

jQuery multiple conditions within if statement

A more general approach:

if ( ($("body").hasClass("homepage") || $("body").hasClass("contact")) && (theLanguage == 'en-gb') )   {

       // Do something

}