Programs & Examples On #Queueuserworkitem

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

Subtracting two lists in Python

Python 2.7+ and 3.0 have collections.Counter (a.k.a. multiset). The documentation links to Recipe 576611: Counter class for Python 2.5:

from operator import itemgetter
from heapq import nlargest
from itertools import repeat, ifilter

class Counter(dict):
    '''Dict subclass for counting hashable objects.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    >>> Counter('zyzygy')
    Counter({'y': 3, 'z': 2, 'g': 1})

    '''

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''        
        self.update(iterable, **kwds)

    def __missing__(self, key):
        return 0

    def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abracadabra').most_common(3)
        [('a', 5), ('r', 2), ('b', 2)]

        '''        
        if n is None:
            return sorted(self.iteritems(), key=itemgetter(1), reverse=True)
        return nlargest(n, self.iteritems(), key=itemgetter(1))

    def elements(self):
        '''Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        If an element's count has been set to zero or is a negative number,
        elements() will ignore it.

        '''
        for elem, count in self.iteritems():
            for _ in repeat(None, count):
                yield elem

    # Override dict methods where the meaning changes for Counter objects.

    @classmethod
    def fromkeys(cls, iterable, v=None):
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, **kwds):
        '''Like dict.update() but add counts instead of replacing them.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''        
        if iterable is not None:
            if hasattr(iterable, 'iteritems'):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    dict.update(self, iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def copy(self):
        'Like dict.copy() but returns a Counter instance instead of a dict.'
        return Counter(self)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            dict.__delitem__(self, elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})


        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] + other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem in set(self) | set(other):
            newcount = self[elem] - other[elem]
            if newcount > 0:
                result[elem] = newcount
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _max = max
        result = Counter()
        for elem in set(self) | set(other):
            newcount = _max(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        _min = min
        result = Counter()
        if len(self) < len(other):
            self, other = other, self
        for elem in ifilter(self.__contains__, other):
            newcount = _min(self[elem], other[elem])
            if newcount > 0:
                result[elem] = newcount
        return result


if __name__ == '__main__':
    import doctest
    print doctest.testmod()

Then you can write

 a = Counter([0,1,2,1,0])
 b = Counter([0, 1, 1])
 c = a - b
 print list(c.elements())  # [0, 2]

Combine [NgStyle] With Condition (if..else)

<h2 [ngStyle]="serverStatus == 'Offline'? {'color': 'red'{'color':'green'}">Server with ID: {{serverId}} is {{getServerStatus()}} </h2>

or you can also use something like this:

<h2 [ngStyle]="{backgroundColor: getColor()}">Server with ID: {{serverId}} is {{getServerStatus()}}</h2>

and in the *.ts

getColor(){return this.serverStatus === 'Offline' ? 'red' : 'green';}

How to create jar file with package structure?

Simply more than above -

  1. Keep your Java packaging contents inside a directory and make sure there is nothing inside except your Java packages and their corresponding Java classes.

  2. Open Command(If Windows) Prompt, reach to the containing directory path like below -

    C:> cd "C:\Users\UserABC\Downloads\Current Folder"

    C:\Users\UserABC\Downloads\Current Folder>jar cvf hello-world-1.0.1.jar .

HTML5 Pre-resize images before uploading

The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).

I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):

private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
    if (width <= maxWidth && height <= maxHeight)
      return { width, height };
    else if (width / maxWidth > height / maxHeight)
      return { width: maxWidth, height: height * maxWidth / width};
    else
      return { width: width * maxHeight / height, height: maxHeight };
  }

How should I declare default values for instance variables in Python?

You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:

>>> class TestClass(object):
...     t = None
... 
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>

Also if you need defaults:

>>> class TestClassDefaults(object):
...    t = None
...    def __init__(self, t=None):
...       self.t = t
... 
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>

Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__.

How to find if an array contains a string

Another simple way using JOIN and INSTR

Sub Sample()
    Dim Mainfram(4) As String, strg As String
    Dim cel As Range
    Dim Delim As String

    Delim = "#"

    Mainfram(0) = "apple"
    Mainfram(1) = "pear"
    Mainfram(2) = "orange"
    Mainfram(3) = "fruit"

    strg = Join(Mainfram, Delim)
    strg = Delim & strg

    For Each cel In Selection
        If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
        Rows(cel.Row).Style = "Accent1"
    Next cel
End Sub

disable viewport zooming iOS 10+ safari?

I tried the previous answer about pinch-to-zoom

document.documentElement.addEventListener('touchstart', function (event) {
    if (event.touches.length > 1) {
        event.preventDefault();
    }
}, false);

however sometime the screen still zoom when the event.touches.length > 1 I found out the best way is using touchmove event, to avoid any finger moving on the screen. The code will be something like this:

document.documentElement.addEventListener('touchmove', function (event) {
    event.preventDefault();      
}, false);

Hope it will help.

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Changing the target framework from .NET Framework 4 Client Profile to .NET Framework 4 fixed this problem for me.

So in your example: set the target framework on MyWebProject1 to .NET Framework 4

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

The network path was not found

At The Beginning, I faced the same error but with a different scenario. I was having two connection strings, one for ado.net, and the other was for the EntityFramework, Both connections where correct. The problem specifically was within the edmx file of the EF, where I changed the ProviderManifestToken="2012" to ProviderManifestToken="2008" therefore, the application worked fine after that.

Convert DataTable to IEnumerable<T>

If you are producing the DataTable from an SQL query, have you considered simply using Dapper instead?

Then, instead of making a SqlCommand with SqlParameters and a DataTable and a DataAdapter and on and on, which you then have to laboriously convert to a class, you just define the class, make the query column names match the field names, and the parameters are bound easily by name. You already have the TankReading class defined, so it will be really simple!

using Dapper;

// Below can be SqlConnection cast to DatabaseConnection, too.
DatabaseConnection connection = // whatever
IEnumerable<TankReading> tankReadings = connection.Query<TankReading>(
   "SELECT * from TankReading WHERE Value = @value",
   new { value = "tank1" } // note how `value` maps to `@value`
);
return tankReadings;

Now isn't that awesome? Dapper is very optimized and will give you darn near equivalent performance as reading directly with a DataAdapter.

If your class has any logic in it at all or is immutable or has no parameterless constructor, then you probably do need to have a DbTankReading class (as a pure POCO/Plain Old Class Object):

// internal because it should only be used in the data source project and not elsewhere
internal sealed class DbTankReading {
   int TankReadingsID { get; set; }
   DateTime? ReadingDateTime { get; set; }
   int ReadingFeet { get; set; }
   int ReadingInches { get; set; }
   string MaterialNumber { get; set; }
   string EnteredBy { get; set; }
   decimal ReadingPounds { get; set; }
   int MaterialID { get; set; }
   bool Submitted { get; set; }
}

You'd use that like this:

IEnumerable<TankReading> tankReadings = connection
   .Query<DbTankReading>(
      "SELECT * from TankReading WHERE Value = @value",
      new { value = "tank1" } // note how `value` maps to `@value`
   )
   .Select(tr => new TankReading(
      tr.TankReadingsID,
      tr.ReadingDateTime,
      tr.ReadingFeet,
      tr.ReadingInches,
      tr.MaterialNumber,
      tr.EnteredBy,
      tr.ReadingPounds,
      tr.MaterialID,
      tr.Submitted
   });

Despite the mapping work, this is still less painful than the data table method. This also lets you perform some kind of logic, though if the logic is any more than very simple straight-across mapping, I'd put the logic into a separate TankReadingMapper class.

HTTP client timeout and server timeout

There's many forms of timeout, are you after the connection timeout, request timeout or time to live (time before TCP connection stops).

The default TimeToLive on Firefox is 115s (network.http.keep-alive.timeout)

The default connection timeout on Firefox is 250s (network.http.connection-retry-timeout)

The default request timeout for Firefox is 30s (network.http.pipelining.read-timeout).

The time it takes to do an HttpRequest depends on if a connection has been made this has to be within 250s which I'm guessing you're not after. You're probably after the request timeout which I think is 30,000ms (30s) so to conclude I'd say it's timing out with a connection time out that's why you got a response back after ~150s though I haven't really tested this.

Rank function in MySQL

One option is to use a ranking variable, such as the following:

SELECT    first_name,
          age,
          gender,
          @curRank := @curRank + 1 AS rank
FROM      person p, (SELECT @curRank := 0) r
ORDER BY  age;

The (SELECT @curRank := 0) part allows the variable initialization without requiring a separate SET command.

Test case:

CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));

INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');

Result:

+------------+------+--------+------+
| first_name | age  | gender | rank |
+------------+------+--------+------+
| Kathy      |   18 | F      |    1 |
| Jane       |   20 | F      |    2 |
| Nick       |   22 | M      |    3 |
| Bob        |   25 | M      |    4 |
| Anne       |   25 | F      |    5 |
| Jack       |   30 | M      |    6 |
| Bill       |   32 | M      |    7 |
| Steve      |   36 | M      |    8 |
+------------+------+--------+------+
8 rows in set (0.02 sec)

How to check file input size with jQuery?

Plese try this:

var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;

if (sizeInKB >= sizeLimit) {
    alert("Max file size 30KB");
    return false;
}

Is there a way to provide named parameters in a function call in JavaScript?

No - the object approach is JavaScript's answer to this. There is no problem with this provided your function expects an object rather than separate params.

How to change the DataTable Column Name?

Use:

dt.Columns["Name"].ColumnName = "xyz";
dt.AcceptChanges();

or

dt.Columns[0].ColumnName = "xyz";
dt.AcceptChanges();

How to add elements of a Java8 stream into an existing List

You just have to refer your original list to be the one that the Collectors.toList() returns.

Here's a demo:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Reference {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    System.out.println(list);

    // Just collect even numbers and start referring the new list as the original one.
    list = list.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());
    System.out.println(list);
  }
}

And here's how you can add the newly created elements to your original list in just one line.

List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList())
);

That's what this Functional Programming Paradigm provides.

Case insensitive string as HashMap key

