Programs & Examples On #Externalizing

How to uncheck checkbox using jQuery Uniform library

Looking at their docs, they have a $.uniform.update feature to refresh a "uniformed" element.

Example: http://jsfiddle.net/r87NH/4/

$("input:checkbox").uniform();

$("body").on("click", "#check1", function () {
    var two = $("#check2").attr("checked", this.checked);
    $.uniform.update(two);
});

What is the easiest way to remove the first character from a string?

I kind of favor using something like:

asdf = "[12,23,987,43"
asdf[0] = '' 

p asdf
# >> "12,23,987,43"

I'm always looking for the fastest and most readable way of doing things:

require 'benchmark'

N = 1_000_000

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
  b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
  b.report('sub') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }

  b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
  b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
  b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
  b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }

end

Running on my Mac Pro:

1.9.3
              user     system      total        real
[0]       0.840000   0.000000   0.840000 (  0.847496)
sub       1.960000   0.010000   1.970000 (  1.962767)
gsub      4.350000   0.020000   4.370000 (  4.372801)
[1..-1]   0.710000   0.000000   0.710000 (  0.713366)
slice     1.020000   0.000000   1.020000 (  1.020336)
length    1.160000   0.000000   1.160000 (  1.157882)

Updating to incorporate one more suggested answer:

require 'benchmark'

N = 1_000_000

class String
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end

  def first(how_many = 1)
    self[0...how_many]
  end

  def shift(how_many = 1)
    shifted = first(how_many)
    self.replace self[how_many..-1]
    shifted
  end
  alias_method :shift!, :shift
end

class Array
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end
end

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
  b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
  b.report('sub') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }

  b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
  b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
  b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
  b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
  b.report('eat!') { N.times { "[12,23,987,43".eat! } }
  b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end

Which results in:

2.1.2
              user     system      total        real
[0]       0.300000   0.000000   0.300000 (  0.295054)
sub       0.630000   0.000000   0.630000 (  0.631870)
gsub      2.090000   0.000000   2.090000 (  2.094368)
[1..-1]   0.230000   0.010000   0.240000 (  0.232846)
slice     0.320000   0.000000   0.320000 (  0.320714)
length    0.340000   0.000000   0.340000 (  0.341918)
eat!      0.460000   0.000000   0.460000 (  0.452724)
reverse   0.400000   0.000000   0.400000 (  0.399465)

And another using /^./ to find the first character:

require 'benchmark'

N = 1_000_000

class String
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end

  def first(how_many = 1)
    self[0...how_many]
  end

  def shift(how_many = 1)
    shifted = first(how_many)
    self.replace self[how_many..-1]
    shifted
  end
  alias_method :shift!, :shift
end

class Array
  def eat!(how_many = 1)
    self.replace self[how_many..-1]
  end
end

puts RUBY_VERSION

STR = "[12,23,987,43"

Benchmark.bm(7) do |b|
  b.report('[0]') { N.times { "[12,23,987,43"[0] = '' } }
  b.report('[/^./]') { N.times { "[12,23,987,43"[/^./] = '' } }
  b.report('[/^\[/]') { N.times { "[12,23,987,43"[/^\[/] = '' } }
  b.report('sub+') { N.times { "[12,23,987,43".sub(/^\[+/, "") } }
  b.report('sub') { N.times { "[12,23,987,43".sub(/^\[/, "") } }
  b.report('gsub') { N.times { "[12,23,987,43".gsub(/^\[/, "") } }
  b.report('[1..-1]') { N.times { "[12,23,987,43"[1..-1] } }
  b.report('slice') { N.times { "[12,23,987,43".slice!(0) } }
  b.report('length') { N.times { "[12,23,987,43"[1..STR.length] } }
  b.report('eat!') { N.times { "[12,23,987,43".eat! } }
  b.report('reverse') { N.times { "[12,23,987,43".reverse.chop.reverse } }
end

Which results in:

# >> 2.1.5
# >>               user     system      total        real
# >> [0]       0.270000   0.000000   0.270000 (  0.270165)
# >> [/^./]    0.430000   0.000000   0.430000 (  0.432417)
# >> [/^\[/]   0.460000   0.000000   0.460000 (  0.458221)
# >> sub+      0.590000   0.000000   0.590000 (  0.590284)
# >> sub       0.590000   0.000000   0.590000 (  0.596366)
# >> gsub      1.880000   0.010000   1.890000 (  1.885892)
# >> [1..-1]   0.230000   0.000000   0.230000 (  0.223045)
# >> slice     0.300000   0.000000   0.300000 (  0.299175)
# >> length    0.320000   0.000000   0.320000 (  0.325841)
# >> eat!      0.410000   0.000000   0.410000 (  0.409306)
# >> reverse   0.390000   0.000000   0.390000 (  0.393044)

Here's another update on faster hardware and a newer version of Ruby:

2.3.1
              user     system      total        real
[0]       0.200000   0.000000   0.200000 (  0.204307)
[/^./]    0.390000   0.000000   0.390000 (  0.387527)
[/^\[/]   0.360000   0.000000   0.360000 (  0.360400)
sub+      0.490000   0.000000   0.490000 (  0.492083)
sub       0.480000   0.000000   0.480000 (  0.487862)
gsub      1.990000   0.000000   1.990000 (  1.988716)
[1..-1]   0.180000   0.000000   0.180000 (  0.181673)
slice     0.260000   0.000000   0.260000 (  0.266371)
length    0.270000   0.000000   0.270000 (  0.267651)
eat!      0.400000   0.010000   0.410000 (  0.398093)
reverse   0.340000   0.000000   0.340000 (  0.344077)

Why is gsub so slow?

After doing a search/replace, gsub has to check for possible additional matches before it can tell if it's finished. sub only does one and finishes. Consider gsub like it's a minimum of two sub calls.

Also, it's important to remember that gsub, and sub can also be handicapped by poorly written regex which match much more slowly than a sub-string search. If possible anchor the regex to get the most speed from it. There are answers here on Stack Overflow demonstrating that so search around if you want more information.

How to get MAC address of client using PHP?

Use this function to get the client MAC address:

function GetClientMac(){
    $macAddr=false;
    $arp=`arp -n`;
    $lines=explode("\n", $arp);

    foreach($lines as $line){
        $cols=preg_split('/\s+/', trim($line));

        if ($cols[0]==$_SERVER['REMOTE_ADDR']){
            $macAddr=$cols[2];
        }
    }

    return $macAddr;
}

How to "scan" a website (or page) for info, and bring it into my program?

You could also try jARVEST.

It is based on a JRuby DSL over a pure-Java engine to spider-scrape-transform web sites.

Example:

Find all links inside a web page (wget and xpath are constructs of the jARVEST's language):

wget | xpath('//a/@href')

Inside a Java program:

Jarvest jarvest = new Jarvest();
  String[] results = jarvest.exec(
    "wget | xpath('//a/@href')", //robot! 
    "http://www.google.com" //inputs
  );
  for (String s : results){
    System.out.println(s);
  }

What is an index in SQL?

First we need to understand how normal (without indexing) query runs. It basically traverse each rows one by one and when it finds the data it returns. Refer the following image. (This image has been taken from this video.)

Without indexing So suppose query is to find 50 , it will have to read 49 records as a linear search.

Refer the following image. (This image has been taken from this video)

enter image description here

When we apply indexing, the query will quickly find out the data without reading each one of them just by eliminating half of the data in each traversal like a binary search. The mysql indexes are stored as B-tree where all the data are in leaf node.

How to find path of active app.config file?

The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

Problem solved

I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.

What is a stored procedure?

Stored Procedure will help you to make code in server.You can pass parameters and find output.

create procedure_name (para1 int,para2 decimal)
as
select * from TableName

How can I get a first element from a sorted list?

If your collection is not a List (and thus you can't use get(int index)), then you can use the iterator:

Iterator iter = collection.iterator();
if (iter.hasNext()) {
    Object first = iter.next();
}

How to run multiple SQL commands in a single SQL connection?

Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.

// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();

// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();

How to scale a UIImageView proportionally?

imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;

How to print GETDATE() in SQL Server with milliseconds in time?

these 2 are the same:

Print CAST(GETDATE() as Datetime2 (3) )
PRINT (CONVERT( VARCHAR(24), GETDATE(), 121))

enter image description here

Using Java 8 to convert a list of objects into a string obtained from the toString() method

List<String> list = Arrays.asList("One", "Two", "Three");
    list.stream()
            .reduce("", org.apache.commons.lang3.StringUtils::join);

Or

List<String> list = Arrays.asList("One", "Two", "Three");
        list.stream()
                .reduce("", (s1,s2)->s1+s2);

This approach allows you also build a string result from a list of objects Example

List<Wrapper> list = Arrays.asList(w1, w2, w2);
        list.stream()
                .map(w->w.getStringValue)
                .reduce("", org.apache.commons.lang3.StringUtils::join);

Here the reduce function allows you to have some initial value to which you want to append new string Example:

 List<String> errors = Arrays.asList("er1", "er2", "er3");
            list.stream()
                    .reduce("Found next errors:", (s1,s2)->s1+s2);

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

Mercurial — revert back to old version and continue from there

hg update [-r REV]

If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.

Detect all changes to a <input type="text"> (immediately) using JQuery

Can't you just use <span contenteditable="true" spellcheck="false"> element in place of <input type="text">?

<span> (with contenteditable="true" spellcheck="false" as attributes) distincts by <input> mainly because:

  • It's not styled like an <input>.
  • It doesn't have a value property, but the text is rendered as innerText and makes part of its inner body.
  • It's multiline whereas <input> isn't although you set the attribute multiline="true".

To accomplish the appearance you can, of course, style it in CSS, whereas writing the value as innerText you can get for it an event:

Here's a fiddle.

Unfortunately there's something that doesn't actually work in IE and Edge, which I'm unable to find.

How to use JavaScript to change div backgroundColor

Adding/changing style of the elements in code is a bad practice. Today you want to change the background color and tomorrow you would like to change background image and after tomorrow you decided that it would be also nice to change the border.

Editing the code every-time only because the design requirements changes is a pain. Also, if your project will grow, changing js files will be even more pain. More code, more pain.

Try to eliminate use of hard coded styles, this will save you time and, if you do it right, you could ask to do the "change-color" task to someone else.

So, instead of changing direct properties of style, you can add/remove CSS classes on nodes. In your specific case, you only need to do this for parent node - "div" and then, style the subnodes through CSS. So no need to apply specific style property to DIV and to H2.

One more recommendation point. Try not to connect nodes hardcoded, but use some semantic to do that. For example: "To add events to all nodes which have class 'content'.

In conclusion, here is the code which I would use for such tasks:

//for adding a css class
function onOver(node){
   node.className = node.className + ' Hover';
}

//for removing a css class
function onOut(node){
    node.className = node.className.replace('Hover','');
}

function connect(node,event,fnc){
    if(node.addEventListener){
        node.addEventListener(event.substring(2,event.length),function(){
            fnc(node);
        },false);
    }else if(node.attachEvent){
        node.attachEvent(event,function(){
            fnc(node);
        });
    }
}

// run this one when window is loaded
var divs = document.getElementsByTagName("div");
for(var i=0,div;div =divs[i];i++){
    if(div.className.match('content')){
        connect(div,'onmouseover',onOver);
        connect(div,'onmouseout',onOut);
    }
}

And you CSS whould be like this:

.content {
    background-color: blue;
}

.content.Hover{
    background-color: red;
}

.content.Hover h2{
    background-color : yellow;
}

MongoDB: update every document on one field

You can use updateMany() methods of mongodb to update multiple document

Simple query is like this

db.collection.updateMany(filter, update, options)

For more doc of uppdateMany read here

As per your requirement the update code will be like this:

User.updateMany({"created": false}, {"$set":{"created": true}});

here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

How to display a confirmation dialog when clicking an <a> link?

jAplus

You can do it, without writing JavaScript code

<head>
   <script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
   <script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
   <a href="delete.php?id=22" class="confirm" title="Are you sure?">Link</a>
...
</body>

Demo page

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}

Shell command to sum integers, one per line?

Simple php

  cat numbers.txt | php -r "echo array_sum(explode(PHP_EOL, stream_get_contents(STDIN)));"

Android marshmallow request permission?

For multiple permission at a time you can use this. This work for me.. I got another solution. if you give your targetSdkVersion bellow 22 it works for me. and it behavior as like getting permission from manifest.xml. Tested and works for me.

final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

    private void insertDummyContactWrapper() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
            permissionsNeeded.add("GPS");
        if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
            permissionsNeeded.add("Read Contacts");
        if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
            permissionsNeeded.add("Write Contacts");

        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {
                // Need Rationale
                String message = "You need to grant access to " + permissionsNeeded.get(0);
                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + ", " + permissionsNeeded.get(i);
                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }

        insertDummyContact();
    }

    private boolean addPermission(List<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }






@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
                {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.WRITE_CONTACTS, PackageManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for ACCESS_FINE_LOCATION
                if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                    // All Permissions Granted
                    insertDummyContact();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

For more details. Check bellow link

https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en

How to set a cron job to run every 3 hours

Change Minute parameter to 0.

You can set the cron for every three hours as:

0 */3 * * * your command here ..

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Visual Studio 2010 shortcut to find classes and methods?

try: ctrl + P

type: @

followed by the name of the class,method or variable name you search for.

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

How can I generate a unique ID in Python?

here you can find an implementation :

def __uniqueid__():
    """
      generate unique id with length 17 to 21.
      ensure uniqueness even with daylight savings events (clocks adjusted one-hour backward).

      if you generate 1 million ids per second during 100 years, you will generate 
      2*25 (approx sec per year) * 10**6 (1 million id per sec) * 100 (years) = 5 * 10**9 unique ids.

      with 17 digits (radix 16) id, you can represent 16**17 = 295147905179352825856 ids (around 2.9 * 10**20).
      In fact, as we need far less than that, we agree that the format used to represent id (seed + timestamp reversed)
      do not cover all numbers that could be represented with 35 digits (radix 16).

      if you generate 1 million id per second with this algorithm, it will increase the seed by less than 2**12 per hour
      so if a DST occurs and backward one hour, we need to ensure to generate unique id for twice times for the same period.
      the seed must be at least 1 to 2**13 range. if we want to ensure uniqueness for two hours (100% contingency), we need 
      a seed for 1 to 2**14 range. that's what we have with this algorithm. You have to increment seed_range_bits if you
      move your machine by airplane to another time zone or if you have a glucky wallet and use a computer that can generate
      more than 1 million ids per second.

      one word about predictability : This algorithm is absolutely NOT designed to generate unpredictable unique id.
      you can add a sha-1 or sha-256 digest step at the end of this algorithm but you will loose uniqueness and enter to collision probability world.
      hash algorithms ensure that for same id generated here, you will have the same hash but for two differents id (a pair of ids), it is
      possible to have the same hash with a very little probability. You would certainly take an option on a bijective function that maps
      35 digits (or more) number to 35 digits (or more) number based on cipher block and secret key. read paper on breaking PRNG algorithms 
      in order to be convinced that problems could occur as soon as you use random library :)

      1 million id per second ?... on a Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz, you get :

      >>> timeit.timeit(uniqueid,number=40000)
      1.0114529132843018

      an average of 40000 id/second
    """
    mynow=datetime.now
    sft=datetime.strftime
    # store old datetime each time in order to check if we generate during same microsecond (glucky wallet !)
    # or if daylight savings event occurs (when clocks are adjusted backward) [rarely detected at this level]
    old_time=mynow() # fake init - on very speed machine it could increase your seed to seed + 1... but we have our contingency :)
    # manage seed
    seed_range_bits=14 # max range for seed
    seed_max_value=2**seed_range_bits - 1 # seed could not exceed 2**nbbits - 1
    # get random seed
    seed=random.getrandbits(seed_range_bits)
    current_seed=str(seed)
    # producing new ids
    while True:
        # get current time 
        current_time=mynow()
        if current_time <= old_time:
            # previous id generated in the same microsecond or Daylight saving time event occurs (when clocks are adjusted backward)
            seed = max(1,(seed + 1) % seed_max_value)
            current_seed=str(seed)
        # generate new id (concatenate seed and timestamp as numbers)
        #newid=hex(int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed])))[2:-1]
        newid=int(''.join([sft(current_time,'%f%S%M%H%d%m%Y'),current_seed]))
        # save current time
        old_time=current_time
        # return a new id
        yield newid

""" you get a new id for each call of uniqueid() """
uniqueid=__uniqueid__().next

import unittest
class UniqueIdTest(unittest.TestCase):
    def testGen(self):
        for _ in range(3):
            m=[uniqueid() for _ in range(10)]
            self.assertEqual(len(m),len(set(m)),"duplicates found !")

hope it helps !

jQuery dialog popup

This HTML is fine:

<a href="#" id="contactUs">Contact Us</a>                   
<div id="dialog" title="Contact form">
  <p>appear now</p>
</div>

You need to initialize the Dialog (not sure if you are doing this):

$(function() {
  // this initializes the dialog (and uses some common options that I do)
  $("#dialog").dialog({
    autoOpen : false, modal : true, show : "blind", hide : "blind"
  });

  // next add the onclick handler
  $("#contactUs").click(function() {
    $("#dialog").dialog("open");
    return false;
  });
});

Take multiple lists into dataframe

Adding to Aditya Guru's answer here. There is no need of using map. You can do it simply by:

pd.DataFrame(list(zip(lst1, lst2, lst3)))

This will set the column's names as 0,1,2. To set your own column names, you can pass the keyword argument columns to the method above.

pd.DataFrame(list(zip(lst1, lst2, lst3)),
              columns=['lst1_title','lst2_title', 'lst3_title'])

Display only date and no time

I had some problems with the other solutions on this page, so thought I'd drop this in.

@Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "form-control datepicker" })

So you only need to add "{0:d}" in the second parameter and you should be good to go.

Converting a string to a date in DB2

You can use:

select VARCHAR_FORMAT(creationdate, 'MM/DD/YYYY') from table name

Format price in the current locale and currency

I think Google could have answered your question ;-) See http://blog.chapagain.com.np/magento-format-price/.

You can do it with

$formattedPrice = Mage::helper('core')->currency($finalPrice, true, false);

How do you handle multiple submit buttons in ASP.NET MVC Framework?

I don't have enough rep to comment in the correct place, but I spent all day on this so want to share.

While trying to implement the "MultipleButtonAttribute" solution ValueProvider.GetValue(keyValue) would incorrectly come back null.

It turned out I was referencing System.Web.MVC version 3.0 when it should have been 4.0 (other assemblies are 4.0). I don't know why my project didn't upgrade correctly and I had no other obvious problems.

So if your ActionNameSelectorAttribute is not working... check that.

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

See my article on understanding vertical alignment. There are multiple techniques to accomplish what you want at the end of the discussion.

(Super-short summary: either set the line-height of the child equal to the height of the container, or set positioning on the container and absolutely position the child at top:50% with margin-top:-YYYpx, YYY being half the known height of the child.)

Javascript change font color

Don't use <font color=. It's a really old fashioned way to style text and some browsers even don't even support it anymore.

caniuse lists it as obsolete, and strongly recommends not using the <font> tag. The same is with MDN

Do not use this element! Though once normalized in HTML 3.2, it was deprecated in HTML 4.01, at the same time as all elements related to styling only, then obsoleted in HTML5.

Starting with HTML 4, HTML does not convey styling information anymore (outside the element or the style attribute of each element). For any new web development, styling should be written using CSS only.

The former behavior of the element can be achieved, and even better controlled using the CSS Fonts CSS properties.

If we look at when the 4.01 standard was published we see it was published in 1999

published html5 standard

where <font> was officially deprecated, meaning it is still supported but shouldn't be used anymore as it will go away in the newer standard.

And in the html5 standard released in August 2014 it was deemed obsolete and non conforming.

To achieve the desired effect use spans and css:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    return '<span style="color:'+thecolor+'">'+thetext+'</span>';
}
document.write(givemecolor('green',"Hello, I'm green"));
document.write(givemecolor('red',"Hello, I'm red"));
_x000D_
body {
  background: #333;
  color: #eee;
}
_x000D_
_x000D_
_x000D_

update

This question and answer are from 2012 and now I wouldn't recommend using document.write as it needs to be executed when the document is rendered first time. I had used it back then because I assumed OP was wishing to use it in such a way. I'd recommend using a more conventional way to insert the custom elements you wish to use, at the place you wish to insert them, without relying on document rendering and when and where the script is executed.

Native:

_x000D_
_x000D_
function givemecolor(thecolor,thetext)
{
    var span = document.createElement('span');
    span.style.color = thecolor;
    span.innerText = thetext;
    return span;
}
var container = document.getElementById('textholder');
container.append(givemecolor('green', "Hello I'm green"));
container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
function givemecolor(thecolor, thetext)
{
    var $span = $("<span>");
    $span.css({color:thecolor});
    $span.text(thetext);
    return $span;
}
var $container = $('#textholder');
$container.append(givemecolor('green', "Hello I'm green"));
$container.append(givemecolor('red', "Hello I'm red"));
_x000D_
body {
 background: #333;
 color: #eee;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> some title </h1>
<div id="textholder">
</div>
<p> some other text </p>
_x000D_
_x000D_
_x000D_

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

how do I initialize a float to its max/min value?

There's no real need to initialize to smallest/largest possible to find the smallest/largest in the array:

double largest = smallest = array[0];
for (int i=1; i<array_size; i++) {
    if (array[i] < smallest)
        smallest = array[i];
    if (array[i] > largest0
        largest= array[i];
}

Or, if you're doing it more than once:

#include <utility>

template <class iter>
std::pair<typename iter::value_type, typename iter::value_type> find_extrema(iter begin, iter end) {
    std::pair<typename iter::value_type, typename iter::value_type> ret;
    ret.first = ret.second = *begin;
    while (++begin != end) {
        if (*begin < ret.first)
           ret.first = *begin;
        if (*begin > ret.second)
           ret.second = *begin;
   }
   return ret;
}

The disadvantage of providing sample code -- I see others have already suggested the same idea.

Note that while the standard has a min_element and max_element, using these would require scanning through the data twice, which could be a problem if the array is large at all. Recent standards have addressed this by adding a std::minmax_element, which does the same as the find_extrema above (find both the minimum and maximum elements in a collection in a single pass).

Edit: Addressing the problem of finding the smallest non-zero value in an array of unsigned: observe that unsigned values "wrap around" when they reach an extreme. To find the smallest non-zero value, we can subtract one from each for the comparison. Any zero values will "wrap around" to the largest possible value for the type, but the relationship between other values will be retained. After we're done, we obviously add one back to the value we found.

unsigned int min_nonzero(std::vector<unsigned int> const &values) { 
    if (vector.size() == 0)
        return 0;
    unsigned int temp = values[0]-1;
    for (int i=1; i<values.size(); i++)
        if (values[i]-1 < temp)
            temp = values[i]-1;
    return temp+1;
}

Note this still uses the first element for the initial value, but we still don't need any "special case" code -- since that will wrap around to the largest possible value, any non-zero value will compare as being smaller. The result will be the smallest nonzero value, or 0 if and only if the vector contained no non-zero values.

git: 'credential-cache' is not a git command

For the sake of others having this issue - I landed here because I tried to get cute with how I set up a new github repository, but per the setup page credential helper doesn't work unless you clone a repository.

"Tip: The credential helper only works when you clone an HTTPS repository URL. If you use the SSH repository URL instead, SSH keys are used for authentication. This guide offers help generating and using an SSH key pair."

SQL NVARCHAR and VARCHAR Limits

You mus use nvarchar text too. that's mean you have to simply had a "N" before your massive string and that's it! no limitation anymore

DELARE @SQL NVARCHAR(MAX);
SET @SQL = N'SomeMassiveString > 4000 chars...';
EXEC(@SQL);
GO

endforeach in loops?

It's just a different syntax. Instead of

foreach ($a as $v) {
    # ...
}

You could write this:

foreach ($a as $v):
    # ...
endforeach;

They will function exactly the same; it's just a matter of style. (Personally I have never seen anyone use the second form.)

Javascript decoding html entities

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

Overlapping Views in Android

If you want to add you custom Overlay screen on Layout, you can create a Custom Linear Layout and get control of drawing and key events. You can my tutorial- Overlay on Android Layout- http://prasanta-paul.blogspot.com/2010/08/overlay-on-android-layout.html

Can't connect to MySQL server on 'localhost' (10061) after Installation

I found the same error re occurring even after I tried all the above solutions given above. I had even tried version 5.7 and few more. Guys don't waste your time trying to fix it. Rather install version 5.5. It's working perfectly fine without any unnecessary error.

How to alert using jQuery

$(".overdue").each( function() {
    alert("Your book is overdue.");
});

Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.

Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).

Perhaps use the size function:

alert( "You have " + $(".overdue").size() + " books overdue." );

Get day of week using NSDate

This code is to find the whole current week. It is written in Swift 2.0 :

var i = 2
var weekday: [String] = []
var weekdate: [String] = []
var weekmonth: [String] = []

@IBAction func buttonaction(sender: AnyObject) {

    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM-dd-yyyy"
    let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate)
    let weekdays = getDayOfWeek(dayOfWeekStrings)
    let calendar = NSCalendar.currentCalendar()

    while((weekdays - weekdays) + i < 9)
    {
        let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-weekdays+i), toDate: NSDate(), options: [])

        let dayFormatter = NSDateFormatter()
        dayFormatter.dateFormat = "EEEE"
        let dayOfWeekString = dayFormatter.stringFromDate(weekFirstDate!)
        weekday.append(dayOfWeekString)

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd"
        let dateOfWeekString = dateFormatter.stringFromDate(weekFirstDate!)
        weekdate.append(dateOfWeekString)

        let monthFormatter = NSDateFormatter()
        monthFormatter.dateFormat = "MMMM"
        let monthOfWeekString = monthFormatter.stringFromDate(weekFirstDate!)
        weekmonth.append(monthOfWeekString)

        i++
    }

    for(var j = 0; j<7 ; j++)
    {
    let day = weekday[j]
    let date = weekdate[j]
    let month = weekmonth[j]
    var wholeweek = date + "-" + month + "(" + day + ")"
    print(wholeweek)
    }

}