Two choices come to my mind:

  1. You could use directly the s.toUpperCase().hashCode(); as the key of the Map.
  2. You could use a TreeMap<String> with a custom Comparator that ignore the case.

Otherwise, if you prefer your solution, instead of defining a new kind of String, I would rather implement a new Map with the required case insensibility functionality.

How can I align text in columns using Console.WriteLine?

I really like those libraries mentioned here but I had an idea that could be simpler than just padding or doing tons of string manipulations,

You could just manually set your cursor using the maximum string length of your data. Here's some code to get the idea (not tested):

var column1[] = {"test", "longer test", "etc"}
var column2[] = {"data", "more data", "etc"}
var offset = strings.OrderByDescending(s => s.Length).First().Length;
for (var i = 0; i < column.Length; i++) {
    Console.Write(column[i]);
    Console.CursorLeft = offset + 1;
    Console.WriteLine(column2[i]);
}

you could easily extrapolate if you have more rows.

Compare two columns using pandas

You could use np.where. If cond is a boolean array, and A and B are arrays, then

C = np.where(cond, A, B)

defines C to be equal to A where cond is True, and B where cond is False.

import numpy as np
import pandas as pd

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])

df['que'] = np.where((df['one'] >= df['two']) & (df['one'] <= df['three'])
                     , df['one'], np.nan)

yields

  one  two three  que
0  10  1.2   4.2   10
1  15   70  0.03  NaN
2   8    5     0  NaN

If you have more than one condition, then you could use np.select instead. For example, if you wish df['que'] to equal df['two'] when df['one'] < df['two'], then

conditions = [
    (df['one'] >= df['two']) & (df['one'] <= df['three']), 
    df['one'] < df['two']]

choices = [df['one'], df['two']]

df['que'] = np.select(conditions, choices, default=np.nan)

yields

  one  two three  que
0  10  1.2   4.2   10
1  15   70  0.03   70
2   8    5     0  NaN

If we can assume that df['one'] >= df['two'] when df['one'] < df['two'] is False, then the conditions and choices could be simplified to

conditions = [
    df['one'] < df['two'],
    df['one'] <= df['three']]

choices = [df['two'], df['one']]

(The assumption may not be true if df['one'] or df['two'] contain NaNs.)


Note that

a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])

defines a DataFrame with string values. Since they look numeric, you might be better off converting those strings to floats:

df2 = df.astype(float)

This changes the results, however, since strings compare character-by-character, while floats are compared numerically.

In [61]: '10' <= '4.2'
Out[61]: True

In [62]: 10 <= 4.2
Out[62]: False

Secure hash and salt for PHP passwords

A much shorter and safer answer - don't write your own password mechanism at all, use a tried and tested mechanism.

  • PHP 5.5 or higher: password_hash() is good quality and part of PHP core.
  • PHP 4.x (obsolete): OpenWall's phpass library is much better than most custom code - used in WordPress, Drupal, etc.

Most programmers just don't have the expertise to write crypto related code safely without introducing vulnerabilities.

Quick self-test: what is password stretching and how many iterations should you use? If you don't know the answer, you should use password_hash(), as password stretching is now a critical feature of password mechanisms due to much faster CPUs and the use of GPUs and FPGAs to crack passwords at rates of billions of guesses per second (with GPUs).

For example, you can crack all 8-character Windows passwords in 6 hours using 25 GPUs installed in 5 desktop PCs. This is brute-forcing i.e. enumerating and checking every 8-character Windows password, including special characters, and is not a dictionary attack. That was in 2012, as of 2018 you could use fewer GPUs, or crack faster with 25 GPUs.

There are also many rainbow table attacks on Windows passwords that run on ordinary CPUs and are very fast. All this is because Windows still doesn't salt or stretch its passwords, even in Windows 10 - don't make the same mistake as Microsoft did!

See also:

  • excellent answer with more about why password_hash() or phpass are the best way to go.
  • good blog article giving recommmended 'work factors' (number of iterations) for main algorithms including bcrypt, scrypt and PBKDF2.

Eloquent ->first() if ->exists()

(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

Oh, also: count() instead if exists but this could be something used after get.

What is an Android PendingIntent?

A future intent that other apps can use.
And here's an example for creating one:

Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(context, 0, intent, 0);

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

Programmatically relaunch/recreate an activity?

i found out the best way to refresh your Fragment when data change

if you have a button "search", you have to initialize your ARRAY list inside the button

mSearchBtn.setOnClickListener(new View.OnClickListener() {

@Override public void onClick(View v) {

mList = new ArrayList<Node>();

firebaseSearchQuery.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {


      for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

        Node p = dataSnapshot1.getValue(Node .class);
        mList.add(p);
      }
      YourAdapter = new NodeAdapter(getActivity(), mList);
      mRecyclerView.setAdapter(YourAdapter );

    }

Using an Alias in a WHERE clause

Or you can have your alias in a HAVING clause

.Net: How do I find the .NET version?

Per Microsoft in powershell:

Get-ChildItem "hklm:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" | Get-ItemPropertyValue -Name Release | % { $_ -ge 394802 }

See the table at this link to get the DWORD value to search for specific versions:

https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#ps_a

removeEventListener on anonymous functions in JavaScript

To give a more up-to-date approach to this:

//one-time fire
element.addEventListener('mousedown', {
  handleEvent: function (evt) {
    element.removeEventListener(evt.type, this, false);
  }
}, false);

What's the best practice to "git clone" into an existing folder?

Don't clone, fetch instead. In the repo:

git init
git remote add origin $url_of_clone_source
git fetch origin
git checkout -b master --track origin/master # origin/master is clone's default

Then you can reset the tree to get the commit you want:

git reset origin/master # or whatever commit you think is proper...

and you are like you cloned.

The interesting question here (and the one without answer): How to find out which commit your naked tree was based on, hence to which position to reset to.

How do I keep Python print from adding newlines or spaces?

For completeness, one other way is to clear the softspace value after performing the write.

import sys
print "hello",
sys.stdout.softspace=0
print "world",
print "!"

prints helloworld !

Using stdout.write() is probably more convenient for most cases though.

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

I used the below to solve this problem.

import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);

Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.

Camel Case is usually without spaces between words.

Print <div id="printarea"></div> only?

@Kevin Florida If you have multiple divs with same class, you can use it like this:

 <div style="display:none">
   <div id="modal-2" class="printableArea">
     <input type="button" class="printdiv-btn" value="print a div!" />
   </div>
 </div>

i was using Colorbox inner content type

$(document).on('click', '.printdiv-btn', function(e) {
    e.preventDefault();

    var $this = $(this);
    var originalContent = $('body').html();
    var printArea = $this.parents('.printableArea').html();

    $('body').html(printArea);
    window.print();
    $('body').html(originalContent);
});

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

How can I remove all my changes in my SVN working directory?

If you are on windows, the following for loop will revert all uncommitted changes made to your workspace:

for /F "tokens=1,*" %%d in ('svn st') do (
  svn revert "%%e"
)

If you want to remove all uncommitted changes and all unversioned objects, it will require 2 loops:

for /F "tokens=1,*" %%d in ('svn st') do (
  svn revert "%%e"
)
for /F "tokens=1,*" %%d in ('svn st') do (
  svn rm --force "%%e"
)

What is the right way to debug in iPython notebook?

Your return function is in line of def function(main function), you must give one tab to it. And Use

%%debug 

instead of

%debug 

to debug the whole cell not only line. Hope, maybe this will help you.

Regex Last occurrence?

Your negative lookahead solution would e.g. be this:

\\(?:.(?!\\))+$

See it here on Regexr

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

dir /ad /b /s will give the required answer.

Iterate through string array in Java

Those algorithms are both incorrect because of the comparison:

for( int i = 0; i < elements.length - 1; i++)

or

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

It's true that the array elements range from 0 to length - 1, but the comparison in that case should be less than or equal to. Those should be:

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

or

for(int i = 0; i <= elements.length - 1; i++) {

or

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

The array ["a", "b"] would iterate as:

i = 0 is < 2: elements[0] yields "a"

i = 1 is < 2: elements[1] yields "b"

then exit the loop because 2 is not < 2.

The incorrect examples both exit the loop prematurely and only execute with the first element in this simple case of two elements.

Colorizing text in the console with C++

I'm not sure what you really want to do, but my guess is you want your C++ program to output colored text in the console, right ? Don't know about Windows, but on all Unices (including Mac OS X), you'd simply use ANSI escape sequences for that.

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

Verify host key with pysftp

Do not set cnopts.hostkeys = None (as the second most upvoted answer shows), unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.


Use CnOpts.hostkeys (returns HostKeys) to manage trusted host keys.

cnopts = pysftp.CnOpts(knownhosts='known_hosts')

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

where the known_hosts contains a server public key(s)] in a format like:

example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

If you do not want to use an external file, you can also use

from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add('example.com', 'ssh-rsa', key)

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

Though as of pysftp 0.2.9, this approach will issue a warning, what seems like a bug:
"Failed to load HostKeys" warning while connecting to SFTP server with pysftp


An easy way to retrieve the host key in the needed format is using OpenSSH ssh-keyscan:

$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

(due to a bug in pysftp, this does not work, if the server uses non-standard port – the entry starts with [example.com]:port + beware of redirecting ssh-keyscan to a file in PowerShell)

You can also make the application do the same automatically:
Use Paramiko AutoAddPolicy with pysftp
(It will automatically add host keys of new hosts to known_hosts, but for known host keys, it will not accept a changed key)


Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

See my article Where do I get SSH host key fingerprint to authorize the server?
It's for my WinSCP SFTP client, but most information there is valid in general.


If you need to verify the host key using its fingerprint only, see Python - pysftp / paramiko - Verify host key using its fingerprint.

What is the difference between max-device-width and max-width for mobile web?

If you are making a cross-platform app (eg. using phonegap/cordova) then,

Don't use device-width or device-height. Rather use width or height in CSS media queries because Android device will give problems in device-width or device-height. For iOS it works fine. Only android devices doesn't support device-width/device-height.

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

Multi-line labels are also a little tricky, you might want to check out this wrap function.

How to compare different branches in Visual Studio Code

It's now possible by using the githistory extension.

Here's a small trick though: You can compare the latest commits from each branch and that would be the same as comparing two branches side by side or creating a PR.

Here's how to do that using githistory extension:

  1. Open githistory
  2. Pick the latest commit from your current branch by clicking on "Git Commit Icon" → (Usually it should be latest commit it the list). From the opened dropdown menu click on "Select this commit".
  3. Pick the latest commit from the branch you want to compare to by clicking "Git Commit Icon".
  4. As a result, the dropdown should appear with a few options → Select the last option that says "Compare with SHA" and you'll see the diff.

iPhone app could not be installed at this time

As for Xcode 5.1, the problem was in arm64 architecture in VALID_ARCHS. Building the release configuration for 5.0 device locally gives the following error:

Xcode cannot install or launch applications supporting the 64-bit architecture on devices running iOS versions prior to 6.0. This configuration is supported for distribution through the iOS App Store, but cannot be used during development with Xcode. To continue, edit the Run scheme action and select a build configuration that does not include the 64-bit architecture.

Removing arm64 from VALID_ARCHS solves the issue. In my case I had to create a separate branch for testing on iOS 5 devices.

How to cherry-pick multiple commits

To cherry pick from a commit id up to the tip of the branch, you can use:

git cherry-pick commit_id^..branch_name

Efficient way to do batch INSERTS with JDBC

Though the question asks inserting efficiently to Oracle using JDBC, I'm currently playing with DB2 (On IBM mainframe), conceptually inserting would be similar so thought it might be helpful to see my metrics between

  • inserting one record at a time

  • inserting a batch of records (very efficient)

Here go the metrics

1) Inserting one record at a time

public void writeWithCompileQuery(int records) {
    PreparedStatement statement;

    try {
        Connection connection = getDatabaseConnection();
        connection.setAutoCommit(true);

        String compiledQuery = "INSERT INTO TESTDB.EMPLOYEE(EMPNO, EMPNM, DEPT, RANK, USERNAME)" +
                " VALUES" + "(?, ?, ?, ?, ?)";
        statement = connection.prepareStatement(compiledQuery);

        long start = System.currentTimeMillis();

        for(int index = 1; index < records; index++) {
            statement.setInt(1, index);
            statement.setString(2, "emp number-"+index);
            statement.setInt(3, index);
            statement.setInt(4, index);
            statement.setString(5, "username");

            long startInternal = System.currentTimeMillis();
            statement.executeUpdate();
            System.out.println("each transaction time taken = " + (System.currentTimeMillis() - startInternal) + " ms");
        }

        long end = System.currentTimeMillis();
        System.out.println("total time taken = " + (end - start) + " ms");
        System.out.println("avg total time taken = " + (end - start)/ records + " ms");

        statement.close();
        connection.close();

    } catch (SQLException ex) {
        System.err.println("SQLException information");
        while (ex != null) {
            System.err.println("Error msg: " + ex.getMessage());
            ex = ex.getNextException();
        }
    }
}

The metrics for 100 transactions :

each transaction time taken = 123 ms
each transaction time taken = 53 ms
each transaction time taken = 48 ms
each transaction time taken = 48 ms
each transaction time taken = 49 ms
each transaction time taken = 49 ms
...
..
.
each transaction time taken = 49 ms
each transaction time taken = 49 ms
total time taken = 4935 ms
avg total time taken = 49 ms

The first transaction is taking around 120-150ms which is for the query parse and then execution, the subsequent transactions are only taking around 50ms. (Which is still high, but my database is on a different server(I need to troubleshoot the network))

2) With insertion in a batch (efficient one) - achieved by preparedStatement.executeBatch()