func getDayOfWeek(today:String)->Int {
    let formatter  = NSDateFormatter()
    formatter.dateFormat = "MMM-dd-yyyy"
    let todayDate = formatter.dateFromString(today)!
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
    let daynumber = myComponents.weekday
    return daynumber
}

The output will be like this:

14March(Monday) 15March(Tuesday) 16March(Wednesday) 17March(Thursday) 18March(Friday) 19March(Saturday) 20March(Sunday)

Non-recursive depth first search algorithm

Just wanted to add my python implementation to the long list of solutions. This non-recursive algorithm has discovery and finished events.


worklist = [root_node]
visited = set()
while worklist:
    node = worklist[-1]
    if node in visited:
        # Node is finished
        worklist.pop()
    else:
        # Node is discovered
        visited.add(node)
        for child in node.children:
            worklist.append(child)

DD/MM/YYYY Date format in Moment.js

for anyone who's using react-moment:

simply use format prop to your needed format:

const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

Bootstrap 3 dropdown select

You can also add 'active' class to the selected item.

$('.dropdown').on( 'click', '.dropdown-menu li a', function() { 
   var target = $(this).html();

   //Adds active class to selected item
   $(this).parents('.dropdown-menu').find('li').removeClass('active');
   $(this).parent('li').addClass('active');

   //Displays selected text on dropdown-toggle button
   $(this).parents('.dropdown').find('.dropdown-toggle').html(target + ' <span class="caret"></span>');
});

See the jsfiddle example

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

How do I configure PyCharm to run py.test tests?

I think you need to use the Run/Debug Configuration item on the toolbar. Click it and 'Edit Configurations' (or alternatively use the menu item Run->Edit Configurations). In the 'Defaults' section in the left pane there is a 'py.test' item which I think is what you want.

I also found that the manual didn't match up to the UI for this. Hope I've understood the problem correctly and that helps.

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

Best practices for SQL varchar column length

VARCHAR(255) and VARCHAR(2) take exactly the same amount of space on disk! So the only reason to limit it is if you have a specific need for it to be smaller. Otherwise make them all 255.

Specifically, when doing sorting, larger column do take up more space, so if that hurts performance, then you need to worry about it and make them smaller. But if you only ever select 1 row from that table, then you can just make them all 255 and it won't matter.

See: What are the optimum varchar sizes for MySQL?

Angular 2 declaring an array of objects

Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

  1. Create a class that represent your data model

    export class Data{
        private id:number;
        private text: string;
    
        constructor(id,text) {
            this.id = id;
            this.text = text;
        }
    
  2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

    export class AppComponent {
        private search_key: string;
        private dataList: Data[] = [];
    
        getWikiData() {
           this.httpService.getDataFromAPI()
            .subscribe(data => {
              this.parseData(data);
            });
         }
    
        parseData(jsonData: string) {
        //considering you get your data in json arrays
        for (let i = 0; i < jsonData[1].length; i++) {
             const data = new WikiData(jsonData[1][i], jsonData[2][i]);
             this.wikiData.push(data);
        }
      }
    }
    

How to navigate to a directory in C:\ with Cygwin?

Create a file named "overrideBashCdForWindowsPaths" in your HOME folder. Paste the following lines into that file and save it:

#!/bin/bash

function cd() {
    CD_PATH="$(history | tail -1 | sed -e "s,.*${FUNCNAME[0]}\s*,,g")"

    if [ -z "${CD_PATH}" -o "${CD_PATH}" = "~" ]; then
        CD_PATH="${HOME}"
    fi

    builtin cd "$(cygpath "$CD_PATH")"
}

Next, type the following command in a terminal, while you are in your HOME folder:

echo ". overrideBashCdForWindowsPaths" >> .bashrc

Close your terminal and open a new one. You can now easily change into that Windows folder by simply typing

cd C:\Python31\sip

The script reads the last command, extracts the path and passes it to Cygwin's path-conversion tool. By naming the function "cd" we sort of 'override' Bash's builtin "cd" and delegate the actual call to it in the very last line.

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

Accessing elements of Python dictionary by index

Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:

>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}

And getting how many of them are American (16), do like this:

>>> mydict["Apple"]["American"]
'16'

Document directory path of Xcode Device Simulator

With the adoption of CoreSimulator in Xcode 6.0, the data directories are per-device rather than per-version. The data directory is ~/Library/Developer/CoreSimulator/Devices//data where can be determined from 'xcrun simctl list'

Note that you can safely delete ~/Library/Application Support/iPhone Simulator and ~/Library/Logs/iOS Simulator if you don't plan on needing to roll back to Xcode 5.x or earlier.

How to test the type of a thrown exception in Jest

I use a slightly more concise version:

expect(() => {
  // Code block that should throw error
}).toThrow(TypeError) // Or .toThrow('expectedErrorMessage')

ConfigurationManager.AppSettings - How to modify and save?

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

How do you add a timed delay to a C++ program?

The top answer here seems to be an OS dependent answer; for a more portable solution you can write up a quick sleep function using the ctime header file (although this may be a poor implementation on my part).

#include <iostream>
#include <ctime>

using namespace std;

void sleep(float seconds){
    clock_t startClock = clock();
    float secondsAhead = seconds * CLOCKS_PER_SEC;
    // do nothing until the elapsed time has passed.
    while(clock() < startClock+secondsAhead);
    return;
}
int main(){

    cout << "Next string coming up in one second!" << endl;
    sleep(1.0);
    cout << "Hey, what did I miss?" << endl;

    return 0;
}

No content to map due to end-of-input jackson parser

This error is sometimes (often?) hiding the real problem: a failure condition could be causing the content to be incorrect, which then fails to deserialize.

In my case, today, I was making HTTP calls and (foolishly) omitted to check the HTTP status code before trying to unmarshal the body of the response => my real problem was actualy that I had some authentication error, which caused a 401 Unauthorized to be sent back to me, with an empty body. Since I was unmarshalling that empty body directly without checking anything, I was getting this No content to map due to end-of-input, without getting any clue about the authentication issue.

How to set caret(cursor) position in contenteditable element (div)?

I'm writting a syntax highlighter (and basic code editor), and I needed to know how to auto-type a single quote char and move the caret back (like a lot of code editors nowadays).

Heres a snippet of my solution, thanks to much help from this thread, the MDN docs, and a lot of moz console watching..

//onKeyPress event

if (evt.key === "\"") {
    let sel = window.getSelection();
    let offset = sel.focusOffset;
    let focus = sel.focusNode;

    focus.textContent += "\""; //setting div's innerText directly creates new
    //nodes, which invalidate our selections, so we modify the focusNode directly

    let range = document.createRange();
    range.selectNode(focus);
    range.setStart(focus, offset);

    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}

//end onKeyPress event

This is in a contenteditable div element

I leave this here as a thanks, realizing there is already an accepted answer.

Python PDF library

There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.

Why is Spring's ApplicationContext.getBean considered bad?

One of the coolest benefits of using something like Spring is that you don't have to wire your objects together. Zeus's head splits open and your classes appear, fully formed with all of their dependencies created and wired-in, as needed. It's magical and fantastic.

The more you say ClassINeed classINeed = (ClassINeed)ApplicationContext.getBean("classINeed");, the less magic you're getting. Less code is almost always better. If your class really needed a ClassINeed bean, why didn't you just wire it in?

That said, something obviously needs to create the first object. There's nothing wrong with your main method acquiring a bean or two via getBean(), but you should avoid it because whenever you're using it, you're not really using all of the magic of Spring.

How can I convert an Integer to localized month name in Java?

import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

How to run cron job every 2 hours

The line should read either:

0 0-23/2 * * * /home/username/test.sh

or

0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh

How to convert / cast long to String?

String strLong = Long.toString(longNumber);

Simple and works fine :-)

Difference between string and char[] types in C++

Strings have helper functions and manage char arrays automatically. You can concatenate strings, for a char array you would need to copy it to a new array, strings can change their length at runtime. A char array is harder to manage than a string and certain functions may only accept a string as input, requiring you to convert the array to a string. It's better to use strings, they were made so that you don't have to use arrays. If arrays were objectively better we wouldn't have strings.

Can't ignore UserInterfaceState.xcuserstate

Just "git clean -f -d" worked for me!

foreach for JSON array , syntax

Sure, you can use JS's foreach.

for (var k in result) {
  something(result[k])
}

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

Check for special characters (/*-+_@&$#%) in a string?

string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c) 
                                            || Char.IsWhiteSpace(c)).ToArray());

if (s != withoutSpecial)
{
    Console.WriteLine("String contains special chars");
}

How does setTimeout work in Node.JS?

The only way to ensure code is executed is to place your setTimeout logic in a different process.

Use the child process module to spawn a new node.js program that does your logic and pass data to that process through some kind of a stream (maybe tcp).

This way even if some long blocking code is running in your main process your child process has already started itself and placed a setTimeout in a new process and a new thread and will thus run when you expect it to.

Further complication are at a hardware level where you have more threads running then processes and thus context switching will cause (very minor) delays from your expected timing. This should be neglible and if it matters you need to seriously consider what your trying to do, why you need such accuracy and what kind of real time alternative hardware is available to do the job instead.

In general using child processes and running multiple node applications as separate processes together with a load balancer or shared data storage (like redis) is important for scaling your code.

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

MySQL Creating tables with Foreign Keys giving errno: 150

Helpful tip, use SHOW WARNINGS; after trying your CREATE query and you will receive the error as well as the more detailed warning:

    ---------------------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                                                                                                                                                                 |
+---------+------+--------------------------------------------------------------------------                          --------------------------------------------------------------------------------------------                          ---------------+
| Warning |  150 | Create table 'fakeDatabase/exampleTable' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.
|
| Error   | 1005 | Can't create table 'exampleTable' (errno:150)                                                                                                                                                                           |
+---------+------+--------------------------------------------------------------------------                          --------------------------------------------------------------------------------------------                          ---------------+

So in this case, time to re-create my table!

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

Simple PowerShell LastWriteTime compare

(ls $source).LastWriteTime

("ls", "dir", or "gci" are the default aliases for Get-ChildItem.)

How to reload / refresh model data from the server programmatically?

You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope:

function PersonListCtrl($scope, $http) {
  $scope.loadData = function () {
     $http.get('/persons').success(function(data) {
       $scope.persons = data;
     });
  };

  //initial load
  $scope.loadData();
}

then in your markup

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="loadData()">Refresh</button>
</div>

As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller:

for example (just puedo code) in your controller:

$scope.addPerson = function() {
     $scope.persons.push({ name: 'Test Monkey' });
};

Then you could use that in your view or whatever you'd want to do.

How to test code dependent on environment variables using JUnit?

For JUnit 4 users, System Lambda as suggested by Stefan Birkner is a great fit.

In case you are using JUnit 5, there is the JUnit Pioneer extension pack. It comes with @ClearEnvironmentVariable and @SetEnvironmentVariable. From the docs:

The @ClearEnvironmentVariable and @SetEnvironmentVariable annotations can be used to clear, respectively, set the values of environment variables for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the variables mentioned in the annotation will be restored to their original value or will be cleared if they didn't have one before. Other environment variables that are changed during the test, are not restored.

Example:

@Test
@ClearEnvironmentVariable(key = "SOME_VARIABLE")
@SetEnvironmentVariable(key = "ANOTHER_VARIABLE", value = "new value")
void test() {
    assertNull(System.getenv("SOME_VARIABLE"));
    assertEquals("new value", System.getenv("ANOTHER_VARIABLE"));
}

Make virtualenv inherit specific packages from your global site-packages

Install virtual env with

virtualenv --system-site-packages

and use pip install -U to install matplotlib

EF 5 Enable-Migrations : No context type was found in the assembly

Adding a class which inherits DbContext resolved my problem:

public class MyDbContext : DbContext { public MyDbContext() { } }

Using find command in bash script

You can use this:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

Stop Chrome Caching My JS Files

A few ideas:

  1. When you refresh your page in Chrome, do a CTRL+F5 to do a full refresh.
  2. Even if you set the expires to 0, it will still cache during the session. You'll have to close and re-open your browser again.
  3. Make sure when you save the files on the server, the timestamps are getting updated. Chrome will first issue a HEAD command instead of a full GET to see if it needs to download the full file again, and the server uses the timestamp to see.

If you want to disable caching on your server, you can do something like:

Header set Expires "Thu, 19 Nov 1981 08:52:00 GM"
Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
Header set Pragma "no-cache"

In .htaccess

AngularJs ReferenceError: $http is not defined

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

How to SELECT WHERE NOT EXIST using LINQ?

First of all, I suggest to modify a bit your sql query:

 select * from shift 
 where shift.shiftid not in (select employeeshift.shiftid from employeeshift 
                             where employeeshift.empid = 57);

This query provides same functionality. If you want to get the same result with LINQ, you can try this code:

//Variable dc has DataContext type here
//Here we get list of ShiftIDs from employeeshift table
List<int> empShiftIds = dc.employeeshift.Where(p => p.EmpID = 57).Select(s => s.ShiftID).ToList();

//Here we get the list of our shifts
List<shift> shifts = dc.shift.Where(p => !empShiftIds.Contains(p.ShiftId)).ToList();

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

Error: Cannot invoke an expression whose type lacks a call signature

I think what you want is:

abstract class Component {
  public deps: any = {};
  public props: any = {};

  public makePropSetter<T>(prop: string): (val: T) => T {
    return function(val) {
      this.props[prop] = val
      return val
    }
  }
}

class Post extends Component {
  public toggleBody: (val: boolean) => boolean;

  constructor () {
    super()
    this.toggleBody = this.makePropSetter<boolean>('showFullBody')
  }

  showMore (): boolean {
    return this.toggleBody(true)
  }

  showLess (): boolean {
    return this.toggleBody(false)
  }
}

The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

Apache giving 403 forbidden errors

Check that :

  • Apache can physically access the file (the user that run apache, probably www-data or apache, can access the file in the filesystem)
  • Apache can list the content of the folder (read permission)
  • Apache has a "Allow" directive for that folder. There should be one for /var/www/, you can check default vhost for example.

Additionally, you can look at the error.log file (usually located at /var/log/apache2/error.log) which will describe why you get the 403 error exactly.

Finally, you may want to restart apache, just to be sure all that configuration is applied. This can be generally done with /etc/init.d/apache2 restart. On some system, the script will be called httpd. Just figure out.

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

"Instantiating" a List in Java?

In Java, List is an interface. That is, it cannot be instantiated directly.

Instead you can use ArrayList which is an implementation of that interface that uses an array as its backing store (hence the name).

Since ArrayList is a kind of List, you can easily upcast it:

List<T> mylist = new ArrayList<T>();

This is in contrast with .NET, where, since version 2.0, List<T> is the default implementation of the IList<T> interface.

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

Could not find default endpoint element

Allow me to add one more thing to look for. (Tom Haigh's answer already alludes to it, but I want to be explicit)

My web.config file had the following defined:

<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>

I was already using basicHttpsBinding for one reference, but then I added a new reference which required basicHttpBinding (no s). All I had to do was add that to my protocolMapping as follows:

<protocolMapping>
    <add binding="basicHttpBinding" scheme="http" />
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>

As L.R. correctly points out, this needs to be defined in the right places. For me, that meant one in my Unit Test project's app.config as well as one in the main service project's web.config.

IE11 Document mode defaults to IE7. How to reset?

For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"

Click here for more details

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.

Pycharm: run only part of my Python file

You can select a code snippet and use right click menu to choose the action "Execute Selection in console".

How to select an item in a ListView programmatically?

        int i=99;//is what row you want to select and focus
        listViewRamos.FocusedItem = listViewRamos.Items[0];
        listViewRamos.Items[i].Selected = true;
        listViewRamos.Select();
        listViewRamos.EnsureVisible(i);//This is the trick

ng serve not detecting file changes automatically

I would like to leave my case here, just for reference. In my case, the problem was on the system permissions. I used a shared folder inside a VM as a repo. I had no other message like permission denied or something. Tried everything and then I just realized that I was using a network drive.

Android: Center an image

Another method. (in Relative tested, but I think in Linear would be also works)

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:adjustViewBounds="true"
    android:gravity="center"

If you use Eclipse you can choose graphical layout when *.xml file is active. On the top, you will find the Structure and option Adjust View Bounds. It will cut short all dimensions of pseudo-frame (blue rectangle) to size of your drawable file.

See also the scaleType option with make funny your image. Try it in Eclipse ;)

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

How to import cv2 in python3?

The best way is to create a virtual env. first and then do pip install , everything will work fine

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Getting "conflicting types for function" in C, why?

In "classic" C language (C89/90) when you call an undeclared function, C assumes that it returns an int and also attempts to derive the types of its parameters from the types of the actual arguments (no, it doesn't assume that it has no parameters, as someone suggested before).

In your specific example the compiler would look at do_something(dest, src) call and implicitly derive a declaration for do_something. The latter would look as follows

int do_something(char *, char *)

However, later in the code you explicitly declare do_something as

char *do_something(char *, const char *)

As you can see, these declarations are different from each other. This is what the compiler doesn't like.

jQuery get input value after keypress

please use this code for input text

$('#search').on("input",function (e) {});

if you use .on("change",function (e) {}); then you need to blur input

if you use .on("keyup",function (e) {}); then you get value before the last character you typed

How to set custom ActionBar color / style?

You can define the color of the ActionBar (and other stuff) by creating a custom Style:

Simply edit the res/values/styles.xml file of your Android project.

For example like this:

<resources>
    <style name="MyCustomTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBarTheme</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">ANY_HEX_COLOR_CODE</item>
    </style>
</resources>

Then set "MyCustomTheme" as the Theme of your Activity that contains the ActionBar.

You can also set a color for the ActionBar like this:

ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED)); // set your desired color

Taken from here: How do I change the background color of the ActionBar of an ActionBarActivity using XML?

How to print object array in JavaScript?

There is a wonderful print_r implementation for JavaScript in php.js library.

Note, you should also add echo support in the code.

DEMO: http://jsbin.com/esexiw/1

How to read a line from the console in C?

If you are using the GNU C library or another POSIX-compliant library, you can use getline() and pass stdin to it for the file stream.

Why is my method undefined for the type object?

The line

Object EchoServer0;

says that you are allocating an Object named EchoServer0. This has nothing to do with the class EchoServer0. Furthermore, the object is not initialized, so EchoServer0 is null. Classes and identifiers have separate namespaces. This will actually compile:

String String = "abc";  // My use of String String was deliberate.

Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enums are all-capitals.

public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;

How to Edit a row in the datatable

Try the SetField method:

By passing column object :

table.Rows[rowIndex].SetField(column, value);

By Passing column index :

table.Rows[rowIndex].SetField(0 /*column index*/, value);