public int[] writeInABatchWithCompiledQuery(int records) {
    PreparedStatement preparedStatement;

    try {
        Connection connection = getDatabaseConnection();
        connection.setAutoCommit(true);

        String compiledQuery = "INSERT INTO TESTDB.EMPLOYEE(EMPNO, EMPNM, DEPT, RANK, USERNAME)" +
                " VALUES" + "(?, ?, ?, ?, ?)";
        preparedStatement = connection.prepareStatement(compiledQuery);

        for(int index = 1; index <= records; index++) {
            preparedStatement.setInt(1, index);
            preparedStatement.setString(2, "empo number-"+index);
            preparedStatement.setInt(3, index+100);
            preparedStatement.setInt(4, index+200);
            preparedStatement.setString(5, "usernames");
            preparedStatement.addBatch();
        }

        long start = System.currentTimeMillis();
        int[] inserted = preparedStatement.executeBatch();
        long end = System.currentTimeMillis();

        System.out.println("total time taken to insert the batch = " + (end - start) + " ms");
        System.out.println("total time taken = " + (end - start)/records + " s");

        preparedStatement.close();
        connection.close();

        return inserted;

    } catch (SQLException ex) {
        System.err.println("SQLException information");
        while (ex != null) {
            System.err.println("Error msg: " + ex.getMessage());
            ex = ex.getNextException();
        }
        throw new RuntimeException("Error");
    }
}

The metrics for a batch of 100 transactions is

total time taken to insert the batch = 127 ms

and for 1000 transactions

total time taken to insert the batch = 341 ms

So, making 100 transactions in ~5000ms (with one trxn at a time) is decreased to ~150ms (with a batch of 100 records).

NOTE - Ignore my network which is super slow, but the metrics values would be relative.

How to add reference to a method parameter in javadoc?

As you can see in the Java Source of the java.lang.String class:

/**
 * Allocates a new <code>String</code> that contains characters from
 * a subarray of the character array argument. The <code>offset</code>
 * argument is the index of the first character of the subarray and
 * the <code>count</code> argument specifies the length of the
 * subarray. The contents of the subarray are copied; subsequent
 * modification of the character array does not affect the newly
 * created string.
 *
 * @param      value    array that is the source of characters.
 * @param      offset   the initial offset.
 * @param      count    the length.
 * @exception  IndexOutOfBoundsException  if the <code>offset</code>
 *               and <code>count</code> arguments index characters outside
 *               the bounds of the <code>value</code> array.
 */
public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count < 0) {
        throw new StringIndexOutOfBoundsException(count);
    }
    // Note: offset or count might be near -1>>>1.
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }

    this.value = new char[count];
    this.count = count;
    System.arraycopy(value, offset, this.value, 0, count);
}

Parameter references are surrounded by <code></code> tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).

What is the use of DesiredCapabilities in Selenium WebDriver?

When you run selenium WebDriver, the WebDriver opens a remote server in your computer's local host. Now, this server, called the Selenium Server, is used to interpret your code into actions to run or "drive" the instance of a real browser known as either chromebrowser, ie broser, ff browser, etc.

So, the Selenium Server can interact with different browser properties and hence it has many "capabilities".

Now what capabilities do you desire? Consider a scenario where you are validating if files have been downloaded properly in your app but, however, you do not have a desktop automation tool. In the case where you click the download link and a desktop pop up shows up to ask where to save and/or if you want to download. Your next route to bypass that would be to suppress that pop up. How? Desired Capabilities.

There are other such examples. In summary, Selenium Server can do a lot, use Desired Capabilities to tailor it to your need.

Delegation: EventEmitter or Observable in Angular

Breaking news: I've added another answer that uses an Observable rather than an EventEmitter. I recommend that answer over this one. And actually, using an EventEmitter in a service is bad practice.


Original answer: (don't do this)

Put the EventEmitter into a service, which allows the ObservingComponent to directly subscribe (and unsubscribe) to the event:

import {EventEmitter} from 'angular2/core';

export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emit(number) {
    this.navchange.emit(number);
  }
  subscribe(component, callback) {
    // set 'this' to component when callback is called
    return this.navchange.subscribe(data => call.callback(component, data));
  }
}