By Passing column name as string :

table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);

How do you run a .exe with parameters using vba's shell()?

Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.

Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
 " -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)

Open some text file.

Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")

Open some application.

Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)

Hope this helps!

changing minDate option in JQuery DatePicker not working

How to dynamically alter the minDate (after init)

The above answers address how to set the default minDate at init, but the question was actually how to dynamically alter the minDate, below I also clarify How to set the default minDate.

All that was wrong with the original question was that the minDate value being set should have been a string (don't forget the quotes):

$('#datePickerId').datepicker('option', 'minDate', '3');

minDate also accepts a date object and a common use is to have an end date you are trying to calculate so something like this could be useful:

$('#datePickerId').datepicker(
    'option', 'minDate', new Date($(".datePop.start").val())
);

How to set the default minDate (at init)

Just answering this for best practice; the minDate option expects one of:

  1. a string in the current dateFormat OR
  2. number of days from today (e.g. +7) OR
  3. string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '-1y -1m')

@bogart setting the string to "0" is a solution as it satisfies option 2 above

$('#datePickerId').datepicker('minDate': '3');

jQuery UI docs for minDate

How to get the Mongo database specified in connection string in C#

Update:

MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

var _server = new MongoClient(connectionString).GetServer();

It's easy. You should first take database name from connection string and then get database by name. Complete example:

var connectionString = "mongodb://localhost:27020/mydb";

//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);

//and then get database by database name:
_server.GetDatabase(_databaseName);

Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

From docs:

NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.

Breaking a list into multiple columns in Latex

Another option to avoid nesting two different environments (like multicols and enumerate).

The environment called tasks from the package with the same name seems to me very easy to customize thanks to a variety of options (pdf guide here).

This code:

\documentclass{article}
\usepackage{tasks}

%\settasks{style=itemize}

\begin{document}
Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.

\begin{tasks}(2)
\task[*] a
\task[*] b
\task[*] c
\task[*] d
\task[*] e
\task[*] f
\end{tasks}    

Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.
\end{document}

produces this output

tasks

The package tasks was updated in August 2020 and it was originally created specifically for horizontally columned lists (see the screenshot just above here), the motivations behind this are resumed in the guide. If such arrangement of the items/tasks is acceptable, then this may be a good choice since it keeps - IMHO - the code tidy and flexible.

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

SELECT * FROM (
    SELECT * FROM Table1 WHERE Field1 = Value1
    UNION
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

I think your best option would just be to include the readonly attribute in your template rendered in a <span> or <p> rather than include it in the form if it's readonly.

Forms are for collecting data, not displaying it. That being said, the options to display in a readonly widget and scrub POST data are fine solutions.

ImportError: Couldn't import Django

If you are working on a machine where it doesn't have permissions to all the files and moreover you have two versions such as default 2.7 & latest 3.6 then while running the command use the python version with the command. If the latest python is installed with sudo then run the command with sudo.

exp:

sudo python3.6 manage.py runserver

How do I write to the console from a Laravel Controller?

If you want the fancy command IO from Laravel (like styling, asking and table) then I created this class below

Instructions

I have not fully verified everywhere that it is THE cleanest solution etc, but it works nice (but I only tested it from within a unit test case, under Laravel 5.5).

So most probably you can use it however you like:

$cmd = new ConsoleCommand;

$cmd->error("Aw snap!");
$cmd->table($headers, $rows);
$answer = $cmd->ask("Tell me, what do you need?");

//even Symfony's progress bar
$cmd->outputStyle->progressStart(5);  //set n = 100% (here 100% is 5 steps)
$cmd->outputStyle->progressAdvance(); //you can call it n times
$cmd->outputStyle->progressFinish();  //set to 100%

Or course you can also wrap in your own facade, or some static singleton etc, or anyway you wish.

The class itself

class ConsoleCommand extends \Illuminate\Console\Command
{
    protected $name = 'NONEXISTENT';
    protected $hidden = true;

    public $outputSymfony;
    public $outputStyle;

    public function __construct($argInput = null)
    {
        parent::__construct();

        $this->input = new \Symfony\Component\Console\Input\StringInput($argInput);

        $this->outputSymfony = new \Symfony\Component\Console\Output\ConsoleOutput();
        $this->outputStyle = new \Illuminate\Console\OutputStyle($this->input, $this->outputSymfony);

        $this->output = $this->outputStyle;
    }

}

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

iTerm2 keyboard shortcut - split pane navigation

Spanish ISO:

  1. ?+?+[ goes left top
  2. ?+?+] goes bottom right

Get started with Latex on Linux

I would recommend start using Lyx, with that you can use Latex just as easy as OOO-Writer. It gives you the possibility to step into Latex deeper by manually adding Latex-Code to your Document. PDF is just one klick away after installatioin. Lyx is cross-plattform.

How do I append one string to another in Python?

str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))

That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...). str.join() takes an iterable, so you'd have to put the strings in a list or a tuple.

That's about as efficient as it gets for a builtin method.

jQuery: How can I create a simple overlay?

What do you intend to do with the overlay? If it's static, say, a simple box overlapping some content, just use absolute positioning with CSS. If it's dynamic (I believe this is called a lightbox), you can write some CSS-modifying jQuery code to show/hide the overlay on-demand.

SQL: Return "true" if list of records exists?

I know this is old but I think this will help anyone else who comes looking...

SELECT CAST(COUNT(ProductID) AS bit) AS [EXISTS] FROM Products WHERE(ProductID = @ProductID)

This will ALWAYS return TRUE if exists and FALSE if it doesn't (as opposed to no row).

How to refresh the data in a jqGrid?

Try this to reload jqGrid with new data

jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');

How to block until an event is fired in c#

If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:

public class Foo
{
    public delegate void MyEventHandler(object source, MessageEventArgs args);
    public event MyEventHandler _event;
    public string ReadLine()
    {
        return Observable
            .FromEventPattern<MyEventHandler, MessageEventArgs>(
                h => this._event += h,
                h => this._event -= h)
            .Select(ep => ep.EventArgs.Message)
            .First();
    }
    public void SendLine(string message)
    {
        _event(this, new MessageEventArgs() { Message = message });
    }
}

public class MessageEventArgs : EventArgs
{
    public string Message;
}

I can use it like this:

var foo = new Foo();

ThreadPoolScheduler.Instance
    .Schedule(
        TimeSpan.FromSeconds(5.0),
        () => foo.SendLine("Bar!"));

var resp = foo.ReadLine();

Console.WriteLine(resp);

I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.

remove legend title in ggplot

You were almost there : just add theme(legend.title=element_blank())

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  theme(legend.title=element_blank())

This page on Cookbook for R gives plenty of details on how to customize legends.

how to delete installed library form react native project

I followed the following steps:--

  1. react-native unlink <lib name> -- this command has done the unlinking of the library from both platforms.

  2. react-native uninstall <lib name> -- this has uninstalled the library from the node modules and its dependencies

  3. Manually removed the library name from package.json -- somehow the --save command was not working for me to remove the library declaration from package.json.

After this I have manually deleted the empty react-native library from the node_modules folder

How to increase the gap between text and underlining in CSS

See my fiddle.

You would need to use the border width property and the padding property. I added some animation to make it look cooler:

_x000D_
_x000D_
body{_x000D_
  background-color:lightgreen;_x000D_
}_x000D_
a{_x000D_
  text-decoration:none;_x000D_
  color:green;_x000D_
  border-style:solid;_x000D_
  border-width: 0px 0px 1px 0px;_x000D_
  transition: all .2s ease-in;_x000D_
}_x000D_
_x000D_
a:hover{_x000D_
  color:darkblue;_x000D_
  border-style:solid;_x000D_
  border-width: 0px 0px 1px 0px;_x000D_
  padding:2px;_x000D_
}
_x000D_
<a href='#' >Somewhere ... over the rainbow (lalala)</a> , blue birds, fly... (tweet tweet!), and I wonder (hmm) about what a <i><a href="#">what a wonder-ful world!</a> World!</i>
_x000D_
_x000D_
_x000D_

How can I change the remote/target repository URL on Windows?

The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.

On my machine in a repo I regularly use it looks like this:

KidA% cat .git/config 
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    autocflg = true
[remote "origin"]
    url = ssh://localhost:8888/opt/local/var/git/project.git
    #url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
    fetch = +refs/heads/*:refs/remotes/origin/*

The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.

This is the file that is getting manipulated under-the-hood when you run something like git remote rm or git remote add but in this case since its only a typo you made it might make sense to correct it this way.

How to insert an object in an ArrayList at a specific position

To insert value into ArrayList at particular index, use:

public void add(int index, E element)

This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.


To replace the element at the specified position, use:

public E set(int index, E element)

This method replaces the element at the specified position in the list with the specified element, and returns the element previously at the specified position.

Detecting superfluous #includes in C/C++?

The problem with detecting superfluous includes is that it can't be just a type dependency checker. A superfluous include is a file which provides nothing of value to the compilation and does not alter another item which other files depend. There are many ways a header file can alter a compile, say by defining a constant, redefining and/or deleting a used macro, adding a namespace which alters the lookup of a name some way down the line. In order to detect items like the namespace you need much more than a preprocessor, you in fact almost need a full compiler.

Lint is more of a style checker and certainly won't have this full capability.

I think you'll find the only way to detect a superfluous include is to remove, compile and run suites.

How to enter a series of numbers automatically in Excel

If you want to pick cell entries from a list then you have a couple of non-code based options

I would recommend The Data Validation approach where

  • creating a list of your 100 records in a single column,
  • provide a range name to this list,
  • then using Data Validation's List option

sample from Debra's site below, click on the first link above to access it.

Data Validation

_tkinter.TclError: no display name and no $DISPLAY environment variable

To add up on the answer, I used this at the beginning of the needed script. So it runs smoothly on different environments.

import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
    print('no display found. Using non-interactive Agg backend')
    mpl.use('Agg')
import matplotlib.pyplot as plt

Because I didn't want it to be alsways using the 'Agg' backend, only when it would go through Travis CI for example.

How do I enable saving of filled-in fields on a PDF form?

When you use Acrobat 8, or 9, select "enable usage rights" from the Advanced menu. This adds about 20 kb to the pdf.

The other possibility is to use CutePDF Pro, add a submit button and have the XFDF data submitted to your self as an email or to a web server. The XFDF data can then reload the original PDF with your data.

Trying to get Laravel 5 email to work

My .env file configuration is like this for laravel 5.1

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=tls

here most important thing is that I created gmail application specific password(16 digit).

I need to reveal one more thing since no luck for any of configuration. That is, whenever I changed .env file need to run this command

php artisan config:cache

And this is most most most important because without this command laravel executes previous settings from it's cache. It's required me more than 10 hours to figure out.

USB Debugging option greyed out

I have a feeling that if you have a corporate phone, your corporation IT might also be blocking USB Debugging. I've tried all the different connection modes and the USB Debugging option remains firmly greyed out.

I'm trying to get in to enable the BATTERY_STATS for GSam Monitor Pro, but I think it's disable through the Airwatch MDM software my company makes me use. They pay for it so I guess I'm stuck.

Is this how you define a function in jQuery?

jQuery.fn.extend({
    zigzag: function () {
        var text = $(this).text();
        var zigzagText = '';
        var toggle = true; //lower/uppper toggle
            $.each(text, function(i, nome) {
                zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
                toggle = (toggle) ? false : true;
            });
    return zigzagText;
    }
});

How can I delete a user in linux when the system says its currently used in a process

restart your computer and run $sudo deluser username... worked for me

URLEncoder not able to translate space character

If you are using jetty then org.eclipse.jetty.util.URIUtil will solve the issue.

String encoded_string = URIUtil.encodePath(not_encoded_string).toString();

EntityType has no key defined error

You don't have to use key attribute all the time. Make sure the mapping file properly addressed the key

this.HasKey(t => t.Key);
this.ToTable("PacketHistory");
this.Property(p => p.Key)
            .HasColumnName("PacketHistorySK");

and don't forget to add the mapping in the Repository's OnModelCreating

modelBuilder.Configurations.Add(new PacketHistoryMap());

VBA Convert String to Date

Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.

How to load/reference a file as a File instance from the classpath

Try getting hold of a URL for your classpath resource:

URL url = this.getClass().getResource("/com/path/to/file.txt")

Then create a file using the constructor that accepts a URI:

File file = new File(url.toURI());

Can I set the height of a div based on a percentage-based width?

This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box CSS attribute:

_x000D_
_x000D_
div {_x000D_
  border: 1px solid red;_x000D_
  width: 40%;_x000D_
  padding: 40%;_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
}_x000D_
p {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div>_x000D_
  <p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adjust percentages to your liking. Here is a JSFiddle

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

TempData keep() vs peek()

When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.

That means if you put something on TempData like

TempData["value"] = "someValueForNextRequest";

And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:

//second request, read value and is marked for deletion
object value = TempData["value"];

//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null

The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.

With Peek you get the value without marking it for deletion with a single call, see msdn:

//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn

//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

You have 2 good questions about how TempData works here and here

Hope it helps!

Execute method on startup in Spring

With SpringBoot, we can execute a method on startup via @EventListener annotation

@Component
public class LoadDataOnStartUp
{   
    @EventListener(ApplicationReadyEvent.class)
    public void loadData()
    {
        // do something
    }
}

Vertical dividers on horizontal UL menu

Quite and simple without any "having to specify the first element". CSS is more powerful than most think (e.g. the first-child:before is great!). But this is by far the cleanest and most proper way to do this, at least in my opinion it is.

#navigation ul
{
    margin: 0;
    padding: 0;
}

#navigation ul li
{
    list-style-type: none;
    display: inline;
}

#navigation li:not(:first-child):before {
    content: " | ";
}

Now just use a simple unordered list in HTML and it'll populate it for you. HTML should look like this:

<div id="navigation">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Support</a></li>
    </ul>
</div><!-- navigation -->

The result will be just like this:

HOME | ABOUT US | SUPPORT

Now you can indefinitely expand and never have to worry about order, changing links, or your first entry. It's all automated and works great!

How to enable cURL in PHP / XAMPP

On Debian with Apache 2:

apt-get install php5-curl
/etc/init.d/apache2 restart

(php4-curl if it's php4)

How to keep :active css style after click a button

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}    

.my-div{background-color:#FFF} 

#activate-div:checked ~ label 
.my-div{background-color:#000}



To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF} 

#activate-div:checked + 
.my-div{background-color:#000}

Hope it helps!!

word-wrap break-word does not work in this example

  • inline-block is of no use in this scenario

SOLUTION

  • word-break: normal|break-all|keep-all|break-word|initial|inherit;
    Simple Answer to your doubt is Use above and make sure white-space: nowrap nowhere used.

NOTE FOR BETTER UNDERSTANDING:

  • word-wrap/overflow-wrap is used to break words that overflow their container

  • word-break property breaks all words at the end of a line, even those that would normally wrap onto another line and wouldn’t overflow their container.

  • word-wrap is the historic and nonstandard property. It has been renamed to overflow-wrap but remains an alias, browsers must support in future. Many browsers (especially the old ones) don’t support overflow-wrap and require word-wrap as a fallback (which is supported by all).

  • If you want to please the W3C you should consider associate both in your CSS. If you don’t, using word-wrap alone is just fine.

Can I add color to bootstrap icons only using CSS?

Another possible way to have bootstrap icons in a different color is to create a new .png in the desired color, (eg. magenta) and save it as /path-to-bootstrap-css/img/glyphicons-halflings-magenta.png

In your variables.less find

// Sprite icons path
// -------------------------
@iconSpritePath:          "../img/glyphicons-halflings.png";
@iconWhiteSpritePath:     "../img/glyphicons-halflings-white.png";

and add this line

@iconMagentaSpritePath:     "../img/glyphicons-halflings-magenta.png";

In your sprites.less add

/* Magenta icons with optional class, or on hover/active states of certain elements */
.icon-magenta,
.nav-pills > .active > a > [class^="icon-"],
.nav-pills > .active > a > [class*=" icon-"],
.nav-list > .active > a > [class^="icon-"],
.nav-list > .active > a > [class*=" icon-"],
.navbar-inverse .nav > .active > a > [class^="icon-"],
.navbar-inverse .nav > .active > a > [class*=" icon-"],
.dropdown-menu > li > a:hover > [class^="icon-"],
.dropdown-menu > li > a:hover > [class*=" icon-"],
.dropdown-menu > .active > a > [class^="icon-"],
.dropdown-menu > .active > a > [class*=" icon-"],
.dropdown-submenu:hover > a > [class^="icon-"],
.dropdown-submenu:hover > a > [class*=" icon-"] {
  background-image: url("@{iconMagentaSpritePath}");
}