@Component({
  selector: 'obs-comp',
  template: 'obs component, index: {{index}}'
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private navService:NavService) {
   this.subscription = this.navService.subscribe(this, this.selectedNavItem);
  }
  selectedNavItem(item: number) {
    console.log('item index changed!', item);
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">item 1 (click me)</div>
  `,
})
export class Navigation {
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emit(item);
  }
}

If you try the Plunker, there are a few things I don't like about this approach:

  • ObservingComponent needs to unsubscribe when it is destroyed
  • we have to pass the component to subscribe() so that the proper this is set when the callback is called

Update: An alternative that solves the 2nd bullet is to have the ObservingComponent directly subscribe to the navchange EventEmitter property:

constructor(private navService:NavService) {
   this.subscription = this.navService.navchange.subscribe(data =>
     this.selectedNavItem(data));
}

If we subscribe directly, then we wouldn't need the subscribe() method on the NavService.

To make the NavService slightly more encapsulated, you could add a getNavChangeEmitter() method and use that:

getNavChangeEmitter() { return this.navchange; }  // in NavService

constructor(private navService:NavService) {  // in ObservingComponent
   this.subscription = this.navService.getNavChangeEmitter().subscribe(data =>
     this.selectedNavItem(data));
}

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

Index of duplicates items in a python list

In a single line with pandas 1.2.2 and numpy:

 import numpy as np
 import pandas as pd
 
 idx = np.where(pd.DataFrame(List).duplicated(keep=False))

The argument keep=False will mark every duplicate as True and np.where() will return an array with the indices where the element in the array was True.

define() vs. const

define I use for global constants.

const I use for class constants.

You cannot define into class scope, and with const you can. Needless to say, you cannot use const outside class scope.

Also, with const, it actually becomes a member of the class, and with define, it will be pushed to global scope.

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

Pass by Reference / Value in C++

I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.

I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:

    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

I vote for the following definition:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.

That means that the following is pass by value:

void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5

1 is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2 is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3 is pass by value, because the parameter has not reference type. 4 is pass by value for the same reason. 5 is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):

void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Provide a User-Agent header:

import requests

url = 'http://www.ichangtou.com/#company:data_000008.html'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

response = requests.get(url, headers=headers)
print(response.content)

FYI, here is a list of User-Agent strings for different browsers:


As a side note, there is a pretty useful third-party package called fake-useragent that provides a nice abstraction layer over user agents:

fake-useragent

Up to date simple useragent faker with real world database

Demo:

>>> from fake_useragent import UserAgent
>>> ua = UserAgent()
>>> ua.chrome
u'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'
>>> ua.random
u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'

Can I get image from canvas element and use it in img src tag?

I'm getting SecurityError: The operation is insecure.

when using canvas.toDataURL('image/jpg'); in safari browser

Change color of bootstrap navbar on hover link?

Updated 2018

You can change the Navbar link colors with CSS to override Bootstrap colors...

Bootstrap 4

.navbar-nav .nav-item .nav-link {
    color: red;
}
.navbar-nav .nav-item.active .nav-link,
.navbar-nav .nav-item:hover .nav-link {
    color: pink;
}

Bootstrap 4 navbar link color demo

Bootstrap 3

.navbar .navbar-nav > li > a,
.navbar .navbar-nav > .active > a{
    color: orange;
}

.navbar .navbar-nav > li > a:hover,
.navbar .navbar-nav > li > a:focus,
.navbar .navbar-nav > .active > a:hover,
.navbar .navbar-nav > .active > a:focus {
    color: red;
}

Bootstrap 3 navbar link color demo


The change or customize the entire Navbar color, see: https://stackoverflow.com/a/18530995/171456

jQuery show/hide not working

Demo

_x000D_
_x000D_
$( '.expand' ).click(function() {_x000D_
  $( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
    margin-left:auto;_x000D_
    margin-right:auto;_x000D_
    width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
    height:20px;_x000D_
    background-color:#CCC;_x000D_
    display:block;_x000D_
    border:#333 solid 1px;_x000D_
    margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
 float:right;_x000D_
 height: 100%;_x000D_
 padding-right:5px;_x000D_
 cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
    width: 100%;_x000D_
    height:100px;   _x000D_
    background-color:#0F3;_x000D_
    margin-top: -2px;_x000D_
    display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://api.jquery.com/toggle/
"Display or hide the matched elements."

This is much shorter in code than using show() and hide() methods.

How can I refresh c# dataGridView after update ?

You can use SqlDataAdapter to update the DataGridView

     using (SqlConnection conn = new SqlConnection(connectionString))
        {
            using (SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Table", conn))
            {
               DataTable dt = new DataTable();
                 ad.Fill(dt);
               dataGridView1.DataSource = dt;
            }
        }

The equivalent of wrap_content and match_parent in flutter?

I used this solution, you have to define the height and width of your screen using MediaQuery:

 Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width
  )

Find out if string ends with another string in C++

Let a be a string and b the string you look for. Use a.substr to get the last n characters of a and compare them to b (where n is the length of b)

Or use std::equal (include <algorithm>)

Ex:

bool EndsWith(const string& a, const string& b) {
    if (b.size() > a.size()) return false;
    return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin());
}

PostgreSQL - query from bash script as database user 'postgres'

To ans to @Jason 's question, in my bash script, I've dome something like this (for my purpose):

dbPass='xxxxxxxx'
.....
## Connect to the DB
PGPASSWORD=${dbPass} psql -h ${dbHost} -U ${myUsr} -d ${myRdb} -P pager=on --set AUTOCOMMIT=off

The another way of doing it is:

psql --set AUTOCOMMIT=off --set ON_ERROR_STOP=on -P pager=on \
     postgresql://${myUsr}:${dbPass}@${dbHost}/${myRdb}

but you have to be very careful about the password: I couldn't make a password with a ' and/or a : to work in that way. So gave up in the end.

-S

ValueError: unconverted data remains: 02:05

The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.

Jenkins "Console Output" log location in filesystem

@Bruno Lavit has a great answer, but if you want you can just access the log and download it as txt file to your workspace from the job's URL:

${BUILD_URL}/consoleText

Then it's only a matter of downloading this page to your ${Workspace}

  • You can use "Invoke ANT" and use the GET target
  • On Linux you can use wget to download it to your workspace
  • etc.

Good luck!

Edit: The actual log file on the file system is not on the slave, but kept in the Master machine. You can find it under: $JENKINS_HOME/jobs/$JOB_NAME/builds/lastSuccessfulBuild/log

If you're looking for another build just replace lastSuccessfulBuild with the build you're looking for.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

It has 3 solutions that other guys told upper... but when try Application_Start solution, My other jQuery library like Pickup_Date_and_Time doesn't work... so I test second way and it's answered: 1- set the Target FrameWork to Pre 4.5 2- Use " UnobtrusiveValidationMode="None" " in your page header =>

<%@ Page Title="" Language="C#" 
    MasterPageFile="~/Master/MasteOfHotel.Master" 
    UnobtrusiveValidationMode="None" %>

it works for me and doesn't disrupt my other jQuery function.

Check if PHP session has already started

Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.

if (strlen(session_id()) < 1) {
    session_start();
}

SQL-Server: The backup set holds a backup of a database other than the existing

I was just trying to solve this issue.

I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.

Hopefully this helps somebody else.

How do I detect the Python version at runtime?

The best solution depends on how much code is incompatible. If there are a lot of places you need to support Python 2 and 3, six is the compatibility module. six.PY2 and six.PY3 are two booleans if you want to check the version.

However, a better solution than using a lot of if statements is to use six compatibility functions if possible. Hypothetically, if Python 3000 has a new syntax for next, someone could update six so your old code would still work.

import six

#OK
if six.PY2:
  x = it.next() # Python 2 syntax
else:
  x = next(it) # Python 3 syntax

#Better
x = six.next(it)

http://pythonhosted.org/six/

Cheers

jquery how to use multiple ajax calls one after the end of the other

I consider the following to be more pragmatic since it does not sequence the ajax calls but that is surely a matter of taste.

function check_ajax_call_count()
{
    if ( window.ajax_call_count==window.ajax_calls_completed )
    {
        // do whatever needs to be done after the last ajax call finished
    }
}
window.ajax_call_count = 0;
window.ajax_calls_completed = 10;
setInterval(check_ajax_call_count,100);

Now you can iterate window.ajax_call_count inside the success part of your ajax requests until it reaches the specified number of calls send (window.ajax_calls_completed).

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

Could not find any resources appropriate for the specified culture or the neutral culture

When I tried sharing a resource.resx file from one C# project with another C# project, I got this problem. The suggestion on moving the Form class to the beginning of its file wasn't appropriate. This is how I solved it. You essentially use a link from the second project to the first, then enable regeneration of the resource.designer.cs file.

  1. Delete the second project's Properties/Resources.resx file
  2. Add the first project's Properties/Resources.resx file as a LINK to the Properties folder in the second project. Don't add it to the root level of the project.
  3. Don't add the first project's Properties/Resources.designer.cs!
  4. On the properties of the second project's Resources.resx, add ResXFileCodeGenerator as the CustomTool
  5. Right click on the Resources.resx and select "Run Custom Tool". This will generate a new designer.cs file.

Note: I would avoid editing the resource.designer.cs file, as this is autogenerated.

How to create a zip file in Java

Spring boot controller, zip the files in a directory, and can be downloaded.

@RequestMapping(value = "/files.zip")
@ResponseBody
byte[] filesZip() throws IOException {
    File dir = new File("./");
    File[] filesArray = dir.listFiles();
    if (filesArray == null || filesArray.length == 0)
        System.out.println(dir.getAbsolutePath() + " have no file!");
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ZipOutputStream zipOut= new ZipOutputStream(bo);
    for(File xlsFile:filesArray){
        if(!xlsFile.isFile())continue;
        ZipEntry zipEntry = new ZipEntry(xlsFile.getName());
        zipOut.putNextEntry(zipEntry);
        zipOut.write(IOUtils.toByteArray(new FileInputStream(xlsFile)));
        zipOut.closeEntry();
    }
    zipOut.close();
    return bo.toByteArray();
}

SQL Server : fetching records between two dates?

You need to be more explicit and add the start and end times as well, down to the milliseconds:

select * 
from xxx 
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'

The database can very well interpret '2012-10-27' as '2012-10-27 00:00:00.000'.

How do I empty an array in JavaScript?

enter image description here

To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0'

  • length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases.
  • pop() : The pop method removes the last element from an array and returns that returns the removed value.
  • shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.

Example:

var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]

var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];

var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);

refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);

mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);

mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);

Array.prototype.poptill_length = function (e) {
  while (this.length) {
    if( this.length == e ) break;

    console.log('removed last element:', this.pop());
  }
};

  • new Array() | [] Create an Array with new memory location by using Array constructor or array literal.

    mainArr = []; // a new empty array is addressed to mainArr.
    
    var arr = new Array('10'); // Array constructor
    arr.unshift('1'); // add to the front
    arr.push('15'); // add to the end
    console.log("After Adding : ", arr); // ["1", "10", "15"]
    
    arr.pop(); // remove from the end
    arr.shift(); // remove from the front
    console.log("After Removing : ", arr); // ["10"]
    
    var arrLit = ['14', '17'];
    console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17}
    
    function indexedItem( arr ) {
        var indexedStr = "";
        arr.forEach(function(item, index, array) {
            indexedStr += "{"+index+","+item+"}";
            console.log(item, index);
        });
        return indexedStr;
    }
    
  • slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array.

    var shallowCopy = mainArr.slice(); // this is how to make a copy
    
    var cloneArr = mainArr.slice(0, 3); 
    console.log('Main', mainArr, '\tCloned', cloneArr);
    
    cloneArr.length = 0; // Clears current memory location of an array.
    console.log('Main', mainArr, '\tCloned', cloneArr);
    

Date to milliseconds and back to date in Swift

//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
    let currentDate = Date()
    let since1970 = currentDate.timeIntervalSince1970
    return Int(since1970 * 1000)
}

//Milliseconds to date
extension Int {
    func dateFromMilliseconds() -> Date {
        return Date(timeIntervalSince1970: TimeInterval(self)/1000)
    }
}

I removed seemingly useless conversion via string and all those random !.

curl: (60) SSL certificate problem: unable to get local issuer certificate

Had this problem after install Git Extensions v3.48. Tried to install mysysgit again but same problem. At the end, had to disable (please consider security implications!) Git SSL verification with:

git config --global http.sslVerify false

but if you have a domain certificate better add it to (Win7)

C:\Program Files (x86)\Git\bin\curl-ca-bundle.crt

How can I get a precise time, for example in milliseconds in Objective-C?

Also, here is how to calculate a 64-bit NSNumber initialized with the Unix epoch in milliseconds, in case that is how you want to store it in CoreData. I needed this for my app which interacts with a system that stores dates this way.

  + (NSNumber*) longUnixEpoch {
      return [NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970] * 1000];
  }

How to get folder path from file path with CMD

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

set filepath=%~dp1
set filename=%~nx1

Then you should have no issues.

How to remove leading whitespace from each line in a file

This Perl code edits your original file:

perl -i -ne 's/^\s+//;print' file

The next one makes a backup copy before editing the original file:

perl -i.bak -ne 's/^\s+//;print' file

Notice that Perl borrows heavily from sed (and AWK).

How to sort 2 dimensional array by column value?

As my usecase involves dozens of columns, I expanded @jahroy's answer a bit. (also just realized @charles-clayton had the same idea.)
I pass the parameter I want to sort by, and the sort function is redefined with the desired index for the comparison to take place on.

var ID_COLUMN=0
var URL_COLUMN=1

findings.sort(compareByColumnIndex(URL_COLUMN))

function compareByColumnIndex(index) {
  return function(a,b){
    if (a[index] === b[index]) {
        return 0;
    }
    else {
        return (a[index] < b[index]) ? -1 : 1;
    }
  }
}

Error In PHP5 ..Unable to load dynamic library

I had a similar problem, which led me here:

$ phpunit --version
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20131226/profiler.so' - /usr/lib/php5/20131226/profiler.so: cannot open shared object file: No such file or directory in Unknown on line 0
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.

Unlike the above, installing the software did not resolve my problem because I already had it.

$ sudo apt-get install php5-uprofiler
Reading package lists... Done
Building dependency tree       
Reading state information... Done
php5-uprofiler is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 52 not upgraded.

I found my solution via : Debian Bug report logs

$ sudo vim /etc/php5/mods-available/uprofiler.ini

I edited the ini file, changing extension=profiler.so to extension=uprofiler.so .... the result, happily:

$ phpunit --version
PHPUnit 5.7.17 by Sebastian Bergmann and contributors.

i.e. no more warning.

Responsive design with media query : screen size?

Here is media queries for common device breakpoints.

    /* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen  and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen  and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}

Cross Browser Flash Detection in Javascript

Detecting and embedding Flash within a web document is a surprisingly difficult task.

I was very disappointed with the quality and non-standards compliant markup generated from both SWFObject and Adobe's solutions. Additionally, my testing found Adobe's auto updater to be inconsistent and unreliable.

The JavaScript Flash Detection Library (Flash Detect) and JavaScript Flash HTML Generator Library (Flash TML) are a legible, maintainable and standards compliant markup solution.

-"Luke read the source!"

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

I installed Oracle Express Edition and I have the same error. One of the possible reason that is maybe your user does not have permission to open this shortcut. Here is how I solved the problem.

1. Right-click the shortcut and select the properties. enter image description here

2. Now click the Open File Location. Now you will see there is a Get_Started shortcut. enter image description here

3. Now right-click the Get_Started and select the properties. Then select your user and give permission to your user in the security tab. enter image description here

How do I open a URL from C++?

Here's an example in windows code using winsock.

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

Gradients on UIView and UILabels On iPhone

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

How to change an input button image using CSS?

You can use the <button> tag. For a submit, simply add type="submit". Then use a background image when you want the button to appear as a graphic.

Like so:

<button type="submit" style="border: 0; background: transparent">
    <img src="/images/Btn.PNG" width="90" height="50" alt="submit" />
</button>

More info: http://htmldog.com/reference/htmltags/button/

Unrecognized escape sequence for path string containing backslashes

You can either use a double backslash each time

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

or use the @ symbol

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Here's what worked for me:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <false/>
    <key>NSExceptionDomains</key>
    <dict>
        <key><!-- your_remote_server.com / localhost --></key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
        </dict>
    <!-- add more domain here -->
    </dict>
</dict>

I just wanna add this to help others and save some time:

if you are using: CFStreamCreatePairWithSocketToHost. make sure your host is the same with what you have in your .plist or if you have separate domain for socket just add it there.

CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)/*from .plist*/, (unsigned int)port, &readStream, &writeStream);

Hope this is helpful. Cheers. :)

How to get a user's client IP address in ASP.NET?

UPDATE: Thanks to Bruno Lopes. If several ip addresses could come then need to use this method:

    private string GetUserIP()
    {
        string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {
            return ipList.Split(',')[0];
        }

        return Request.ServerVariables["REMOTE_ADDR"];
    }

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

How to remove all ListBox items?

while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}

In PHP how can you clear a WSDL cache?

You can safely delete the WSDL cache files. If you wish to prevent future caching, use:

ini_set("soap.wsdl_cache_enabled", 0);

or dynamically:

$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );

implements Closeable or implements AutoCloseable

Recently I have read a Java SE 8 Programmer Guide ii Book.

I found something about the difference between AutoCloseable vs Closeable.

The AutoCloseable interface was introduced in Java 7. Before that, another interface existed called Closeable. It was similar to what the language designers wanted, with the following exceptions:

  • Closeable restricts the type of exception thrown to IOException.
  • Closeable requires implementations to be idempotent.

The language designers emphasize backward compatibility. Since changing the existing interface was undesirable, they made a new one called AutoCloseable. This new interface is less strict than Closeable. Since Closeable meets the requirements for AutoCloseable, it started implementing AutoCloseable when the latter was introduced.

Convert Float to Int in Swift

You can get an integer representation of your float by passing the float into the Integer initializer method.

Example:

Int(myFloat)

Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

How does origin/HEAD get set?

Remember there are two independent git repos we are talking about. Your local repo with your code and the remote running somewhere else.

Your are right, when you change a branch, HEAD points to your current branch. All of this is happening on your local git repo. Not the remote repo, which could be owned by another developer, or siting on a sever in your office, or github, or another directory on the filesystem, or etc...

Your computer (local repo) has no business changing the HEAD pointer on the remote git repo. It could be owned by a different developer for example.

One more thing, what your computer calls origin/XXX is your computer's understanding of the state of the remote at the time of the last fetch.

So what would "organically" update origin/HEAD? It would be activity on the remote git repo. Not your local repo.

People have mentioned

git symbolic-ref HEAD refs/head/my_other_branch

Normally, that is used when there is a shared central git repo on a server for use by the development team. It would be a command executed on the remote computer. You would see this as activity on the remote git repo.

What's the default password of mariadb on fedora?

I had the same problem. It's true the password is empty, but even so the error message is shown. The solution is just using "sudo" so

$ sudo mysql

will open the mysql tool

For securing the database, you should use sudo again.

$ sudo mysql_secure_installation

How to get a substring between two strings in PHP?

Use:

<?php

$str = "...server daemon started with pid=6849 (parent=6848).";
$from = "pid=";
$to = "(";

echo getStringBetween($str,$from,$to);

function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
}

?>

Set value of textarea in jQuery

Have you tried val?

$("textarea#ExampleMessage").val(result.exampleMessage);

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

Chrome 11 spits out the following in its debugger:

[Error] GET http://www.mypicx.com/images/logo.jpg undefined (undefined)

It looks like that hosting service is using some funky dynamic system that is preventing these browsers from fetching it correctly. (Instead it tries to fetch the default base image, which is problematically a jpeg.) Could you just upload another copy of the image elsewhere? I would expect it to be the easiest solution by a long mile.

Edit: See what happens in Chrome when you place the image using normal <img> tags ;)

best practice to generate random token for forgot password

This may be helpful whenever you need a very very random token

<?php
   echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>

list.clear() vs list = new ArrayList<Integer>();

Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.

List al= new ArrayList();
        for(int i=0;i<100;i++)
        {
            //List al= new ArrayList();

            for(int j=0;j<10;j++)
            {
                al.add(Integer.parseInt("" +j+i));
                //System.out.println("Obj val " +al.get(j));
            }
            //System.out.println("Hashcode : " + al.hashCode());
            al.clear();

        }

and to my surprise. the memory allocation didnt change much.

With New Arraylist approach.

Before loop total free memory: 64,909 ::

After loop total free memory: 64,775 ::

with Clear approach,

Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::

So this says there is not much difference in using arraylist.clear from memory utilization perspective.

Rails 4: before_filter vs. before_action

It is just syntax difference, in rails app there is CRUD, and seven actions basically by name index, new, create, show, update, edit, destroy.

Rails 4 make it developer friendly to change syntax before filter to before action.

before_action call method before the actions which we declare, like

before_action :set_event, only: [:show, :update, :destroy, :edit]

set_event is a method which will call always before show, update, edit and destroy.

Count rows with not empty value

Here's what I believe is the best solution so far:

=CountIf(ArrayFormula(range<>""),TRUE)

Here's why in 3 easy steps

Step 1: Simple As Pie - Add Extra Column

The answer by eniacAvenger will yield the correct solution without worrying about edge cases as =A1<>"" seems to arrive at the correct truthy/falsy value based on how we intuitively think of blank cells, either virgin blanks or created blanks.

So imagine we have this data and we want the Count of non-blanks in B2:B6:

|   |      A      |   B   |    C    |
|---|-------------|-------|---------|
| 1 | Description | Value | B1<>""  |
| 2 | Text        | H     | TRUE    |
| 3 | Number      | 1     | TRUE    |
| 4 | IF -> ""    |       | FALSE   |
| 5 | IF -> Text  | h     | TRUE    |
| 6 | Blank       |       | FALSE   |

If we relied on Column C, we could get the count of values in B like this:

=COUNTIF(C2:C6,True)

Step 2: Use FormulaArray to dynamically create Extra Column

However, consideRatio's comment is a valid one - if you need an extra column, you can often accomplish the same goal with an ArrayFormula which can create a column in memory without eating up sheet space.

So if we want to create C dynamically, we can use an array formula like this:

=ArrayFormula(B2:B6<>"")

If we simply put it in C2, it would create the vertical array with a single stroke of the pen:

|   |      A      |   B   |    C                     |
|---|-------------|-------|--------------------------|
| 1 | Description | Value | =ArrayFormula(B2:B6<>"") |
| 2 | Text        | H     | TRUE                     |
| 3 | Number      | 1     | TRUE                     |
| 4 | IF -> ""    |       | FALSE                    |
| 5 | IF -> Text  | h     | TRUE                     |
| 6 | Blank       |       | FALSE                    |

Step 3: Count Values in Dynamic Column

But with that solved, we no longer need the column to merely display the values.

ArrayFormula will resolve to the following range: {True,True,False,True,False}.
CountIf just takes in any range and in this case can count the number of True values.

So we can wrap CountIf around the values produced by ArrayFormula like this:

=CountIf(ArrayFormula(B2:B6<>""),TRUE)

Further Reading

The other solutions in this thread are either overly complex, or fail in particular edge cases that I've enumerated in this test sheet:

Google Spreadsheet - CountA Test - Demo

For why CountA works the wonky way it does, see my answer here

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

What is the difference between application server and web server?

An application server is typically designed and deployed to facilitate longer running processes that will also be more resource intensive.

A web server is used for short bursts that are not resource intensive, generally. This is mostly to facilitate serving up web based traffic.

Splitting a continuous variable into equal sized groups

If you want to split into 3 equally distributed groups, the answer is the same as Ben Bolker's answer above - use ggplot2::cut_number(). For sake of completion here are the 3 methods of converting continuous to categorical (binning).

  • cut_number(): Makes n groups with (approximately) equal numbers of observation
  • cut_interval(): Makes n groups with equal range
  • cut_width(): Makes groups of width

My go-to is cut_number() because this uses evenly spaced quantiles for binning observations. Here's an example with skewed data.

library(tidyverse)

skewed_tbl <- tibble(
    counts = c(1:100, 1:50, 1:20, rep(1:10, 3), 
               rep(1:5, 5), rep(1:2, 10), rep(1, 20))
    ) %>%
    mutate(
        counts_cut_number   = cut_number(counts, n = 4),
        counts_cut_interval = cut_interval(counts, n = 4),
        counts_cut_width    = cut_width(counts, width = 25)
        ) 

# Data
skewed_tbl
#> # A tibble: 265 x 4
#>    counts counts_cut_number counts_cut_interval counts_cut_width
#>     <dbl> <fct>             <fct>               <fct>           
#>  1      1 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  2      2 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  3      3 [1,3]             [1,25.8]            [-12.5,12.5]    
#>  4      4 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  5      5 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  6      6 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  7      7 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  8      8 (3,13]            [1,25.8]            [-12.5,12.5]    
#>  9      9 (3,13]            [1,25.8]            [-12.5,12.5]    
#> 10     10 (3,13]            [1,25.8]            [-12.5,12.5]    
#> # ... with 255 more rows

summary(skewed_tbl$counts)
#>    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#>    1.00    3.00   13.00   25.75   42.00  100.00

# Histogram showing skew
skewed_tbl %>%
    ggplot(aes(counts)) +
    geom_histogram(bins = 30)

# cut_number() evenly distributes observations into bins by quantile
skewed_tbl %>%
    ggplot(aes(counts_cut_number)) +
    geom_bar()

# cut_interval() evenly splits the interval across the range
skewed_tbl %>%
    ggplot(aes(counts_cut_interval)) +
    geom_bar()

# cut_width() uses the width = 25 to create bins that are 25 in width
skewed_tbl %>%
    ggplot(aes(counts_cut_width)) +
    geom_bar()

Created on 2018-11-01 by the reprex package (v0.2.1)

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

How to call a parent class function from derived class function?

Call the parent method with the parent scope resolution operator.

Parent::method()

class Primate {
public:
    void whatAmI(){
        cout << "I am of Primate order";
    }
};

class Human : public Primate{
public:
    void whatAmI(){
        cout << "I am of Human species";
    }
    void whatIsMyOrder(){
        Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
    }
};

Define a global variable in a JavaScript function

Just declare it outside the functions, and assign values inside the functions. Something like:

<script type="text/javascript">
    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    var trailimage = null ;  // Global variable
    function makeObj(address) {
        trailimage = [address, 50, 50];  // Assign value

Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;

function makeObj(address) {
    trailimage = [address, 50, 50];  // Global variable, assign value

I hope this example explains more: http://jsfiddle.net/qCrGE/

var globalOne = 3;
testOne();

function testOne()
{
    globalOne += 2;
    alert("globalOne is :" + globalOne );
    globalOne += 1;
}

alert("outside globalOne is: " + globalOne);

testTwo();

function testTwo()
{
    globalTwo = 20;
    alert("globalTwo is " + globalTwo);
    globalTwo += 5;
}

alert("outside globalTwo is:" + globalTwo);

php timeout - set_time_limit(0); - don't work

I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).

I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.

I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.

Hope this helps!

How to convert column with string type to int form in pyspark data frame?

Another way to do it is using the StructField if you have multiple fields that needs to be modified.

Ex:

from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
       StructField('OPEN_FLG',IntegerType(),True),
       StructField('I1_GNDR_CODE',StringType(),True),
       StructField('TRW_INCOME_CD_V4',StringType(),True),
       StructField('ASIAN_CD',IntegerType(),True),
       StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
       ]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)

Output:

Before

root
 |-- CLICK_FLG: string (nullable = true)
 |-- OPEN_FLG: string (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)

After:

root
 |-- CLICK_FLG: integer (nullable = true)
 |-- OPEN_FLG: integer (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)

This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.

It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

Could not create the Java virtual machine

I had this issue today, and for me the problem was that I had allocated too much memory:

-Xmx1024M -XX:MaxPermSize=1024m

Once I reduced the PermGen space, everything worked fine:

-Xmx1024M -XX:MaxPermSize=512m

I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.

Have bash script answer interactive prompts

This is not "auto-completion", this is automation. One common tool for these things is called Expect.

You might also get away with just piping input from yes.

PL/SQL, how to escape single quote in a string?

EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'; worked for me. closing the varchar/string with two pairs of single quotes did the trick. Other option could be to use using keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'; Remember using keyword will not work, if you are using EXECUTE IMMEDIATE to execute DDL's with parameters, however, using quotes will work for DDL's.

Save range to variable

In your own answer, you effectively do this:

Dim SrcRange As Range ' you should always declare things explicitly
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

You're not really "extracting" the range to a variable, you're setting a reference to the range.

In many situations, this can be more efficient as well as more flexible:

Dim Src As Variant
Src= Sheets("Src").Range("A2:A9").Value 'Read range to array
'Here you can add code to manipulate your Src array
'...
Sheets("Dest").Range("A2:A9").Value = Src 'Write array back to another range

Duplicate AssemblyVersion Attribute

My error was that I was also referencing another file in my project, which was also containing a value for the attribute "AssemblyVersion". I removed that attribute from one of the file and it is now working properly.

The key is to make sure that this value is not declared more than once in any file in your project.

How to create named and latest tag in Docker?

Here is my bash script

docker build -t ${IMAGE}:${VERSION} .
docker tag ${IMAGE}:${VERSION} ${IMAGE}:latest

You can then remove untagged images if you rebuilt the same version with

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")

link

or

docker rmi $(docker images | grep "^<none>" | tr -s " " | cut -d' ' -f3 | tr '\n' ' ')

or

Clean up commands:

Docker 1.13 introduces clean-up commands. To remove all unused containers, images, networks and volumes:

docker system prune

or individually:

docker container prune
docker image prune
docker network prune
docker volume prune

windows batch file rename

as Itsproinc said, the REN command works!

but if your file path/name has spaces, use quotes " "

example:

ren C:\Users\&username%\Desktop\my file.txt not my file.txt

add " "

ren "C:\Users\&username%\Desktop\my file.txt" "not my file.txt"

hope it helps

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

PHP find difference between two datetimes

You can simply use datetime diff and format for calculating difference.

<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>

For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.

Here is the working example

P.S. These features( diff() and format()) work with >=PHP 5.3.0 only

jQuery UI Dialog - missing close icon

As a reference, this is how I extended the open method as per @john-macintyre's suggestion:

_x000D_
_x000D_
$.widget( "ui.dialog", $.ui.dialog, {_x000D_
 open: function() {_x000D_
  $(this.uiDialogTitlebarClose)_x000D_
   .html("<span class='ui-button-icon-primary ui-icon ui-icon-closethick'></span><span class='ui-button-text'>close</span>");_x000D_
  // Invoke the parent widget's open()._x000D_
  return this._super();_x000D_
 }_x000D_
});
_x000D_
_x000D_
_x000D_

How to remove element from ArrayList by checking its value?

One-liner (java8):

list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one

(does all the iterating implicitly)

What is the Sign Off feature in Git for?

Sign-off is a line at the end of the commit message which certifies who is the author of the commit. Its main purpose is to improve tracking of who did what, especially with patches.

Example commit:

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

It should contain the user real name if used for an open-source project.

If branch maintainer need to slightly modify patches in order to merge them, he could ask the submitter to rediff, but it would be counter-productive. He can adjust the code and put his sign-off at the end so the original author still gets credit for the patch.

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

[Project Maintainer: Renamed test methods according to naming convention.]
Signed-off-by: Project Maintainer <[email protected]>

Source: http://gerrit.googlecode.com/svn/documentation/2.0/user-signedoffby.html

Recyclerview inside ScrollView not scrolling smoothly

I only needed to use this:

mMyRecyclerView.setNestedScrollingEnabled(false);

in my onCreateView() method.

Thanks a lot!

How to make a .NET Windows Service start right after the installation?

You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.

How to export/import PuTTy sessions list?

  1. Launch Run, then type in the Open drop down window: regedit

  2. Navigate to, just like in Window's Explorer:
    HKEY_CURRENT_USER\Software\SimonTatham

  3. Right click on 'SimonTatham' key (directory icon), select Export
    Give the file a name (say) putty.reg and save it to your location for
    later use.
  4. Close Registry Editor.

Done.

Datagridview: How to set a cell in editing mode?

I know this is an old question, but none of the answers worked for me, because I wanted to reliably (always be able to) set the cell into edit mode when possibly executing other events like Toolbar Button clicks, menu selections, etc. that may affect the default focus after those events return. I ended up needing a timer and invoke. The following code is in a new component derived from DataGridView. This code allows me to simply make a call to myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName); anytime I want to arbitrarily set a databound cell to edit mode (assuming the cell is Not in ReadOnly mode).

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

How do I find which transaction is causing a "Waiting for table metadata lock" state?

I had a similar issue with Datagrip and none of these solutions worked.

Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.

Chart.js v2 - hiding grid lines

If you want to hide gridlines but want to show yAxes, you can set:

yAxes: [{...
         gridLines: {
                        drawBorder: true,
                        display: false
                    }
       }]

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

If the text is retrieved from a mysql database you may try adding this after BD connection.

mysqli_set_charset($con, "utf8");

https://www.php.net/manual/en/mysqli.set-charset.php

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

How to set password for Redis?

step 1. stop redis server using below command /etc/init.d/redis-server stop step 2.enter command : sudo nano /etc/redis/redis.conf

step 3.find # requirepass foobared word and remove # and change foobared to YOUR PASSWORD

ex. requirepass root

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

Submit two forms with one button

A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));

document.forms.payPal.submit();

Why doesn't calling a Python string method do anything unless you assign its output?

Example for String Methods

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
    if i.endswith(".hpp"):
        x = i.replace("hpp", "h")
        newfilenames.append(x)
    else:
        newfilenames.append(i)


print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

hasOwnProperty in JavaScript

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

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

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

Action bar navigation modes are deprecated in Android L

I found these tutorials helpful while putting together an action bar (now the 'tool bar' - argh) that supports sliding tabs with Material Design:

https://www.youtube.com/watch?v=Fl0xMuo10yA

http://www.exoguru.com/android/material-design/navigation/android-sliding-tabs-with-material-design.html

You sort of have to synthesize these resources to match your particular situation. For example, you may not want to manually create the tabs in the same style that the exoguru.com tutorial did.

RESTful Authentication via Spring

Regarding tokens carrying information, JSON Web Tokens (http://jwt.io) is a brilliant technology. The main concept is to embed information elements (claims) into the token, and then signing the whole token so that the validating end can verify that the claims are indeed trustworthy.

I use this Java implementation: https://bitbucket.org/b_c/jose4j/wiki/Home

There is also a Spring module (spring-security-jwt), but I haven't looked into what it supports.

Python: most idiomatic way to convert None to empty string?

Probably the shortest would be str(s or '')

Because None is False, and "x or y" returns y if x is false. See Boolean Operators for a detailed explanation. It's short, but not very explicit.

How to check for Is not Null And Is not Empty string in SQL server?

Coalesce will fold nulls into a default:

COALESCE (fieldName, '') <> ''

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Check if MySQL table exists or not

$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
    $tablesExists[] = $row[0];
}

How do I remove a CLOSE_WAIT socket connection

CLOSE_WAIT means your program is still running, and hasn't closed the socket (and the kernel is waiting for it to do so). Add -p to netstat to get the pid, and then kill it more forcefully (with SIGKILL if needed). That should get rid of your CLOSE_WAIT sockets. You can also use ps to find the pid.

SO_REUSEADDR is for servers and TIME_WAIT sockets, so doesn't apply here.

How to validate an email address in JavaScript

Very simple in JavaScript. follow this code.

function validate(){
    var email = document.getElementById('Email');
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email.value))
    {
        alert('Please Enter the valid email address');
        email.focus;
        return false;
    }
    else
{
        return true;
    }

HTML code for this:

form name="form"
     enctype="multipart/form-data"
     name="form"
     action="register.php"
     method="POST" onsubmit="return validate();" >
    <input type="text" placeholder="Enter ur Email Id" id="Email" name="Email" />
    <input type="submit" id="submit" value="save" name="Like" class="button" />
</form>

How to generate unique ID with node.js

I am using the following and it is working fine plus without any third-party dependencies.

const {
  randomBytes
} = require('crypto');

const uid = Math.random().toString(36).slice(2) + randomBytes(8).toString('hex') + new Date().getTime();

How can I remove a commit on GitHub?

if you want to remove do interactive rebase,

git rebase -i HEAD~4

4 represents total number of commits to display count your commit andchange it accordingly

and delete commit you want from list...

save changes by Ctrl+X(ubuntu) or :wq(centos)

2nd method, do revert,

git revert 29f4a2 #your commit ID

this will revert specific commit

make arrayList.toArray() return more specific types

It doesn't really need to return Object[], for example:-

    List<Custom> list = new ArrayList<Custom>();
    list.add(new Custom(1));
    list.add(new Custom(2));

    Custom[] customs = new Custom[list.size()];
    list.toArray(customs);

    for (Custom custom : customs) {
        System.out.println(custom);
    }

Here's my Custom class:-

public class Custom {
    private int i;

    public Custom(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return String.valueOf(i);
    }
}

JavaScript error: "is not a function"

For more generic advice on debugging this kind of problem MDN have a good article TypeError: "x" is not a function:

It was attempted to call a value like a function, but the value is not actually a function. Some code expects you to provide a function, but that didn't happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript objects have no map function, but JavaScript Array object do.

Basically the object (all functions in js are also objects) does not exist where you think it does. This could be for numerous reasons including(not an extensive list):

  • Missing script library
  • Typo
  • The function is within a scope that you currently do not have access to, e.g.:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//the global scope can't access y because it is closed over in x and not exposed_x000D_
//y is not a function err triggered_x000D_
x.y();
_x000D_
_x000D_
_x000D_

  • Your object/function does not have the function your calling:

_x000D_
_x000D_
var x = function(){_x000D_
   var y = function() {_x000D_
      alert('fired y');_x000D_
   }_x000D_
};_x000D_
    _x000D_
//z is not a function error (as above) triggered_x000D_
x.z();
_x000D_
_x000D_
_x000D_

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

Detecting real time window size changes in Angular 4

To get it on init

public innerWidth: any;
ngOnInit() {
    this.innerWidth = window.innerWidth;
}

If you wanna keep it updated on resize:

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.innerWidth = window.innerWidth;
}

Parse HTML in Android

Have you tried using Html.fromHtml(source)?

I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.

How to center a (background) image within a div?

This works for me:

#doit{
    background-image: url('images/pic.png');
    background-repeat: no-repeat;
    background-position: center;  
}  

How do I convert from int to String?

Mostly ditto on SimonJ. I really dislike the ""+i idiom. If you say String.valueOf(i), Java converts the integer to a string and returns the result. If you say ""+i, Java creates a StringBuilder object, appends an empty string to it, converts the integer to a string, appends this to the StringBuilder, then converts the StringBuilder to a String. That's a lot of extra steps. I suppose if you do it once in a big program, it's no big deal. But if you're doing this all the time, you're making the computer do a bunch of extra work and creating all these extra objects that then have to be cleaned up. I don't want to get fanatic about micro-optimization, but I don't want to be pointlessly wasteful either.

Traits vs. interfaces

An interface is a contract that says “this object is able to do this thing”, whereas a trait is giving the object the ability to do the thing.

A trait is essentially a way to “copy and paste” code between classes.

Try reading this article, What are PHP traits?

How can I uninstall Ruby on ubuntu?

If you used rbenv to install it, you can use

rbenv versions 

to see which versions you have installed.

Then, use the uninstall command:

rbenv uninstall [-f|--force] <version>

for example:

rbenv uninstall 2.4.0  # Uninstall Ruby 2.4.0

If you installed Rails, it will be removed, too.

Repeat each row of data.frame the number of times specified in a column

In case you have to do this operation on very large data.frames I would recommend converting it into a data.table and use the following, which should run much faster:

library(data.table)
dt <- data.table(df)
dt.expanded <- dt[ ,list(freq=rep(1,freq)),by=c("var1","var2")]
dt.expanded[ ,freq := NULL]
dt.expanded

See how much faster this solution is:

df <- data.frame(var1=1:2e3, var2=1:2e3, freq=1:2e3)
system.time(df.exp <- df[rep(row.names(df), df$freq), 1:2])
##    user  system elapsed 
##    4.57    0.00    4.56
dt <- data.table(df)
system.time(dt.expanded <- dt[ ,list(freq=rep(1,freq)),by=c("var1","var2")])
##    user  system elapsed 
##    0.05    0.01    0.06

get and set in TypeScript

TypeScript uses getter/setter syntax that is like ActionScript3.

class foo {
    private _bar: boolean = false;
    get bar(): boolean {
        return this._bar;
    }
    set bar(value: boolean) {
        this._bar = value;
    }
}

That will produce this JavaScript, using the ECMAScript 5 Object.defineProperty() feature.

var foo = (function () {
    function foo() {
        this._bar = false;
    }
    Object.defineProperty(foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (value) {
            this._bar = value;
        },
        enumerable: true,
        configurable: true
    });
    return foo;
})();

So to use it,

var myFoo = new foo();
if(myFoo.bar) {         // calls the getter
    myFoo.bar = false;  // calls the setter and passes false
}

However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target flag like this;

tsc --target ES5

If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:

As @DanFromGermany suggests below, if your are simply reading and writing a local property like foo.bar = true, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.

How to get milliseconds from LocalDateTime in Java 8

You can try this:

long diff = LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();

QByteArray to QString

You can use:

QString::fromStdString(byteArray.toStdString())

cURL not working (Error #77) for SSL connections on CentOS for non-root users

If you recently reached here as I did when searching for the same error in vain you may find it to be an update to NSS causing failure on CentOS. Test by running yum update and see if you get errors, curl also creates this error. Solution is simple enough just install NSS manually.

Read on...

If you're like me it threw up an error similar to this:

curl: (77) Problem with the SSL CA cert (path? access rights?)

This took some time to solve but found that it wasn't the CA cert because by recreating them and checking all the configuration I had ruled it out. It could have been libcurl so I went in search of updates.

As mentioned I recreated CA certs. You can do this also but it may be a waste of time. http://wiki.centos.org/HowTos/Https

The next step (probably should of been my first) was to check that everything was up-to-date by simply running yum.

$ yum update
$ yum upgrade

This gave me an affirmative answer that there was a bigger problem at play: Downloading Packages: error: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: BAD Problem opening package nss-softokn-freebl-3.14.3–19.el6_6.x86_64.rpm I started reading about Certificate Verification with NSS and how this new update may be related to my problems. So yum is broken. This is because nss-softokn-* needs nss-softokn-freebl-* need each other to function. The problem is they don't check each others version for compatibility and in some cases it ends up breaking yum. Lets go fix things:

$ wget http://mirrors.linode.com/centos/6.6/updates/x86_64/Packages/nsssoftokn-freebl-3.14.3-19.el6_6.x86_64.rpm
$ rpm -Uvh nss-softokn-freebl-3.14.3–19.el6_6.x86_64.rpm
$ yum update

You should of course download from your nearest mirror and check for the correct version / OS etc. We basically download and install the update from the rpm to fix yum. As @grumpysysadmin pointed out you can shorten the commands down. @cwgtex contributed that you should install the upgrade using the RPM command making the process even simplier.

To fix things with wordpress you need to restart your http server.

$ service httpd restart

Try again and success!

How to fix C++ error: expected unqualified-id

Get rid of the semicolon after WordGame.

You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.

Multiple selector chaining in jQuery?

I think you might see slightly better performance by doing it this way:

$("#Create, #Edit").find(".myClass").plugin(){
    // Options
});

String concatenation in MySQL

Try:

select concat(first_name,last_name) as "Name" from test.student

or, better:

select concat(first_name," ",last_name) as "Name" from test.student

jQuery if Element has an ID?

Like this:

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

Following OP's comment, test it like this:

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

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

PHP Fatal error: Cannot redeclare class

I had the same problem "PHP Fatal error: Cannot redeclare class XYZ.php".

I have two directories like controller and model and I uploaded by mistakenly XYZ.php in both directories.(so file with the same name cause the issue).

First solution:

Find in your whole project and make sure you have only one class XYZ.php.

Second solution:

Add a namespace in your class so you can use the same class name.

Remove all whitespaces from NSString

That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use

xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];

It will replace empty space with no space and empty field is taken care of by below method:

searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

Run Batch File On Start-up

If your Windows language is different from English, you can launch the Task Scheduler by

  1. Press Windows+X
  2. Select your language translation of "Computer Management"
  3. Follow the instruction in the answer provided by prankin

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

Android: Pass data(extras) to a fragment

I prefer Serializable = no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable does not matter.

I would also always provide a helper method for a Fragment or Activity, this way you always know, what data has to be passed. Here an example for your ListMusicFragment:

private static final String EXTRA_MUSIC_LIST = "music_list";

public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_MUSIC_LIST, music);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public View onCreateView(...) { 
    ...
    Bundle bundle = intent.getArguments();
    List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
    ...
}

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

A cycle was detected in the build path of project xxx - Build Path Problem

This could happen when you have several projects that include each other in JAR form. What I did was remove all libraries and project dependencies on buildpath, for all projects. Then, one at a time, I added the project dependencies on the Project Tab, but only the ones needed. This is because you can add a project which in turn has itself referenced or another project which is referencing some other project with this self-referencing issue.

This resolved my issue.

How to determine the screen width in terms of dp or dip at runtime in Android?

Try this

Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

OR

Thanks @Tomáš Hubálek

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

How to use sed to remove the last n lines of a file

To delete last 4 lines:

$ nl -b a file | sort -k1,1nr | sed '1, 4 d' | sort -k1,1n | sed 's/^ *[0-9]*\t//'   

getaddrinfo: nodename nor servname provided, or not known

I got the same error when I check the localhost is set in hosts file it is somehow not set. Setting localhost to 127.0.0.1 solved it.

sudo vi /etc/hosts
>>

127.0.0.1       localhost

How can I get just the first row in a result set AFTER ordering?

An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

How to upload files in asp.net core?

 <form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">

     <div class="form-group">
        <input type="file" class="form-control" name="image" />
     </div>

     <div class="form-group">
        <button type="submit" class="btn btn-primary col-xs-12">Add</button>
     </div>
  </form>

My Action Is

        [HttpPost]
        public IActionResult AddNews(IFormFile image)
        {
            Tbl_News tbl_News = new Tbl_News();
            if (image!=null)
            {

                //Set Key Name
                string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);

                //Get url To Save
                string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);

                using(var stream=new FileStream(SavePath, FileMode.Create))
                {
                    image.CopyTo(stream);
                }
            }
            return View();
        }

How can I calculate the number of lines changed between two commits in Git?

Another way to get all change log in a specified period of time

git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10"

Output:

2637cc736 Revert changed code
 1 file changed, 5 insertions(+), 5 deletions(-)
ba8d29402 Fix review
 2 files changed, 4 insertions(+), 11 deletions(-)

With a long output content, you can export to file for more readable

git log --author="Tri Nguyen" --oneline --shortstat --before="2017-03-20" --after="2017-03-10" > /mnt/MyChangeLog.txt

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    ... do something
}

Explanation:

document.documentMode

An IE only property, first available in IE8.

/Edge/

A regular expression to search for the string 'Edge' - which we then test against the 'navigator.userAgent' property

Update Mar 2020

@Jam comments that the latest version of Edge now reports Edg as the user agent. So the check would be:

if (document.documentMode || /Edge/.test(navigator.userAgent) || /Edg/.test(navigator.userAgent)) {
    ... do something
}

Arrow operator (->) usage in C

a->b is just short for (*a).b in every way (same for functions: a->b() is short for (*a).b()).

What is the best way to seed a database in Rails?

factory_bot sounds like it will do what you are trying to achieve. You can define all the common attributes in the default definition and then override them at creation time. You can also pass an id to the factory:

Factory.define :theme do |t|
  t.background_color '0x000000'
  t.title_text_color '0x000000',
  t.component_theme_color '0x000000'
  t.carrier_select_color '0x000000'
  t.label_text_color '0x000000',
  t.join_upper_gradient '0x000000'
  t.join_lower_gradient '0x000000'
  t.join_text_color '0x000000',
  t.cancel_link_color '0x000000'
  t.border_color '0x000000'
  t.carrier_text_color '0x000000'
  t.public true
end

Factory(:theme, :id => 1, :name => "Lite", :background_color => '0xC7FFD5')
Factory(:theme, :id => 2, :name => "Metallic", :background_color => '0xC7FFD5')
Factory(:theme, :id => 3, :name => "Blues", :background_color => '0x0060EC')

When used with faker it can populate a database really quickly with associations without having to mess about with Fixtures (yuck).

I have code like this in a rake task.

100.times do
    Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])
end

Jupyter Notebook not saving: '_xsrf' argument missing from post

1 workaround to solve this problem is:

  1. Download the notebook which you are not able to save by going to: File --> Download as --> Notebook (ipynb).

  2. Open the downloaded notebook by clicking on the downloaded file on the jupyter browser UI

Now, you should be able to save (or rename) this notebook from jupyter UI

Simple DatePicker-like Calendar

How about the Dijit Calendar from the Dojo framework? It's pretty cool and very easy to implement. I always use this calendar.
https://www.dojotoolkit.org/reference-guide/dijit/Calendar.html

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

How to find NSDocumentDirectory in Swift?

Usually I prefer to use this extension:

Swift 3.x and Swift 4.0:

extension FileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
}

Swift 2.x:

extension NSFileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
}

One liner for If string is not null or empty else

There is a null coalescing operator (??), but it would not handle empty strings.

If you were only interested in dealing with null strings, you would use it like

string output = somePossiblyNullString ?? "0";

For your need specifically, there is the conditional operator bool expr ? true_value : false_value that you can use to simplify if/else statement blocks that set or return a value.

string output = string.IsNullOrEmpty(someString) ? "0" : someString;

TSQL How do you output PRINT in a user defined function?

I have tended in the past to work on my functions in two stages. The first stage would be to treat them as fairly normal SQL queries and make sure that I am getting the right results out of it. After I am confident that it is performing as desired, then I would convert it into a UDF.

Find all packages installed with easy_install/pip?

If Debian behaves like recent Ubuntu versions regarding pip install default target, it's dead easy: it installs to /usr/local/lib/ instead of /usr/lib (apt default target). Check https://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747

I am an ArchLinux user and as I experimented with pip I met this same problem. Here's how I solved it in Arch.

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'

Key here is /usr/lib/python2.7/site-packages, which is the directory pip installs to, YMMV. pacman -Qo is how Arch's pac kage man ager checks for ownership of the file. No package is part of the return it gives when no package owns the file: error: No package owns $FILENAME. Tricky workaround: I'm querying about __init__.py because pacman -Qo is a little bit ignorant when it comes to directories :(

In order to do it for other distros, you have to find out where pip installs stuff (just sudo pip install something), how to query ownership of a file (Debian/Ubuntu method is dpkg -S) and what is the "no package owns that path" return (Debian/Ubuntu is no path found matching pattern). Debian/Ubuntu users, beware: dpkg -S will fail if you give it a symbolic link. Just resolve it first by using realpath. Like this:

find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'

Fedora users can try (thanks @eddygeek):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'