And use it like this:

<i class='icon-chevron-down icon-magenta'></i>

Hope it helps someone.

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

What is the canonical way to trim a string in Ruby without creating a new string?

I think your example is a sensible approach, although you could simplify it slightly as:

@title = tokens[Title].strip! || tokens[Title] if tokens[Title]

Alternative you could put it on two lines:

@title = tokens[Title] || ''
@title.strip!

ImportError: DLL load failed: The specified module could not be found

(I found this answer from a video: http://www.youtube.com/watch?v=xmvRF7koJ5E)

  1. Download msvcp71.dll and msvcr71.dll from the web.

  2. Save them to your C:\Windows\System32 folder.

  3. Save them to your C:\Windows\SysWOW64 folder as well (if you have a 64-bit operating system).

Now try running your code file in Python and it will load the graph in couple of seconds.

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

Failed to resolve version for org.apache.maven.archetypes

This worked for me:- navigate to windows-> preferences-> maven and check the "download artifacts sources" and click apply.

Jquery click event not working after append method

Use on :

$('#registered_participants').on('click', '.new_participant_form', function() {

So that the click is delegated to any element in #registered_participants having the class new_participant_form, even if it's added after you bound the event handler.

Python unexpected EOF while parsing

Use raw_input instead of input :)

If you use input, then the data you type is is interpreted as a Python Expression which means that you end up with gawd knows what type of object in your target variable, and a heck of a wide range of exceptions that can be generated. So you should NOT use input unless you're putting something in for temporary testing, to be used only by someone who knows a bit about Python expressions.

raw_input always returns a string because, heck, that's what you always type in ... but then you can easily convert it to the specific type you want, and catch the specific exceptions that may occur. Hopefully with that explanation, it's a no-brainer to know which you should use.

Reference

Note: this is only for Python 2. For Python 3, raw_input() has become plain input() and the Python 2 input() has been removed.

Why maven? What are the benefits?

Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

Eclipse: Enable autocomplete / content assist

  1. window->preferences->java->Editor->Contest Assist
  2. Enter in Auto activation triggers for java:
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
  3. Apply and Close

other method:
type initial letter then ctrl+spacebar for auto-complete options.

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

nullable object must have a value

Assign the members directly without the .Value part:

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;
}

Connect to SQL Server Database from PowerShell

# database Intraction

$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; 
User ID= YourUserID; Password= YourPassword" 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) 
$SqlConnection.Close() 

#End :database Intraction
clear

How can I call a function using a function pointer?

You can do the following: Suppose you have your A,B & C function as the following:

bool A()
{
   .....
}

bool B()
{
   .....
}

bool C()
{

 .....
}

Now at some other function, say at main:

int main()
{
  bool (*choice) ();

  // now if there is if-else statement for making "choice" to 
  // point at a particular function then proceed as following

  if ( x == 1 )
   choice = A;

  else if ( x == 2 )
   choice = B;


  else
   choice = C;

if(choice())
 printf("Success\n");

else
 printf("Failure\n");

.........
  .........
  }

Remember this is one example for function pointer. there are several other method and for which you have to learn function pointer clearly.

Can multiple different HTML elements have the same ID if they're different elements?

I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).

Should IDs be unique? YES.

Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Android Studio cannot find the svn command because it's not on PATH, and it doesn't know where svn is installed.

One way to fix is to edit the PATH environment variable: add the directory that contains svn.exe. You will need to restart Android Studio to make it re-read the PATH variable.

Another way is to set the absolute path of svn.exe in the Use command client box in the settings screen that you included in your post.

UPDATE

According to this other post, TortoiseSVN doesn't include the command line tools by default. But you can re-run the installer and enable it. That will add svn.exe to PATH, and Android Studio will correctly pick it up.

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

Change httpd.conf file as follows:

from

<Directory />
    AllowOverride none
    Require all denied
</Directory>

to

<Directory />
    AllowOverride none
    Require all granted
</Directory>

Integrating CSS star rating into an HTML form

CSS:

.rate-container > i {
    float: right;
}

.rate-container > i:HOVER,
.rate-container > i:HOVER ~ i {
    color: gold;
}

HTML:

<div class="rate-container">
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
</div>

Content Security Policy: The page's settings blocked the loading of a resource

You can disable them in your browser.

Firefox

Type about:config in the Firefox address bar and find security.csp.enable and set it to false.

Chrome

You can install the extension called Disable Content-Security-Policy to disable CSP.

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

How to fill in proxy information in cntlm config file?

For me just using cntlm -H wasn't generating the right hash, but it does with the command below providing the user name.

If you need to generate a new password hash for cntlm, because you have change it or you've been forced to update it, you can just type the below command and update your cntlm.conf configuration file with the output:

$ cntlm -u test -H
Password: 
PassLM          D2AABAF8828482D5552C4BCA4AEBFB11
PassNT          83AC305A1582F064C469755F04AE5C0A
PassNTLMv2      4B80D9370D353EE006D714E39715A5CB    # Only for user 'test', domain ''

Handling back button in Android Navigation Component

Newest Update - April 25th, 2019

New release androidx.activity ver. 1.0.0-alpha07 brings some changes

More explanations in android official guide: Provide custom back navigation

Example:

public class MyFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // This callback will only be called when MyFragment is at least Started.
        OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
            @Override
            public void handleOnBackPressed() {
                // Handle the back button event
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

        // The callback can be enabled or disabled here or in handleOnBackPressed()
    }
    ...
}

Old Updates

UPD: April 3rd, 2019

Now its simplified. More info here

Example:

requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), this);

@Override
public boolean handleOnBackPressed() {
    //Do your job here
    //use next line if you just need navigate up
    //NavHostFragment.findNavController(this).navigateUp(); 
    //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
    return true;
    }

Deprecated (since Version 1.0.0-alpha06 April 3rd, 2019) :

Since this, it can be implemented just using JetPack implementation OnBackPressedCallback in your fragment and add it to activity: getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);

Your fragment should looks like this:

public MyFragment extends Fragment implements OnBackPressedCallback {

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
}
    
    @Override
    public boolean handleOnBackPressed() {
        //Do your job here
        //use next line if you just need navigate up
        //NavHostFragment.findNavController(this).navigateUp(); 
        //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().removeOnBackPressedCallback(this);
    }
}

UPD: Your activity should extends AppCompatActivityor FragmentActivity and in Gradle file:

 implementation 'androidx.appcompat:appcompat:{lastVersion}'

'innerText' works in IE, but not in Firefox

Note that the Element::innerText property will not contain the text which has been hidden by CSS style "display:none" in Google Chrome (as well it will drop the content that has been masked by other CSS technics (including font-size:0, color:transparent, and a few other similar effects that cause the text not to be rendered in any visible way).

Other CSS properties are also considered :

  • First the "display:" style of inner elements is parsed to determine if it delimits a block content (such as "display:block" which is the default of HTML block elements in the browser's builtin stylesheet, and whose behavior as not been overriden by your own CSS style); if so a newline will be inserted in the value of the innerText property. This won't happen with the textContent property.
  • The CSS properties that generate inline contents will also be considered : for example the inline element <br \> that generates an inline newline will also generate an newline in the value of innerText.
  • The "display:inline" style causes no newline either in textContent or innerText.
  • The "display:table" style generates newlines around the table and between table rows, but"display:table-cell" will generate a tabulation character.
  • The "position:absolute" property (used with display:block or display:inline, it does not matter) will also cause a line break to be inserted.
  • Some browsers will also include a single space separation between spans

But Element::textContent will still contain ALL contents of inner text elements independantly of the applied CSS even if they are invisible. And no extra newlines or whitespaces will be generated in textContent, which just ignores all styles and the structure and inline/block or positioned types of inner elements.

A copy/paste operation using mouse selection will discard the hidden text in the plain-text format that is put in the clipboard, so it won't contain everything in the textContent, but only what is within innerText (after whitespace/newline generation as above).

Both properties are then supported in Google Chrome, but their content may then be different. Older browsers still included in innetText everything like what textContent now contains (but their behavior in relation with then generation of whitespaces/newlines was inconsistant).

jQuery will solve these inconsistencies between browsers using the ".text()" method added to the parsed elements it returns via a $() query. Internally, it solves the difficulties by looking into the HTML DOM, working only with the "node" level. So it will return something looking more like the standard textContent.

The caveat is that that this jQuery method will not insert any extra spaces or line breaks that may be visible on screen caused by subelements (like <br />) of the content.

If you design some scripts for accessibility and your stylesheet is parsed for non-aural rendering, such as plugins used to communicate with a Braille reader, this tool should use the textContent if it must include the specific punctuation signs that are added in spans styled with "display:none" and that are typically included in pages (for example for superscripts/subscripts), otherwise the innerText will be very confusive on the Braille reader.

Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.

IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML property after the assignment of innerText or textContent.

link button property to open in new tab?

 <asp:LinkButton ID="LinkButton1" runat="server" target="_blank">LinkButton</asp:LinkButton>

Use target="_blank" because It creates anchor markup. the following HTML is generated for above code

<a id="ctl00_ContentPlaceHolder1_LinkButton1" target="_blank" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$LinkButton1','')">LinkButton</a>

Remove leading and trailing spaces?

Expand your one liner into multiple lines. Then it becomes easy:

f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])

parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)

Node.js fs.readdir recursive directory search

just a simple walk

let pending = [baseFolderPath]
function walk () {
    pending.shift();
    // do stuffs width pending[0] and change pending items
    if (pending[0]) walk(pending[0])
}
walk(pending[0])

Collapse all methods in Visual Studio Code

  • Ctrl + K + 0: fold all levels (namespace, class, method, and block)
  • Ctrl + K + 1: namspace
  • Ctrl + K + 2: class
  • Ctrl + K + 3: methods
  • Ctrl + K + 4: blocks
  • Ctrl + K + [ or Ctrl + k + ]: current cursor block
  • Ctrl + K + j: UnFold

Does it matter what extension is used for SQLite database files?

If you have settled on a particular set of tools to access / modify your databases, I would go with whatever extension they expect you to use. This will avoid needless friction when doing development tasks.

For instance, SQLiteStudio v3.1.1 defaults to looking for files with the following extensions:

enter image description here

(db|sdb|sqlite|db3|s3db|sqlite3|sl3|db2|s2db|sqlite2|sl2)

If necessary for deployment your installation mechanism could rename the file if obscuring the file type seems useful to you (as some other answers have suggested). Filename requirements for development and deployment can be different.

How to completely uninstall Android Studio from windows(v10)?

To Completely Remove Android Studio from Windows:

Step 1: Run the Android Studio uninstaller

The first step is to run the uninstaller. Open the Control Panel and under Programs, select Uninstall a Program. After that, click on "Android Studio" and press Uninstall. If you have multiple versions, uninstall them as well.

Step 2: Remove the Android Studio files

To delete any remains of Android Studio setting files, in File Explorer, go to your user folder (%USERPROFILE%), and delete .android, .AndroidStudio and any analogous directories with versions on the end, i.e. .AndroidStudio1.2, as well as .gradle and .m2 if they exist.

Then go to %APPDATA% and delete the JetBrains directory.

Finally, go to C:\Program Files and delete the Android directory.

Step 3: Remove SDK

To delete any remains of the SDK, go to %LOCALAPPDATA% and delete the Android directory.

Step 4: Delete Android Studio projects

Android Studio creates projects in a folder %USERPROFILE%\AndroidStudioProjects, which you may want to delete.

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

How to set environment variable or system property in spring tests?

All of the answers here currently only talk about the system properties which are different from the environment variables that are more complex to set, esp. for tests. Thankfully, below class can be used for that and the class docs has good examples

EnvironmentVariables.html

A quick example from the docs, modified to work with @SpringBootTest

@SpringBootTest
public class EnvironmentVariablesTest {
   @ClassRule
   public final EnvironmentVariables environmentVariables = new EnvironmentVariables().set("name", "value");

   @Test
   public void test() {
     assertEquals("value", System.getenv("name"));
   }
 }

How to upload files in asp.net core?

Fileservice.cs:

public class FileService : IFileService
{
    private readonly IWebHostEnvironment env;

    public FileService(IWebHostEnvironment env)
    {
        this.env = env;
    }

    public string Upload(IFormFile file)
    {
        var uploadDirecotroy = "uploads/";
        var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);

        if (!Directory.Exists(uploadPath))
            Directory.CreateDirectory(uploadPath);

        var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploadPath, fileName);

        using (var strem = File.Create(filePath))
        {
            file.CopyTo(strem);
        }
        return fileName;
    }
}

IFileService:

namespace studentapps.Services
{
    public interface IFileService
    {
        string Upload(IFormFile file);
    }
}

StudentController:

[HttpGet]
public IActionResult Create()
{
    var student = new StudentCreateVM();
    student.Colleges = dbContext.Colleges.ToList();
    return View(student);
}

[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
    Student student = new Student()
    {
        DisplayImage = vm.DisplayImage.FileName,
        Name = vm.Name,
        Roll_no = vm.Roll_no,
        CollegeId = vm.SelectedCollegeId,
    };


    if (ModelState.IsValid)
    {
        var fileName = fileService.Upload(vm.DisplayImage);
        student.DisplayImage = fileName;
        getpath = fileName;

        dbContext.Add(student);
        dbContext.SaveChanges();
        TempData["message"] = "Successfully Added";
    }
    return RedirectToAction("Index");
}

SUM of grouped COUNT in SQL Query

After the query, run below to get the total row count

select @@ROWCOUNT

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

Is an entity body allowed for an HTTP DELETE request?

It is worth noting that the OpenAPI specification for version 3.0 dropped support for DELETE methods with a body:

see here and here for references

This may affect your implementation, documentation, or use of these APIs in the future.

<embed> vs. <object>

Answer updated for 2020:

Both <object> and <embed> are included in the WHAT-WG HTML Living Standard (Sept 2020).


<object>

The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.


<embed>

The embed element provides an integration point for an external (typically non-HTML) application or interactive content.


Are there advantages/disadvantages to using one tag vs. the other?

The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object> over <embed> but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.

[...] you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.

Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.

Source: https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies#The_%3Cembed%3E_and_%3Cobject%3E_elements

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

App not setup: This app is still in development mode

When app is release some time that case https://developers.facebook.com/apps/{$appid}/alerts/ "Your app has been placed into development mode due to an invalid Privacy Policy." can change you app from release mode to development mode so check the Privacy Policy

MySQL "WITH" clause

MariaDB is now supporting WITH. MySQL for now is not. https://mariadb.com/kb/en/mariadb/with/

Pandas create empty DataFrame with only column names

You can create an empty DataFrame with either column names or an Index:

In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []

Or

In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Edit: Even after your amendment with the .to_html, I can't reproduce. This:

df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')

Produces:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You could also use it clean and simple (but wrong! because you should use format like Mark Byers said) by doing:

print 'This is my %s formatted with %d arguments' % ('string', 2)

Merge PDF files with PHP

This worked for me on Windows

  1. download PDFtk free from https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/
  2. drop folder (PDFtk) into the root of c:
  3. add the following to your php code where $file1 is the location and name of the first PDF file, $file2 is the location and name of the second and $newfile is the location and name of the destination file

    $file1 = ' c:\\\www\\\folder1\\\folder2\\\file1.pdf';  
    $file2 = ' c:\\\www\\\folder1\\\folder2\\\file2.pdf';  
    $file3 = ' c:\\\www\\\folder1\\\folder2\\\file3.pdf';   
    
    $command =  'cmd /c C:\\\pdftk\\\bin\\\pdftk.exe '.$file1.$file2.$newfile;
    $result = exec($command);
    

Display all dataframe columns in a Jupyter Python Notebook

I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:

import pandas as pd
pd.set_option('display.max_columns', <number of columns>)

You can do the same for the rows too:

pd.set_option('display.max_rows', <number of rows>)

This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html

How do I 'svn add' all unversioned files to SVN?

Since he specified Windows, where awk & sed aren't standard:

for /f "tokens=1*" %e in ('svn status^|findstr "^\?"') do svn add "%f"

or in a batch file:

for /f "tokens=1*" %%e in ('svn status^|findstr "^\?"') do svn add "%%f"

Best way to store time (hh:mm) in a database

Instead of minutes-past-midnight we store it as 24 hours clock, as an SMALLINT.

09:12 = 912 14:15 = 1415

when converting back to "human readable form" we just insert a colon ":" two characters from the right. Left-pad with zeros if you need to. Saves the mathematics each way, and uses a few fewer bytes (compared to varchar), plus enforces that the value is numeric (rather than alphanumeric)

Pretty goofy though ... there should have been a TIME datatype in MS SQL for many a year already IMHO ...

efficient way to implement paging

Trying to give you a brief answer to your doubt, if you execute the skip(n).take(m) methods on linq (with SQL 2005 / 2008 as database server) your query will be using the Select ROW_NUMBER() Over ... statement, with is somehow direct paging in the SQL engine.

Giving you an example, I have a db table called mtcity and I wrote the following query (work as well with linq to entities):

using (DataClasses1DataContext c = new DataClasses1DataContext())
{
    var query = (from MtCity2 c1 in c.MtCity2s
                select c1).Skip(3).Take(3);
    //Doing something with the query.
}

The resulting query will be:

SELECT [t1].[CodCity], 
    [t1].[CodCountry], 
    [t1].[CodRegion], 
    [t1].[Name],  
    [t1].[Code]
FROM (
    SELECT ROW_NUMBER() OVER (
        ORDER BY [t0].[CodCity], 
        [t0].[CodCountry], 
        [t0].[CodRegion], 
        [t0].[Name],
        [t0].[Code]) AS [ROW_NUMBER], 
        [t0].[CodCity], 
        [t0].[CodCountry], 
        [t0].[CodRegion], 
        [t0].[Name],
        [t0].[Code]
    FROM [dbo].[MtCity] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]

Which is a windowed data access (pretty cool, btw cuz will be returning data since the very begining and will access the table as long as the conditions are met). This will be very similar to:

With CityEntities As 
(
    Select ROW_NUMBER() Over (Order By CodCity) As Row,
        CodCity //here is only accessed by the Index as CodCity is the primary
    From dbo.mtcity
)
Select [t0].[CodCity], 
        [t0].[CodCountry], 
        [t0].[CodRegion], 
        [t0].[Name],
        [t0].[Code]
From CityEntities c
Inner Join dbo.MtCity t0 on c.CodCity = t0.CodCity
Where c.Row Between @p0 + 1 AND @p0 + @p1
Order By c.Row Asc

With the exception that, this second query will be executed faster than the linq result because it will be using exclusively the index to create the data access window; this means, if you need some filtering, the filtering should be (or must be) in the Entity listing (where the row is created) and some indexes should be created as well to keep up the good performance.

Now, whats better?

If you have pretty much solid workflow in your logic, implementing the proper SQL way will be complicated. In that case LINQ will be the solution.

If you can lower that part of the logic directly to SQL (in a stored procedure), it will be even better because you can implement the second query I showed you (using indexes) and allow SQL to generate and store the Execution Plan of the query (improving performance).