Programs & Examples On #Polygons

Polygons are multi-sided objects. This heading should be used when describing issues involving multiple polygons and how they relate to each other, for example, overlap detection.

rbind error: "names do not match previous names"

Use code as follows:

mylist <- lapply(pressure, function(i)read.xlsx(i,colNames = FALSE))#
mydata <- do.call('rbind',mylist)#

matplotlib savefig() plots different from show()

I have fixed this in my matplotlib source, but it's not a pretty fix. However, if you, like me, are very particular about how the graph looks, it's worth it.

The issue seems to be in the rendering backends; they each get the correct values for linewidth, font size, etc., but that comes out slightly larger when rendered as a PDF or PNG than when rendered with show().

I added a few lines to the source for PNG generation, in the file matplotlib/backends/backend_agg.py. You could make similar changes for each backend you use, or find a way to make a more clever change in a single location ;)

Added to my matplotlib/backends/backend_agg.py file:

    # The top of the file, added lines 42 - 44
42  # @warning: CHANGED FROM SOURCE to draw thinner lines
43  PATH_SCALAR = .8
44  FONT_SCALAR = .95

    # In the draw_markers method, added lines 90 - 91
89  def draw_markers(self, *kl, **kw):
90      # @warning: CHANGED FROM SOURCE to draw thinner lines
91      kl[0].set_linewidth(kl[0].get_linewidth()*PATH_SCALAR)
92      return self._renderer.draw_markers(*kl, **kw)

    # At the bottom of the draw_path method, added lines 131 - 132:
130 else:
131     # @warning: CHANGED FROM SOURCE to draw thinner lines
132     gc.set_linewidth(gc.get_linewidth()*PATH_SCALAR)
133     self._renderer.draw_path(gc, path, transform, rgbFace)

    # At the bottom of the _get_agg_font method, added line 242 and the *FONT_SCALAR
241     font.clear()
242     # @warning: CHANGED FROM SOURCE to draw thinner lines
243     size = prop.get_size_in_points()*FONT_SCALAR
244     font.set_size(size, self.dpi)

So that suits my needs for now, but, depending on what you're doing, you may want to implement similar changes in other methods. Or find a better way to do the same without so many line changes!

Update: After posting an issue to the matplotlib project at Github, I was able to track down the source of my problem: I had changed the figure.dpi setting in the matplotlibrc file. If that value is different than the default, my savefig() images come out different, even if I set the savefig dpi to be the same as the figure dpi. So, instead of changing the source as above, I just kept the figure.dpi setting as the default 80, and was able to generate images with savefig() that looked like images from show().

Leon, had you also changed that setting?

How to draw polygons on an HTML5 canvas?

For the people looking for regular polygons:

function regPolyPath(r,p,ctx){ //Radius, #points, context
  //Azurethi was here!
  ctx.moveTo(r,0);
  for(i=0; i<p+1; i++){
    ctx.rotate(2*Math.PI/p);
    ctx.lineTo(r,0);
  }
  ctx.rotate(-2*Math.PI/p);
}

Use:

//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.translate(60,60);    //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation);  //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx);   //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();

A simple algorithm for polygon intersection

I have no very simple solution, but here are the main steps for the real algorithm:

  1. Do a custom double linked list for the polygon vertices and edges. Using std::list won't do because you must swap next and previous pointers/offsets yourself for a special operation on the nodes. This is the only way to have simple code, and this will give good performance.
  2. Find the intersection points by comparing each pair of edges. Note that comparing each pair of edge will give O(N²) time, but improving the algorithm to O(N·logN) will be easy afterwards. For some pair of edges (say a?b and c?d), the intersection point is found by using the parameter (from 0 to 1) on edge a?b, which is given by t?=d0/(d0-d1), where d0 is (c-a)×(b-a) and d1 is (d-a)×(b-a). × is the 2D cross product such as p×q=p?·q?-p?·q?. After having found t?, finding the intersection point is using it as a linear interpolation parameter on segment a?b: P=a+t?(b-a)
  3. Split each edge adding vertices (and nodes in your linked list) where the segments intersect.
  4. Then you must cross the nodes at the intersection points. This is the operation for which you needed to do a custom double linked list. You must swap some pair of next pointers (and update the previous pointers accordingly).

Then you have the raw result of the polygon intersection resolving algorithm. Normally, you will want to select some region according to the winding number of each region. Search for polygon winding number for an explanation on this.

If you want to make a O(N·logN) algorithm out of this O(N²) one, you must do exactly the same thing except that you do it inside of a line sweep algorithm. Look for Bentley Ottman algorithm. The inner algorithm will be the same, with the only difference that you will have a reduced number of edges to compare, inside of the loop.

How to set background image in Java?

The answer will vary slightly depending on whether the application or applet is using AWT or Swing.

(Basically, classes that start with J such as JApplet and JFrame are Swing, and Applet and Frame are AWT.)

In either case, the basic steps would be:

  1. Draw or load an image into a Image object.
  2. Draw the background image in the painting event of the Component you want to draw the background in.

Step 1. Loading the image can be either by using the Toolkit class or by the ImageIO class.

The Toolkit.createImage method can be used to load an Image from a location specified in a String:

Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");

Similarly, ImageIO can be used:

Image img = ImageIO.read(new File("background.jpg");

Step 2. The painting method for the Component that should get the background will need to be overridden and paint the Image onto the component.

For AWT, the method to override is the paint method, and use the drawImage method of the Graphics object that is handed into the paint method:

public void paint(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

For Swing, the method to override is the paintComponent method of the JComponent, and draw the Image as with what was done in AWT.

public void paintComponent(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

Simple Component Example

Here's a Panel which loads an image file when instantiated, and draws that image on itself:

class BackgroundPanel extends Panel
{
    // The Image to store the background image in.
    Image img;
    public BackgroundPanel()
    {
        // Loads the background image and stores in img object.
        img = Toolkit.getDefaultToolkit().createImage("background.jpg");
    }

    public void paint(Graphics g)
    {
        // Draws the img to the BackgroundPanel.
        g.drawImage(img, 0, 0, null);
    }
}

For more information on painting:

Any tools to generate an XSD schema from an XML instance document?

the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.

edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that

Extract time from date String

let datestring = "2017-02-14 02:16:28"

let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full

formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

Your JRE was probably defined in run configuration. Follow these steps in Eclipse to change the build JRE.

1) Right click on the project and select Run As > Run Configurations

2) From Run Configurations window, select your project build configuration on the left panel. On the right, you will see various tabs: Main, JRE, Refresh, Source,...

3) Click on JRE tab, you should see something like this

enter image description here

4) By default, Work Default JRE (The JRE you select as default under Preferences->Java->Installed JREs) will be used. If you want to use another installed JRE, tick the Alternate JRE checkbox and select your preferred JRE from the dropdown.

Matplotlib scatter plot with different text at each data point

You may also use pyplot.text (see here).

def plot_embeddings(M_reduced, word2Ind, words):
    """ 
        Plot in a scatterplot the embeddings of the words specified in the list "words".
        Include a label next to each point.
    """
    for word in words:
        x, y = M_reduced[word2Ind[word]]
        plt.scatter(x, y, marker='x', color='red')
        plt.text(x+.03, y+.03, word, fontsize=9)
    plt.show()

M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])
word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}
words = ['test1', 'test2', 'test3', 'test4', 'test5']
plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)

enter image description here

Code line wrapping - how to handle long lines

In general, I break lines before operators, and indent the subsequent lines:

Map<long parameterization> longMap
    = new HashMap<ditto>();

String longString = "some long text"
                  + " some more long text";

To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.

Comparing two arrays & get the values which are not common

This should help, uses simple hash table.

$a1=@(1,2,3,4,5) $b1=@(1,2,3,4,5,6)


$hash= @{}

#storing elements of $a1 in hash
foreach ($i in $a1)
{$hash.Add($i, "present")}

#define blank array $c
$c = @()

#adding uncommon ones in second array to $c and removing common ones from hash
foreach($j in $b1)
{
if(!$hash.ContainsKey($j)){$c = $c+$j}
else {hash.Remove($j)}
}

#now hash is left with uncommon ones in first array, so add them to $c
foreach($k in $hash.keys)
{
$c = $c + $k
}

pypi UserWarning: Unknown distribution option: 'install_requires'

sudo apt-get install python-dev  # for python2.x installs
sudo apt-get install python3-dev  # for python3.x installs

It will install any missing headers. It solved my issue

Use of def, val, and var in scala

I'd start by the distinction that exists in Scala between def, val and var.

  • def - defines an immutable label for the right side content which is lazily evaluated - evaluate by name.

  • val - defines an immutable label for the right side content which is eagerly/immediately evaluated - evaluated by value.

  • var - defines a mutable variable, initially set to the evaluated right side content.

Example, def

scala> def something = 2 + 3 * 4 
something: Int
scala> something  // now it's evaluated, lazily upon usage
res30: Int = 14

Example, val

scala> val somethingelse = 2 + 3 * 5 // it's evaluated, eagerly upon definition
somethingelse: Int = 17

Example, var

scala> var aVariable = 2 * 3
aVariable: Int = 6

scala> aVariable = 5
aVariable: Int = 5

According to above, labels from def and val cannot be reassigned, and in case of any attempt an error like the below one will be raised:

scala> something = 5 * 6
<console>:8: error: value something_= is not a member of object $iw
       something = 5 * 6
       ^

When the class is defined like:

scala> class Person(val name: String, var age: Int)
defined class Person

and then instantiated with:

scala> def personA = new Person("Tim", 25)
personA: Person

an immutable label is created for that specific instance of Person (i.e. 'personA'). Whenever the mutable field 'age' needs to be modified, such attempt fails:

scala> personA.age = 44
personA.age: Int = 25

as expected, 'age' is part of a non-mutable label. The correct way to work on this consists in using a mutable variable, like in the following example:

scala> var personB = new Person("Matt", 36)
personB: Person = Person@59cd11fe

scala> personB.age = 44
personB.age: Int = 44    // value re-assigned, as expected

as clear, from the mutable variable reference (i.e. 'personB') it is possible to modify the class mutable field 'age'.

I would still stress the fact that everything comes from the above stated difference, that has to be clear in mind of any Scala programmer.

Running Tensorflow in Jupyter Notebook

You will need to add a "kernel" for it. Run your enviroment:

>activate tensorflow

Then add a kernel by command (after --name should follow your env. with tensorflow):

>python -m ipykernel install --user --name tensorflow --display-name "TensorFlow-GPU"

After that run jupyter notebook from your tensorflow env.

>jupyter notebook

And then you will see the following enter image description here

Click on it and then in the notebook import packages. It will work out for sure.

how to call an ASP.NET c# method using javascript

There are several options. You can use the WebMethod attribute, for your purpose.

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

How can I throw CHECKED exceptions from inside Java 8 streams?

I agree with the comments above, in using Stream.map you are limited to implementing Function which doesn't throw Exceptions.

You could however create your own FunctionalInterface that throws as below..

@FunctionalInterface
public interface UseInstance<T, X extends Throwable> {
  void accept(T instance) throws X;
}

then implement it using Lambdas or references as shown below.

import java.io.FileWriter;
import java.io.IOException;

//lambda expressions and the execute around method (EAM) pattern to
//manage resources

public class FileWriterEAM  {
  private final FileWriter writer;

  private FileWriterEAM(final String fileName) throws IOException {
    writer = new FileWriter(fileName);
  }
  private void close() throws IOException {
    System.out.println("close called automatically...");
    writer.close();
  }
  public void writeStuff(final String message) throws IOException {
    writer.write(message);
  }
  //...

  public static void use(final String fileName, final UseInstance<FileWriterEAM, IOException> block) throws IOException {

    final FileWriterEAM writerEAM = new FileWriterEAM(fileName);    
    try {
      block.accept(writerEAM);
    } finally {
      writerEAM.close();
    }
  }

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

    FileWriterEAM.use("eam.txt", writerEAM -> writerEAM.writeStuff("sweet"));

    FileWriterEAM.use("eam2.txt", writerEAM -> {
        writerEAM.writeStuff("how");
        writerEAM.writeStuff("sweet");      
      });

    FileWriterEAM.use("eam3.txt", FileWriterEAM::writeIt);     

  }


 void writeIt() throws IOException{
     this.writeStuff("How ");
     this.writeStuff("sweet ");
     this.writeStuff("it is");

 }

}

Turn a number into star rating display using jQuery and CSS

Try this jquery helper function/file

jquery.Rating.js

//ES5
$.fn.stars = function() {
    return $(this).each(function() {
        var rating = $(this).data("rating");
        var fullStar = new Array(Math.floor(rating + 1)).join('<i class="fas fa-star"></i>');
        var halfStar = ((rating%1) !== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
        var noStar = new Array(Math.floor($(this).data("numStars") + 1 - rating)).join('<i class="far fa-star"></i>');
        $(this).html(fullStar + halfStar + noStar);
    });
}

//ES6
$.fn.stars = function() {
    return $(this).each(function() {
        const rating = $(this).data("rating");
        const numStars = $(this).data("numStars");
        const fullStar = '<i class="fas fa-star"></i>'.repeat(Math.floor(rating));
        const halfStar = (rating%1!== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
        const noStar = '<i class="far fa-star"></i>'.repeat(Math.floor(numStars-rating));
        $(this).html(`${fullStar}${halfStar}${noStar}`);
    });
}

index.html

   <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Star Rating</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <script src="js/jquery.Rating.js"></script>
        <script>
            $(function(){
                $('.stars').stars();
            });
        </script>
    </head>
    <body>

        <span class="stars" data-rating="3.5" data-num-stars="5" ></span>

    </body>
    </html>

Screenshot

Is there a way to check for both `null` and `undefined`?

I always write it like this:

var foo:string;

if(!foo){
   foo="something";    
}

This will work fine and I think it's very readable.

Maven dependencies are failing with a 501 error

The following link got me out of the trouble,

https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required

You could make the changes either in your maven, apache-maven/conf/settings.xml. Or, if you are specifying in your pom.xml, make the change there.

Before,

<repository>
            <id>maven_central_repo</id>
            <url>http://repo.maven.apache.org/maven2</url>
</repository>

Now,

<repository>
            <id>maven_central_repo</id>
            <url>https://repo.maven.apache.org/maven2</url>
</repository>

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Why are only final variables accessible in anonymous class?

Java final variable inside an inner class[About]

inner class can use only

  1. reference from outer class
  2. final local variables from out of scope which are a reference type (e.g. Object...)
  3. value(primitive) (e.g. int...) type can be wrapped by a final reference type. IntelliJ IDEA can help you covert it to one element array

When a non static nested (inner class) is generated by compiler - a new class - <OuterClass>$<InnerClass>.class is created and bound parameters are passed into constructor[Local variable on stack]. It is similar to closure

final variable is a variable which can not be reassign. final reference variable still can be changed by modifying a state

If it was be possible it would be weird because as a programmer you could make like this

//Not possible 
private void foo() {

    MyClass myClass = new MyClass(); //Case 1. address 1
    int a = 5; //Case 2. a = 5

    Button button = new Button();

    //just as an example
    button.addClickHandler(new ClickHandler() {
        
        @Override
        public void onClick(ClickEvent event) {

            /*
            myClass.something(); //<- what is the address ?
            int b = a; //<- 5 or 10 ?

            //illusion that next changes are visible for Outer class
            myClass = new MyClass();
            a = 15;
            */
        }
    });

    myClass = new MyClass(); //Case 1. address 2
    int a = 10; //Case 2. a = 10
}

CSS background image alt attribute

You can achieve this by putting the alt tag in the div were your image will appear.

Example:

<div id="yourImage" alt="nameOfImage"></div>

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.

function indexToChar(i) {
  return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a', 
                                    // i=1 returns 'b', etc
}

CSS3 selector to find the 2nd div of the same class

Selectors can be combined:

.bar:nth-child(2)

means "thing that has class bar" that is also the 2nd child.

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

How can I generate random alphanumeric strings?

Horrible, I know, but I just couldn't help myself:


namespace ConsoleApplication2
{
    using System;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            Random adomRng = new Random();
            string rndString = string.Empty;
            char c;

            for (int i = 0; i < 8; i++)
            {
                while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
                rndString += c;
            }

            Console.WriteLine(rndString + Environment.NewLine);
        }
    }
}

Nullable types: better way to check for null or zero in c#

is there a better way?

Well, if you are really looking for a better way, you can probably add another layer of abstraction on top of Rate. Well here is something I just came up with using Nullable Design Pattern.

using System;
using System.Collections.Generic;

namespace NullObjectPatternTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var items = new List
                            {
                                new Item(RateFactory.Create(20)),
                                new Item(RateFactory.Create(null))
                            };

            PrintPricesForItems(items);
        }

        private static void PrintPricesForItems(IEnumerable items)
        {
            foreach (var item in items)
                Console.WriteLine("Item Price: {0:C}", item.GetPrice());
        }
    }

    public abstract class ItemBase
    {
        public abstract Rate Rate { get; }
        public int GetPrice()
        {
            // There is NO need to check if Rate == 0 or Rate == null
            return 1 * Rate.Value;
        }
    }

    public class Item : ItemBase
    {
        private readonly Rate _Rate;
        public override Rate Rate { get { return _Rate; } }
        public Item(Rate rate) { _Rate = rate; }
    }

    public sealed class RateFactory
    {
        public static Rate Create(int? rateValue)
        {
            if (!rateValue || rateValue == 0) 
                return new NullRate();
            return new Rate(rateValue);
        }
    }

    public class Rate
    {
        public int Value { get; set; }
        public virtual bool HasValue { get { return (Value > 0); } }
        public Rate(int value) { Value = value; }
    }

    public class NullRate : Rate
    {
        public override bool HasValue { get { return false; } }
        public NullRate() : base(0) { }
    }
}

Laravel Escaping All HTML in Blade Template

use this tag {!! description text !!}

Store output of subprocess.Popen call in a string

for Python 2.7+ the idiomatic answer is to use subprocess.check_output()

You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....

If args is just single command with no args of its own (or you have shell=True set), it can be a string. Otherwise it must be a list.

for example... to invoke the ls command, this is fine:

from subprocess import check_call
check_call('ls')

so is this:

from subprocess import check_call
check_call(['ls',])

however, if you want to pass some args to the shell command, you can't do this:

from subprocess import check_call
check_call('ls -al')

instead, you must pass it as a list:

from subprocess import check_call
check_call(['ls', '-al'])

the shlex.split() function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this:

from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))

How to extract custom header value in Web API message handler?

For ASP.NET you can get the header directly from parameter in controller method using this simple library/package. It provides a [FromHeader] attribute just like you have in ASP.NET Core :). For example:

    ...
    using RazHeaderAttribute.Attributes;

    [Route("api/{controller}")]
    public class RandomController : ApiController 
    {
        ...
        // GET api/random
        [HttpGet]
        public IEnumerable<string> Get([FromHeader("pages")] int page, [FromHeader] string rows)
        {
            // Print in the debug window to be sure our bound stuff are passed :)
            Debug.WriteLine($"Rows {rows}, Page {page}");
            ...
        }
    }

How can I assign an ID to a view programmatically?

You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

Credits to this answer.

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

Output in a table format in Java's System.out

Using j-text-utils you may print to console a table like: enter image description here

And it as simple as:

TextTable tt = new TextTable(columnNames, data);                                                         
tt.printTable();   

The API also allows sorting and row numbering ...

Convert String XML fragment to Document Node in Java

/**
*
* Convert a string to a Document Object
*
* @param xml The xml to convert
* @return A document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document string2Document(String xml) throws IOException, SAXException, ParserConfigurationException {

    if (xml == null)
    return null;

    return inputStream2Document(new ByteArrayInputStream(xml.getBytes()));

}


/**
* Convert an inputStream to a Document Object
* @param inputStream The inputstream to convert
* @return a Document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document inputStream2Document(InputStream inputStream) throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
    newInstance.setNamespaceAware(true);
    Document parse = newInstance.newDocumentBuilder().parse(inputStream);
    return parse;
}

How to export data as CSV format from SQL Server using sqlcmd?

You can run something like this:

sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable" 
       -o "MyData.csv" -h-1 -s"," -w 700
  • -h-1 removes column name headers from the result
  • -s"," sets the column seperator to ,
  • -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

How to read embedded resource text file

This is a class which you might find very convenient for reading embedded resource files from the current Assembly:

using System.IO;
using System.Linq;
using System.Text;

public static class EmbeddedResourceUtils
{
    public static string ReadFromResourceFile(string endingFileName)
    {
        var assembly = Assembly.GetExecutingAssembly();
        var manifestResourceNames = assembly.GetManifestResourceNames();

        foreach (var resourceName in manifestResourceNames)
        {
            var fileNameFromResourceName = _GetFileNameFromResourceName(resourceName);
            if (!fileNameFromResourceName.EndsWith(endingFileName))
            {
                continue;
            }

            using (var manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
            {
                if (manifestResourceStream == null)
                {
                    continue;
                }

                using (var streamReader = new StreamReader(manifestResourceStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }

        return null;
    }
    
    // https://stackoverflow.com/a/32176198/3764804
    private static string _GetFileNameFromResourceName(string resourceName)
    {
        var stringBuilder = new StringBuilder();
        var escapeDot = false;
        var haveExtension = false;

        for (var resourceNameIndex = resourceName.Length - 1;
            resourceNameIndex >= 0;
            resourceNameIndex--)
        {
            if (resourceName[resourceNameIndex] == '_')
            {
                escapeDot = true;
                continue;
            }

            if (resourceName[resourceNameIndex] == '.')
            {
                if (!escapeDot)
                {
                    if (haveExtension)
                    {
                        stringBuilder.Append('\\');
                        continue;
                    }

                    haveExtension = true;
                }
            }
            else
            {
                escapeDot = false;
            }

            stringBuilder.Append(resourceName[resourceNameIndex]);
        }

        var fileName = Path.GetDirectoryName(stringBuilder.ToString());
        return fileName == null ? null : new string(fileName.Reverse().ToArray());
    }
}

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

As in a similar question, use display: inline-block with a placeholder element to vertically center the span inside of a block element:

_x000D_
_x000D_
html, body, #container, #placeholder { height: 100%; }_x000D_
_x000D_
#content, #placeholder { display:inline-block; vertical-align: middle; }
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="container">_x000D_
      <span id="content">_x000D_
        Content_x000D_
      </span>_x000D_
      <span id="placeholder"></span>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block or display:table-cell with a display:table parent when vertically centering block elements.

References:

CSS Horizontal and Vertical Centering

Insert line after first match using sed

Try doing this using GNU sed:

sed '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' file

if you want to substitute in-place, use

sed -i '/CLIENTSCRIPT="foo"/a CLIENTSCRIPT2="hello"' file

Output

CLIENTSCRIPT="foo"
CLIENTSCRIPT2="hello"
CLIENTFILE="bar"

Doc

  • see sed doc and search \a (append)

RestClientException: Could not extract response. no suitable HttpMessageConverter found

While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.

What happens under the covers is that MappingJackson2HttpMessageConverter swallows any exceptions that occur in its canRead() method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.

For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead(), then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.

My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.

UPDATE FROM THE FUTURE

This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate bean with an instance of the following:

public class JsonRestTemplate extends RestTemplate {

    public JsonRestTemplate(
            ClientHttpRequestFactory clientHttpRequestFactory) {
        super(clientHttpRequestFactory);

        // Force a sensible JSON mapper.
        // Customize as needed for your project's definition of "sensible":
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule())
                .configure(
                        SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {

            public boolean canRead(java.lang.Class<?> clazz,
                    org.springframework.http.MediaType mediaType) {
                return true;
            }    
            public boolean canRead(java.lang.reflect.Type type,
                    java.lang.Class<?> contextClass,
                    org.springframework.http.MediaType mediaType) {
                return true;
            }
            protected boolean canRead(
                    org.springframework.http.MediaType mediaType) {
                return true;
            }
        };

        jsonMessageConverter.setObjectMapper(objectMapper);
        messageConverters.add(jsonMessageConverter);
        super.setMessageConverters(messageConverters);

    }
}

This customization makes the RestClient incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.

Java: Calling a super method which calls an overridden method

this always refers to currently executing object.

To further illustrate the point here is a simple sketch:

+----------------+
|  Subclass      |
|----------------|
|  @method1()    |
|  @method2()    |
|                |
| +------------+ |
| | Superclass | |
| |------------| |
| | method1()  | |
| | method2()  | |
| +------------+ |
+----------------+

If you have an instance of the outer box, a Subclass object, wherever you happen to venture inside the box, even into the Superclass 'area', it is still the instance of the outer box.

What's more, in this program there is only one object that gets created out of the three classes, so this can only ever refer to one thing and it is:

enter image description here

as shown in the Netbeans 'Heap Walker'.

Can I use jQuery to check whether at least one checkbox is checked?

if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }

Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space

run "export TEMPDIR=/someDir" where some dir is a valid directory other than /tmp. Run this on prompt before running your python command. In my case it is "pip install rasa[spacy]" which was earlier failing.

The export command allows you to temporarily use the specified dir as temp dir.

Javascript Drag and drop for touch devices

Thanks for the above codes! - I tried several options and this was the ticket. I had problems in that preventDefault was preventing scrolling on the ipad - I am now testing for draggable items and it works great so far.

if (event.target.id == 'draggable_item' ) {
    event.preventDefault();
}

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Anybody wondering how to do it in EF core:

      protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
                {
                    relationship.DeleteBehavior = DeleteBehavior.Restrict;
                }
           ..... rest of the code.....

async await return Task

You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:

public async Task<object> MethodName()
{
    return await Task.FromResult<object>(null);
}

Here is an example with no return value:

public async Task MethodName()
{
    await Task.CompletedTask;
}

Read these:

TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx

Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx

Understanding the Rails Authenticity Token

The authenticity token is used to prevent Cross-Site Request Forgery attacks (CSRF). To understand the authenticity token, you must first understand CSRF attacks.

CSRF

Suppose that you are the author of bank.com. You have a form on your site that is used to transfer money to a different account with a GET request:

enter image description here

A hacker could just send an HTTP request to the server saying GET /transfer?amount=$1000000&account-to=999999, right?

enter image description here

Wrong. The hackers attack won't work. The server will basically think?

Huh? Who is this guy trying to initiate a transfer. It's not the owner of the account, that's for sure.

How does the server know this? Because there's no session_id cookie authenticating the requester.

When you sign in with your username and password, the server sets a session_id cookie on your browser. That way, you don't have to authenticate each request with your username and password. When your browser sends the session_id cookie, the server knows:

Oh, that's John Doe. He signed in successfully 2.5 minutes ago. He's good to go.

A hacker might think:

Hmm. A normal HTTP request won't work, but if I could get my hand on that session_id cookie, I'd be golden.

The users browser has a bunch of cookies set for the bank.com domain. Every time the user makes a request to the bank.com domain, all of the cookies get sent along. Including the session_id cookie.

So if a hacker could get you to make the GET request that transfers money into his account, he'd be successful. How could he trick you into doing so? With Cross Site Request Forgery.

It's pretty simply, actually. The hacker could just get you to visit his website. On his website, he could have the following image tag:

<img src="http://bank.com/transfer?amount=$1000000&account-to=999999">

When the users browser comes across that image tag, it'll be making a GET request to that url. And since the request comes from his browser, it'll send with it all of the cookies associated with bank.com. If the user had recently signed in to bank.com... the session_id cookie will be set, and the server will think that the user meant to transfer $1,000,000 to account 999999!

enter image description here

Well, just don't visit dangerous sites and you'll be fine.

That isn't enough. What if someone posts that image to Facebook and it appears on your wall? What if it's injected into a site you're visiting with a XSS attack?

It's not so bad. Only GET requests are vulnerable.

Not true. A form that sends a POST request can be dynamically generated. Here's the example from the Rails Guide on Security:

<a href="http://www.harmless.com/" onclick="
  var f = document.createElement('form');
  f.style.display = 'none';
  this.parentNode.appendChild(f);
  f.method = 'POST';
  f.action = 'http://www.example.com/account/destroy';
  f.submit();
  return false;">To the harmless survey</a>

Authenticity Token

When your ApplicationController has this:

protect_from_forgery with: :exception

This:

<%= form_tag do %>
  Form contents
<% end %>

Is compiled into this:

<form accept-charset="UTF-8" action="/" method="post">
  <input name="utf8" type="hidden" value="&#x2713;" />
  <input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
  Form contents
</form>

In particular, the following is generated:

<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />

To protect against CSRF attacks, if Rails doesn't see the authenticity token sent along with a request, it won't consider the request safe.

How is an attacker supposed to know what this token is? A different value is generated randomly each time the form is generated:

enter image description here

A Cross Site Scripting (XSS) attack - that's how. But that's a different vulnerability for a different day.

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

How can I change the color of my prompt in zsh (different from normal text)?

To get a prompt with the color depending on the last command’s exit status, you could use this:

PS1='%(?.%F{green}.%F{red})%n@%m:%~%# %f'

Just add this line to your ~/.zshrc.

The documentation lists possible placeholders.

What is the easiest way to parse an INI File in C++?

Maybe a late answer..But, worth knowing options..If you need a cross-platform solution , definitely you can try GLIB,, its interesting.. (https://developer.gnome.org/glib/stable/glib-Key-value-file-parser.html)

Where to install Android SDK on Mac OS X?

I just have mine in MyUser/Documents/Development. I'm the only one that used my Mac, so I didn't need to worry about making it accessible system-wide.

React.js, wait for setState to finish before triggering a function?

setState takes new state and optional callback function which is called after the state has been updated.

this.setState(
  {newState: 'whatever'},
  () => {/*do something after the state has been updated*/}
)

How to list the properties of a JavaScript object?

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The system function requires const char *, and your expression is of the type std::string. You should write

string name = "john";
string system_str = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'";
system(system_str.c_str ());

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

How to add an existing folder with files to SVN?

Let's say I have code in the directory ~/local_dir/myNewApp, and I want to put it under 'https://svn.host/existing_path/myNewApp' (while being able to ignore some binaries, vendor libraries, etc.).

  1. Create an empty folder in the repository svn mkdir https://svn.host/existing_path/myNewApp
  2. Go to the parent directory of the project, cd ~/local_dir
  3. Check out the empty directory over your local folder. Don't be afraid - the files you have locally will not be deleted. svn co https://svn.host/existing_path/myNewApp. If your folder has a different name locally than in the repository, you must specify it as an additional argument.
  4. You can see that svn st will now show all your files as ?, which means that they are not currently under revision control
  5. Perform svn add on files you want to add to the repository, and add others to svn:ignore. You may find some useful options with svn help add, for example --parents or --depth empty, when you want selectively add only some files/folders.
  6. Commit with svn ci

HTML img scaling

Only set the width or height, and it will scale the other automatically. And yes you can use a percentage.

The first part can be done, but requires JavaScript, so might not work for all users.

How to hide form code from view code/inspect element browser?

Below JavaScript code worked for me to disable inspect element.

// Disable inspect element
$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});
$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I know it's late in the day but might help someone else!

body,html {
  height: 100%;
}

.contentarea {

 /* 
  * replace 160px with the sum of height of all other divs 
  * inc padding, margins etc 
  */
  min-height: calc(100% - 160px); 
}

How do I remove the file suffix and path portion from a path string in Bash?

Here's how to do it with the # and % operators in Bash.

$ x="/foo/fizzbuzz.bar"
$ y=${x%.bar}
$ echo ${y##*/}
fizzbuzz

${x%.bar} could also be ${x%.*} to remove everything after a dot or ${x%%.*} to remove everything after the first dot.

Example:

$ x="/foo/fizzbuzz.bar.quux"
$ y=${x%.*}
$ echo $y
/foo/fizzbuzz.bar
$ y=${x%%.*}
$ echo $y
/foo/fizzbuzz

Documentation can be found in the Bash manual. Look for ${parameter%word} and ${parameter%%word} trailing portion matching section.

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

Succeeded installing but could not start apache 2.4 on my windows 7 system

I was also facing the same issue, then i tried restarting my system after every change and it worked for me:

  1. Uninstall Apache2.4 in cmd prompt (run administrator) with the command: httpd -k uninstall.
  2. Restart the system.
  3. open cmd prompt (run administrator) with the command: httpd -k install.
  4. Then httpd -k install.

Hope you find useful.

Assign a synthesizable initial value to a reg in Verilog

When a chip gets power all of it's registers contain random values. It's not possible to have an an initial value. It will always be random.

This is why we have reset signals, to reset registers to a known value. The reset is controlled by something off chip, and we write our code to use it.

always @(posedge clk) begin
    if (reset == 1) begin // For an active high reset
        data_reg = 8'b10101011;
    end else begin
        data_reg = next_data_reg;
    end
end

Adding to a vector of pair

As many people suggested, you could use std::make_pair.

But I would like to point out another method of doing the same:

revenue.push_back({"string",map[i].second});

push_back() accepts a single parameter, so you could use "{}" to achieve this!

How can I return NULL from a generic method in C#?

Another alternative to 2 answers presented above. If you change your return type to object, you can return null, while at the same time cast the non-null return.

static object FindThing<T>(IList collection, int id)
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return (T) thing;
    }
    return null;  // allowed now
}

Iterate through object properties

Dominik's answer is perfect, I just prefer to do it that way, as it's cleaner to read:

for (var property in obj) {
    if (!obj.hasOwnProperty(property)) continue;

    // Do stuff...
}

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

In case anyone is still wondering...

I did it like this:

<a href="data:application/xml;charset=utf-8,your code here" download="filename.html">Save</a>

cant remember my source but it uses the following techniques\features:

  1. html5 download attribute
  2. data uri's

Found the reference:

http://paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/


EDIT: As you can gather from the comments this does NOT work in

  1. Internet Explorer (works in Edge v13 though)
  2. iOS Safari
  3. Opera Mini

http://caniuse.com/#feat=download

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Download the android SDK http://developer.android.com/sdk/installing/index.html

You only export the path of SDK folder.

export ANDROID_HOME="YOUR_PATH/sdk/"

How do I align views at the bottom of the screen?

Use android:layout_alignParentBottom="true" in your <RelativeLayout>.

This will definitely help.

cartesian product in pandas

This won't win a code golf competition, and borrows from the previous answers - but clearly shows how the key is added, and how the join works. This creates 2 new data frames from lists, then adds the key to do the cartesian product on.

My use case was that I needed a list of all store IDs on for each week in my list. So, I created a list of all the weeks I wanted to have, then a list of all the store IDs I wanted to map them against.

The merge I chose left, but would be semantically the same as inner in this setup. You can see this in the documentation on merging, which states it does a Cartesian product if key combination appears more than once in both tables - which is what we set up.

days = pd.DataFrame({'date':list_of_days})
stores = pd.DataFrame({'store_id':list_of_stores})
stores['key'] = 0
days['key'] = 0
days_and_stores = days.merge(stores, how='left', on = 'key')
days_and_stores.drop('key',1, inplace=True)

How to handle errors with boto3?

If you are calling the sign_up API (AWS Cognito) using Python3, you can use the following code.

def registerUser(userObj):
    ''' Registers the user to AWS Cognito.
    '''

    # Mobile number is not a mandatory field. 
    if(len(userObj['user_mob_no']) == 0):
        mobilenumber = ''
    else:
        mobilenumber = userObj['user_country_code']+userObj['user_mob_no']

    secretKey = bytes(settings.SOCIAL_AUTH_COGNITO_SECRET, 'latin-1')
    clientId = settings.SOCIAL_AUTH_COGNITO_KEY 

    digest = hmac.new(secretKey,
                msg=(userObj['user_name'] + clientId).encode('utf-8'),
                digestmod=hashlib.sha256
                ).digest()
    signature = base64.b64encode(digest).decode()

    client = boto3.client('cognito-idp', region_name='eu-west-1' ) 

    try:
        response = client.sign_up(
                    ClientId=clientId,
                    Username=userObj['user_name'],
                    Password=userObj['password1'],
                    SecretHash=signature,
                    UserAttributes=[
                        {
                            'Name': 'given_name',
                            'Value': userObj['given_name']
                        },
                        {
                            'Name': 'family_name',
                            'Value': userObj['family_name']
                        },
                        {
                            'Name': 'email',
                            'Value': userObj['user_email']
                        },
                        {
                            'Name': 'phone_number',
                            'Value': mobilenumber
                        }
                    ],
                    ValidationData=[
                        {
                            'Name': 'email',
                            'Value': userObj['user_email']
                        },
                    ]
                    ,
                    AnalyticsMetadata={
                        'AnalyticsEndpointId': 'string'
                    },
                    UserContextData={
                        'EncodedData': 'string'
                    }
                )
    except ClientError as error:
        return {"errorcode": error.response['Error']['Code'],
            "errormessage" : error.response['Error']['Message'] }
    except Exception as e:
        return {"errorcode": "Something went wrong. Try later or contact the admin" }
    return {"success": "User registered successfully. "}

error.response['Error']['Code'] will be InvalidPasswordException, UsernameExistsException etc. So in the main function or where you are calling the function, you can write the logic to provide a meaningful message to the user.

An example for the response (error.response):

{
  "Error": {
    "Message": "Password did not conform with policy: Password must have symbol characters",
    "Code": "InvalidPasswordException"
  },
  "ResponseMetadata": {
    "RequestId": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
    "HTTPStatusCode": 400,
    "HTTPHeaders": {
      "date": "Wed, 17 Jul 2019 09:38:32 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "124",
      "connection": "keep-alive",
      "x-amzn-requestid": "c8a591d5-8c51-4af9-8fad-b38b270c3ca2",
      "x-amzn-errortype": "InvalidPasswordException:",
      "x-amzn-errormessage": "Password did not conform with policy: Password must have symbol characters"
    },
    "RetryAttempts": 0
  }
}

For further reference : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.sign_up

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Here is my solution:

dependencies: Gmaps.js, jQuery

var Maps = function($) {
   var lost_addresses = [],
       geocode_count  = 0;

   var addMarker = function() { console.log('Marker Added!') };

   return {
     getGecodeFor: function(addresses) {
        var latlng;
        lost_addresses = [];
        for(i=0;i<addresses.length;i++) {
          GMaps.geocode({
            address: addresses[i],
            callback: function(response, status) {
              if(status == google.maps.GeocoderStatus.OK) {
                addMarker();
              } else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                lost_addresses.push(addresses[i]);
              }

               geocode_count++;
               // notify listeners when the geocode is done
               if(geocode_count == addresses.length) {
                 $.event.trigger({ type: 'done:geocoder' });
               }
            }
          });
        }
     },
     processLostAddresses: function() {
       if(lost_addresses.length > 0) {
         this.getGeocodeFor(lost_addresses);
       }
     }
   };
}(jQuery);

Maps.getGeocodeFor(address);

// listen to done:geocode event and process the lost addresses after 1.5s
$(document).on('done:geocode', function() {
  setTimeout(function() {
    Maps.processLostAddresses();
  }, 1500);
});

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

How to force a web browser NOT to cache images

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it).

Change this, and you've fixed your problem. I use timestamps, as with the solutions proposed above: Image-<timestamp>.jpg

Presumably, whatever problems you're avoiding by keeping the same filename for the image can be overcome, but you don't say what they are.

How do I get the opposite (negation) of a Boolean in Python?

Another way to achieve the same outcome, which I found useful for a pandas dataframe.

As suggested below by mousetail:

bool(1 - False)

bool(1 - True)

How to open a local disk file with JavaScript?

The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.

PostgreSQL delete with inner join

If you have more than one join you could use comma separated USING statements:

DELETE 
FROM 
      AAA AS a 
USING 
      BBB AS b,
      CCC AS c
WHERE 
      a.id = b.id 
  AND a.id = c.id
  AND a.uid = 12345 
  AND c.gid = 's434sd4'

Reference

Filter LogCat to get only the messages from My Application in Android?

If you are using Android Studio you can select the process from which you want to receive logcats. Here is the screenshot.

enter image description here

Getting the first index of an object

Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:

_.pairs(obj)[0]

Then the key would be available with a further [0] subscript, the value with [1]

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Assign JavaScript variable to Java Variable in JSP

I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.

How do I turn off autocommit for a MySQL client?

Instead of switching autocommit off manually at restore time you can already dump your MySQL data in a way that includes all necessary statements right into your SQL file.

The command line parameter for mysqldump is --no-autocommit. You might also consider to add --opt which sets a combination of other parameters to speed up restore operations.

Here is an example for a complete mysqldump command line as I use it, containing --no-autocommit and --opt:

mysqldump -hlocalhost -uMyUser -p'MyPassword' --no-autocommit --opt --default-character-set=utf8 --quote-names  MyDbName  >  dump.sql

For details of these parameters see the reference of mysqldump

List<T> or IList<T>

What if .NET 5.0 replaces System.Collections.Generic.List<T> to System.Collection.Generics.LinearList<T>. .NET always owns the name List<T> but they guarantee that IList<T> is a contract. So IMHO we (atleast I) are not supposed to use someone's name (though it is .NET in this case) and get into trouble later.

In case of using IList<T>, the caller is always guareented things to work, and the implementer is free to change the underlying collection to any alternative concrete implementation of IList

How to add a downloaded .box file to Vagrant?

First rename the Vagrantfile then

vagrant box add new-box name-of-the-box.box
vagrant init new-box
vagrant up

Just to check status

vagrant status

that's all

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

top nav bar blocking top content of the page

As seen on this example from Twitter, add this before the line that includes the responsive styles declarations:

<style> 
    body {
        padding-top: 60px;
    }
</style>

Like so:

<link href="Z/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
    body {
        padding-top: 60px;
    }
</style>
<link href="Z/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

How to get the list of all printers in computer

Get Network and Local Printer List in ASP.NET

This method uses the Windows Management Instrumentation or the WMI interface. It’s a technology used to get information about various systems (hardware) running on a Windows Operating System.

private void GetAllPrinterList()
        {
            ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
            objScope.Connect();

            SelectQuery selectQuery = new SelectQuery();
            selectQuery.QueryString = "Select * from win32_Printer";
            ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
            ManagementObjectCollection MOC = MOS.Get();
            foreach (ManagementObject mo in MOC)
            {
                lstPrinterList.Items.Add(mo["Name"].ToString());
            }
        }

Click here to download source and application demo

Demo of application which listed network and local printer

enter image description here

How to modify a text file?

Wrote a small class for doing this cleanly.

import tempfile

class FileModifierError(Exception):
    pass

class FileModifier(object):

    def __init__(self, fname):
        self.__write_dict = {}
        self.__filename = fname
        self.__tempfile = tempfile.TemporaryFile()
        with open(fname, 'rb') as fp:
            for line in fp:
                self.__tempfile.write(line)
        self.__tempfile.seek(0)

    def write(self, s, line_number = 'END'):
        if line_number != 'END' and not isinstance(line_number, (int, float)):
            raise FileModifierError("Line number %s is not a valid number" % line_number)
        try:
            self.__write_dict[line_number].append(s)
        except KeyError:
            self.__write_dict[line_number] = [s]

    def writeline(self, s, line_number = 'END'):
        self.write('%s\n' % s, line_number)

    def writelines(self, s, line_number = 'END'):
        for ln in s:
            self.writeline(s, line_number)

    def __popline(self, index, fp):
        try:
            ilines = self.__write_dict.pop(index)
            for line in ilines:
                fp.write(line)
        except KeyError:
            pass

    def close(self):
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        with open(self.__filename,'w') as fp:
            for index, line in enumerate(self.__tempfile.readlines()):
                self.__popline(index, fp)
                fp.write(line)
            for index in sorted(self.__write_dict):
                for line in self.__write_dict[index]:
                    fp.write(line)
        self.__tempfile.close()

Then you can use it this way:

with FileModifier(filename) as fp:
    fp.writeline("String 1", 0)
    fp.writeline("String 2", 20)
    fp.writeline("String 3")  # To write at the end of the file

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

How to increment a datetime by one day?

Here is another method to add days on date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Output:

Today: 25/06/2015 20:41:44

After a Days: 01/06/2015 20:41:44

How can I determine the direction of a jQuery scroll event?

I have seen many version of good answers here but it seems some folks are having cross browser issues so this is my fix.

I have used this successfully to detect direction in FF, IE and Chrome ... I haven't tested it in safari as I use windows typically.

$("html, body").bind({'mousewheel DOMMouseScroll onmousewheel touchmove scroll': 
    function(e) {
        if (e.target.id == 'el') return;
        e.preventDefault();
        e.stopPropagation();

        //Determine Direction
        if (e.originalEvent.wheelDelta && e.originalEvent.wheelDelta >= 0) {
            //Up
            alert("up");

        } else if (e.originalEvent.detail && e.originalEvent.detail <= 0) {
            //Up
            alert("up");

        } else {
            //Down
            alert("down");
        }
    }
});

Keep in mind I also use this to stop any scrolling so if you want scrolling to still occur you must remove the e.preventDefault(); e.stopPropagation();

Difference between Relative path and absolute path in javascript

Relative Paths

A relative path assumes that the file is on the current server. Using relative paths allows you to construct your site offline and fully test it before uploading it.

For example:

php/webct/itr/index.php

.

Absolute Paths

An absolute path refers to a file on the Internet using its full URL. Absolute paths tell the browser precisely where to go.

For example:

http://www.uvsc.edu/disted/php/webct/itr/index.php

Absolute paths are easier to use and understand. However, it is not good practice on your own website. For one thing, using relative paths allows you to construct your site offline and fully test it before uploading it. If you were to use absolute paths you would have to change your code before uploading it in order to get it to work. This would also be the case if you ever had to move your site or if you changed domain names.

Reference: http://openhighschoolcourses.org/mod/book/tool/print/index.php?id=12503

AutoComplete TextBox Control

This might not be the best way to do things, but should work:

 this.textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
 this.textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

private void textBox1_TextChanged(object sender, EventArgs e)
{
    TextBox t = sender as TextBox;
    if (t != null)
    {
        //say you want to do a search when user types 3 or more chars
        if (t.Text.Length >= 3)
        {
            //SuggestStrings will have the logic to return array of strings either from cache/db
            string[] arr = SuggestStrings(t.Text);

            AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
            collection.AddRange(arr);

            this.textBox1.AutoCompleteCustomSource = collection;
        }
    }
}

Disable dragging an image from an HTML page

Since my images were created using ajax, and therefore not available on windows.load.

$("#page").delegate('img', 'dragstart', function (event) { event.preventDefault(); });

This way I can control which section blocks the behavior, it only uses one event binding and it works for future ajax created images without having to do anything.

With jQuery new on binding:

$('#page').on('dragstart', 'img', function(event) { event.preventDefault(); }); (thanks @ialphan)

Remove duplicates from an array of objects in JavaScript

If you need an unique array based on multiple properties in the object you can do this with map and combining the properties of the object.

    var hash = array.map(function(element){
        var string = ''
        for (var key in element){
            string += element[key]
        }
        return string
    })
    array = array.filter(function(element, index){
        var string = ''
        for (var key in element){
            string += element[key]
        }
        return hash.indexOf(string) == index
    })

Simple (non-secure) hash function for JavaScript?

I didn't verify this myself, but you can look at this JavaScript implementation of Java's String.hashCode() method. Seems reasonably short.

With this prototype you can simply call .hashCode() on any string, e.g. "some string".hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

String.prototype.hashCode = function() {
    var hash = 0;
    if (this.length == 0) {
        return hash;
    }
    for (var i = 0; i < this.length; i++) {
        var char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You have configured the auth.php and used members table for authentication but there is no user_email field in the members table so, Laravel says

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))

Because, it tries to match the user_email in the members table and it's not there. According to your auth configuration, laravel is using members table for authentication not users table.

How to diff a commit with its parent?

Paul's solution above did what I was hoping it would.

$ git diff HEAD^1

Also, it's useful to add aliases like hobs mentioned, if you put the following in the [alias] section of your ~/.gitconfig file then you can use short-hand to view diff between head and previous.

[alias]
    diff-last = diff HEAD^1

Then running $ git diff-last will get you your result. Note that this will also include any changes you've not yet committed as well as the diff between commits. If you want to ignore changes you've not yet committed, then you can use diff to compare the HEAD with it's parent directly:

$ git diff HEAD^1 HEAD

Adding extra zeros in front of a number using jQuery?

I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:

function lpad(n, e, d) {
  var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
  if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
  return o; }

Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.

A server with the specified hostname could not be found

I received A server with the specified hostname could not be found.. I figured out my MacOS app had turned on App Sandboxing. The easiest way to avoid problem is to turn off Sandbox.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Can I access variables from another file?

This should work - define a global variable in firstfile and access it from secondfile:

<script src="/firstfile.js"></script>
<script src="/secondfile.js"></script>

firstfile.js:

var colors = {
   text:'#000000',
   background:'#aaaaaa',
   something_else:'blue'
};

secondfile.js:

do_something_with(colors.background);

Note that the order in which you load the script files is significant for some browsers (IE6 for sure, maybe others)

Ant error when trying to build file, can't find tools.jar?

Java ships in 2 versions: JRE & SDK (used to be called JDK)

The JRE in addition to not containing the compiler, also doesn't contain all of the libraries available in the JDK (tools.jar is one of them)

When you download Java at: http://java.sun.com/javase/downloads/index.jsp, make sure to select the JDK version and install it. If you have both a JDK & JRE, make sure that ANT is using the JDK, you can check JAVA_HOME (environment variable), and on the commandline if you do "javac -version" you should get a version description.

.NET Core vs Mono

This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:

  • APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
    different; type shape differs in key cases). These differences
    currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
    include more of the .NET Framework BCL APIs over time.
  • Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
    programming model. For example, Code Access Security (CAS) is not
    supported, while reflection is supported.

If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

Linq and Entity framework are included in .NET Core, so you are safe to take a shot.

What does DIM stand for in Visual Basic and BASIC?

It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.

DIM — (short for dimension) define the size of arrays

Ref: http://en.wikipedia.org/wiki/Dartmouth_BASIC

A part of the original BASIC compiler source code, where it would jump when finding a DIM command, in which you can clearly see the original intention for the keyword:

DIM    LDA XR01             BACK OFF OBJECT POINTER
       SUB N3
       STA RX01
       LDA L        2       GET VARIABLE TO BE DIMENSIONED
       STA 3
       LDA S        3
       CAB N36              CHECK FOR $ ARRAY
       BRU *+7              NOT $
       ...

Ref: http://dtss.dartmouth.edu/scans/BASIC/BASIC%20Compiler.pdf

Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.

How to return a html page from a restful controller in spring boot?

@Controller
public class HomeController {

    @RequestMapping(method = RequestMethod.GET, value = "/")
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login.html");
        return modelAndView;
    }
}

This will return the Login.html File. The Login.html should be inside the static Folder.

Note: thymeleaf dependency is not added

@RestController
public class HomeController {

    @RequestMapping(method = RequestMethod.GET, value = "/")
    public String welcome() {
        return "login";
    }
}

This will return the String login

Call a child class method from a parent class object

I had the same situation and I found a way around with a bit of engineering as follows - -

  1. You have to have your method in parent class without any parameter and use - -

    Class<? extends Person> cl = this.getClass(); // inside parent class
    
  2. Now, with 'cl' you can access all child class fields with their name and initialized values by using - -

    cl.getDeclaredFields(); cl.getField("myfield"); // and many more
    
  3. In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.

  4. Another thing you might need to use is Object obj = cl.newInstance();

Let me know if still you got stucked somewhere.

jQuery Set Selected Option Using Next

From version 1.6.1 on, it's advisable to use the method prop for boolean attributes/properties such as selected, readonly, enabled,...

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);

For more info, please refer to to http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

What is the maximum length of a Push Notification alert text?

Apple push will reject a string for a variety of reasons. I tested a variety of scenarios for push delivery, and this was my working fix (in python):

#  Apple rejects push payloads > 256 bytes (truncate msg to < 120 bytes to be safe)
if len(push_str) > 120:
    push_str = push_str[0:120-3] + '...'

# Apple push rejects all quotes, remove them
import re
push_str = re.sub("[\"']", '', push_str)

# Apple push needs to newlines escaped
import MySQLdb
push_str = MySQLdb.escape_string(push_str)

# send it
import APNSWrapper
wrapper = APNSWrapper.APNSNotificationWrapper(certificate=...)
message = APNSWrapper.APNSNotification()
message.token(...)
message.badge(1)
message.alert(push_str)
message.sound("default")
wrapper.append(message)
wrapper.notify()

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

Bash 4's brace expansion has a step feature:

for {0..10..2}; do
  ..
done

No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.

Filter dataframe rows if value in column is in a set list of values

isin() is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the str.contains method and regular expressions.

For example, if we want to return a DataFrame where all of the stock IDs which begin with '600' and then are followed by any three digits:

>>> rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')] # ^ means start of string
...   STK_ID   ...                                    # [0-9]{3} means any three digits
...  '600809'  ...                                    # $ means end of string
...  '600141'  ...
...  '600329'  ...
...      ...   ...

Suppose now we have a list of strings which we want the values in 'STK_ID' to end with, e.g.

endstrings = ['01$', '02$', '05$']

We can join these strings with the regex 'or' character | and pass the string to str.contains to filter the DataFrame:

>>> rpt[rpt['STK_ID'].str.contains('|'.join(endstrings)]
...   STK_ID   ...
...  '155905'  ...
...  '633101'  ...
...  '210302'  ...
...      ...   ...

Finally, contains can ignore case (by setting case=False), allowing you to be more general when specifying the strings you want to match.

For example,

str.contains('pandas', case=False)

would match PANDAS, PanDAs, paNdAs123, and so on.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

This issue happened to me when I created a new entity and an associated entity in a method marked as @Transactional, then performed a query before saving. Ex

@Transactional
public someService() {
    Entity someEntity = new Entity();
    AssocaiatedEntity associatedEntity = new AssocaitedEntity();
    someEntity.setAssociatedEntity(associatedEntity);
    associatedEntity.setEntity(someEntity);

    // Performing any query was causing hibernate to attempt to persist the new entity. It would then throw an exception
    someDao.getSomething();

    entityDao.create(someEntity);
}

To fix, I performed the query before creating the new entity.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

I had the same error. The cause was that I had created a table with wrong schema(it ought to be [dbo]). I did the following steps:

  1. I dropped all tables which does not have a prefix "dbo."

  2. I created and run this query:

CREATE TABLE dbo.Cars(IDCar int PRIMARY KEY NOT NULL,Name varchar(25) NOT NULL,    
CarDescription text NULL)
GO

Set Windows process (or user) memory limit

Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.

Otherwise it is possible to set it once for each process with the windows API

SetProcessWorkingSetSize Function

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

You will get like this error

error ss

Try the following steps

1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter) Then type this command as show in picture

netstat -aon | find ":8080" | find "LISTENING" cmd command

  1. Now open Task Manager (Press Windows key and type "Task Manager" and hit Enter) In that, go to Details Tab and under PID Column, search for the number you found in cmd

task manager

  1. Right Click on that program and select end process

What is fastest children() or find() in jQuery?

children() only looks at the immediate children of the node, while find() traverses the entire DOM below the node, so children() should be faster given equivalent implementations. However, find() uses native browser methods, while children() uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.

Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).

Python foreach equivalent

This worked for me:

def smallest_missing_positive_integer(A):
A.sort()
N = len(A)

now = A[0]
for i in range(1, N, 1):
  next = A[i]
  
  #check if there is no gap between 2 numbers and if positive
  # "now + 1" is the "gap"
  if (next > now + 1):
    if now + 1 > 0:
      return now + 1 #return the gap
  now = next
    
return max(1, A[N-1] + 1) #if there is no positive number returns 1, otherwise the end of A+1

How do I get console input in javascript?

You can try something like process.argv, that is if you are using node.js to run the program.
console.log(process.argv) => Would print an array containing

[                                                                                                                                                                                          
  '/usr/bin/node',                                                                                                                                                                         
  '/home/user/path/filename.js',                                                                                                                                            
  'your_input'                                                                                                                                                                                   
]

You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


Example:

var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two

console.log(somevariable);
console.log(somevariable2);

If you are building a command-line program then the npm package yargs would be really helpful.

How to make a class property?

As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.

I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title property with a setter. Here's what I wrote:

class TitleMeta(type):
    @property
    def title(self):
        return getattr(self, '_title', 'Default Title')

    @title.setter
    def title(self, title):
        self._title = title
        # Do whatever else you want when the title is set...

Now make the actual class you want as normal, except have it use the metaclass you created above.

# Python 2 style:
class ClassWithTitle(object):
    __metaclass__ = TitleMeta
    # The rest of your class definition...

# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
    # Your class definition...

It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.

How do I get the first element from an IEnumerable<T> in .net?

FirstOrDefault ?

Elem e = enumerable.FirstOrDefault();
//do something with e

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...

Update: The page states that the tight_layout() function is the easiest way to go, which attempts to automatically correct spacing.

Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()

How to apply !important using .css()?

The problem is caused by jQuery not understanding the !important attribute, and as such fails to apply the rule.

You might be able to work around that problem, and apply the rule by referring to it, via addClass():

.importantRule { width: 100px !important; }

$('#elem').addClass('importantRule');

Or by using attr():

$('#elem').attr('style', 'width: 100px !important');

The latter approach would unset any previously set in-line style rules, though. So use with care.

Of course, there's a good argument that @Nick Craver's method is easier/wiser.

The above, attr() approach modified slightly to preserve the original style string/properties, and modified as suggested by falko in a comment:

$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });

How to correctly iterate through getElementsByClassName

If you use the new querySelectorAll you can call forEach directly.

document.querySelectorAll('.edit').forEach(function(button) {
    // Now do something with my button
});

Per the comment below. nodeLists do not have a forEach function.

If using this with babel you can add Array.from and it will convert non node lists to a forEach array. Array.from does not work natively in browsers below and including IE 11.

Array.from(document.querySelectorAll('.edit')).forEach(function(button) {
    // Now do something with my button
});

At our meetup last night I discovered another way to handle node lists not having forEach

[...document.querySelectorAll('.edit')].forEach(function(button) {
    // Now do something with my button
});

Browser Support for [...]

Showing as Node List

Showing as Node List

Showing as Array

Showing as Array

How can I enable cURL for an installed Ubuntu LAMP stack?

Try:

sudo apt-get install php-curl

It worked on a fresh Ubuntu 16.04 (Xenial Xerus) LTS, with lamp-server and php7. I tried with php7-curl - it didn't work and also didn't work with php5-curl.

Android Studio - Failed to notify project evaluation listener error

The problem is probably you're using a Gradle version rather than 3. go to gradle/wrapper/gradle-wrapper.properties and change the last line to this:

distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

INFO: No Spring WebApplicationInitializer types detected on classpath

I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.

Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.

Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a

public class HttpGatewayInit implements WebApplicationInitializer { ... }

which implements empty inherited methods, and the whole application works fine!

...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.

working with negative numbers in python

Try this on your TA:

# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)

for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
    print numa, numb,
    accum = 0
    negate = False
    if numa < 0:
        negate = True
        numa = -numa
    while numa:
        if numa & 1:
            accum += numb
        numa >>= 1
        numb <<= 1
    if negate:
        accum = -accum
    print accum

output:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129

Slide a layout up from bottom of screen

Try this below code, Its very short and simple.

transalate_anim.xml

<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2013 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="4000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:repeatCount="infinite"
        android:toXDelta="0"
        android:toYDelta="-90%p" />

    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="4000"
        android:fromAlpha="0.0"
        android:repeatCount="infinite"
        android:toAlpha="1.0" />
</set>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.naveen.congratulations.MainActivity">


    <ImageView
        android:id="@+id/image_1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:srcCompat="@drawable/balloons" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView imageView1 = (ImageView) findViewById(R.id.image_1);
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startBottomToTopAnimation(imageView1);
            }
        });

    }

    private void startBottomToTopAnimation(View view) {
        view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate_anim));
    }
}

bottom_up_navigation of image

How can I link to a specific glibc version?

Setup 1: compile your own glibc without dedicated GCC and use it

Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.

This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.

But it is not reliable as it uses host C runtime objects such as crt1.o, crti.o, and crtn.o provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.

For a more reliable setup, see Setup 2 below.

Build glibc and install locally:

export glibc_install="$(pwd)/glibc/build/install"

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`

Setup 1: verify the build

test_glibc.c

#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>

atomic_int acnt;
int cnt;

int f(void* thr_data) {
    for(int n = 0; n < 1000; ++n) {
        ++cnt;
        ++acnt;
    }
    return 0;
}

int main(int argc, char **argv) {
    /* Basic library version check. */
    printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());

    /* Exercise thrd_create from -pthread,
     * which is not present in glibc 2.27 in Ubuntu 18.04.
     * https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
    thrd_t thr[10];
    for(int n = 0; n < 10; ++n)
        thrd_create(&thr[n], f, NULL);
    for(int n = 0; n < 10; ++n)
        thrd_join(thr[n], NULL);
    printf("The atomic counter is %u\n", acnt);
    printf("The non-atomic counter is %u\n", cnt);
}

Compile and run with test_glibc.sh:

#!/usr/bin/env bash
set -eux
gcc \
  -L "${glibc_install}/lib" \
  -I "${glibc_install}/include" \
  -Wl,--rpath="${glibc_install}/lib" \
  -Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
  -std=c11 \
  -o test_glibc.out \
  -v \
  test_glibc.c \
  -pthread \
;
ldd ./test_glibc.out
./test_glibc.out

The program outputs the expected:

gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674

Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot made it fail with:

cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install

so I removed it.

ldd output confirms that the ldd and libraries that we've just built are actually being used as expected:

+ ldd test_glibc.out
        linux-vdso.so.1 (0x00007ffe4bfd3000)
        libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
        libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
        /home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)

The gcc compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:

COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o

Setup 1: modify glibc

Now let's modify glibc with:

diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
    License along with the GNU C Library; if not, see
    <http://www.gnu.org/licenses/>.  */

+#include <stdio.h>
+
 #include "thrd_priv.h"

 int
 thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
 {
+  puts("hacked");
   _Static_assert (sizeof (thr) == sizeof (pthread_t),
                   "sizeof (thr) != sizeof (pthread_t)");

Then recompile and re-install glibc, and recompile and re-run our program:

cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh

and we see hacked printed a few times as expected.

This further confirms that we actually used the glibc that we compiled and not the host one.

Tested on Ubuntu 18.04.

Setup 2: crosstool-NG pristine setup

This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o, crti.o, and crtn.o.

In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.

The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.

crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.

Yes the GCC build system is so bad that we need a separate project for that.

This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.

Get crosstool-NG and configure it:

git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig

The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:

uname -a

which shows me:

4.15.0-34-generic

so in menuconfig I do:

  • Operating System
    • Version of linux

so I select:

4.14.71

which is the first equal or older version. It has to be older since the kernel is backwards compatible.

Now you can build with:

env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

and now wait for about thirty minutes to two hours for compilation.

Setup 2: optional configurations

The .config that we generated with ./ct-ng x86_64-unknown-linux-gnu has:

CT_GLIBC_V_2_27=y

To change that, in menuconfig do:

  • C-library
  • Version of glibc

save the .config, and continue with the build.

Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:

  • Paths and misc options
    • Try features marked as EXPERIMENTAL: set to true
  • C-library
    • Source of glibc
      • Custom location: say yes
      • Custom location
        • Custom source location: point to a directory containing your glibc source

where glibc was cloned as:

git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28

Setup 2: test it out

Once you have built he toolchain that you want, test it out with:

#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
  x86_64-unknown-linux-gnu-gcc \
  -Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
  -Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
  -v \
  -o test_glibc.out \
  test_glibc.c \
  -pthread \
;
ldd test_glibc.out
./test_glibc.out

Everything seems to work as in Setup 1, except that now the correct runtime objects were used:

COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o

Setup 2: failed efficient glibc recompilation attempt

It does not seem possible with crosstool-NG, as explained below.

If you just re-build;

env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`

then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.

If we do:

./ct-ng list-steps

it gives a nice overview of the build steps:

Available build steps, in order:
  - companion_tools_for_build
  - companion_libs_for_build
  - binutils_for_build
  - companion_tools_for_host
  - companion_libs_for_host
  - binutils_for_host
  - cc_core_pass_1
  - kernel_headers
  - libc_start_files
  - cc_core_pass_2
  - libc
  - cc_for_build
  - cc_for_host
  - libc_post_cc
  - companion_libs_for_target
  - binutils_for_target
  - debug
  - test_suite
  - finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.

therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files comes before cc_core_pass_2, which is likely the most expensive step together with cc_core_pass_1.

In order to build just one step, you must first set the "Save intermediate steps" in .config option for the intial build:

  • Paths and misc options
    • Debug crosstool-NG
      • Save intermediate steps

and then you can try:

env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`

but unfortunately, the + required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536

Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).

and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.

Furthermore, starting from the libc step didn't seem to copy over the source again from Custom source location, further making this method unusable.

Bonus: stdlibc++

A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?

What are the differences between C, C# and C++ in terms of real-world applications?

C is the bare-bones, simple, clean language that makes you do everything yourself. It doesn't hold your hand, it doesn't stop you from shooting yourself in the foot. But it has everything you need to do what you want.

C++ is C with classes added, and then a whole bunch of other things, and then some more stuff. It doesn't hold your hand, but it'll let you hold your own hand, with add-on GC, or RAII and smart-pointers. If there's something you want to accomplish, chances are there's a way to abuse the template system to give you a relatively easy syntax for it. (moreso with C++0x). This complexity also gives you the power to accidentally create a dozen instances of yourself and shoot them all in the foot.

C# is Microsoft's stab at improving on C++ and Java. Tons of syntactical features, but no where near the complexity of C++. It runs in a full managed environment, so memory management is done for you. It does let you "get dirty" and use unsafe code if you need to, but it's not the default, and you have to do some work to shoot yourself.

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Environment Specific application.properties file in Spring Boot application

Spring Boot already has support for profile based properties.

Simply add an application-[profile].properties file and specify the profiles to use using the spring.profiles.active property.

-Dspring.profiles.active=local

This will load the application.properties and the application-local.properties with the latter overriding properties from the first.

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

Difference Between Select and SelectMany

I understand SelectMany to work like a join shortcut.

So you can:

var orders = customers
             .Where(c => c.CustomerName == "Acme")
             .SelectMany(c => c.Orders);

PHP move_uploaded_file() error?

Edit the code to be as follows:

// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );

if( $moved ) {
  echo "Successfully uploaded";         
} else {
  echo "Not uploaded because of error #".$_FILES["file"]["error"];
}

It will give you one of the following error code values 1 to 8:

UPLOAD_ERR_INI_SIZE = Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE = Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL = Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE = Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR = Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE = Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION = Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

What is the => assignment in C# in a property signature

This is a new feature of C# 6 called an expression bodied member that allows you to define a getter only property using a lambda like function.

While it is considered syntactic sugar for the following, they may not produce identical IL:

public int MaxHealth
{
    get
    {
        return Memory[Address].IsValid
               ?   Memory[Address].Read<int>(Offs.Life.MaxHp)
               :   0;
    }
}

It turns out that if you compile both versions of the above and compare the IL generated for each you'll see that they are NEARLY the same.

Here is the IL for the classic version in this answer when defined in a class named TestClass:

.property instance int32 MaxHealth()
{
    .get instance int32 TestClass::get_MaxHealth()
}

.method public hidebysig specialname 
    instance int32 get_MaxHealth () cil managed 
{
    // Method begins at RVA 0x2458
    // Code size 71 (0x47)
    .maxstack 2
    .locals init (
        [0] int32
    )

    IL_0000: nop
    IL_0001: ldarg.0
    IL_0002: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0007: ldarg.0
    IL_0008: ldfld int64 TestClass::Address
    IL_000d: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_0012: ldfld bool MemoryAddress::IsValid
    IL_0017: brtrue.s IL_001c

    IL_0019: ldc.i4.0
    IL_001a: br.s IL_0042

    IL_001c: ldarg.0
    IL_001d: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0022: ldarg.0
    IL_0023: ldfld int64 TestClass::Address
    IL_0028: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_002d: ldarg.0
    IL_002e: ldfld class Offs TestClass::Offs
    IL_0033: ldfld class Life Offs::Life
    IL_0038: ldfld int64 Life::MaxHp
    IL_003d: callvirt instance !!0 MemoryAddress::Read<int32>(int64)

    IL_0042: stloc.0
    IL_0043: br.s IL_0045

    IL_0045: ldloc.0
    IL_0046: ret
} // end of method TestClass::get_MaxHealth

And here is the IL for the expression bodied member version when defined in a class named TestClass:

.property instance int32 MaxHealth()
{
    .get instance int32 TestClass::get_MaxHealth()
}

.method public hidebysig specialname 
    instance int32 get_MaxHealth () cil managed 
{
    // Method begins at RVA 0x2458
    // Code size 66 (0x42)
    .maxstack 2

    IL_0000: ldarg.0
    IL_0001: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0006: ldarg.0
    IL_0007: ldfld int64 TestClass::Address
    IL_000c: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_0011: ldfld bool MemoryAddress::IsValid
    IL_0016: brtrue.s IL_001b

    IL_0018: ldc.i4.0
    IL_0019: br.s IL_0041

    IL_001b: ldarg.0
    IL_001c: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0021: ldarg.0
    IL_0022: ldfld int64 TestClass::Address
    IL_0027: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_002c: ldarg.0
    IL_002d: ldfld class Offs TestClass::Offs
    IL_0032: ldfld class Life Offs::Life
    IL_0037: ldfld int64 Life::MaxHp
    IL_003c: callvirt instance !!0 MemoryAddress::Read<int32>(int64)

    IL_0041: ret
} // end of method TestClass::get_MaxHealth

See https://msdn.microsoft.com/en-us/magazine/dn802602.aspx for more information on this and other new features in C# 6.

See this post Difference between Property and Field in C# 3.0+ on the difference between a field and a property getter in C#.

Update:

Note that expression-bodied members were expanded to include properties, constructors, finalizers and indexers in C# 7.0.

Escape text for HTML

If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System

var encoded = WebUtility.HtmlEncode(unencoded);

This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

Error: Unable to run mksdcard SDK tool

This is what worked for me

When I tried the Accepted ans my Android Studio hangs on start-up

This is the link

http://tools.android.com/tech-docs/linux-32-bit-libraries

and This is the Command

$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1

Possible reason for NGINX 499 error codes

One of the reasons for this behaviour could be you are using http for uwsgi instead of socket. Use the below command if you are using uwsgi directly.

uwsgi --socket :8080 --module app-name.wsgi

Same command in .ini file is

chdir = /path/to/app/folder
socket = :8080
module = app-name.wsgi

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

Getting values from query string in an url using AngularJS $location

If you just need to look at the query string as text, you can use: $window.location.search

Getting java.net.SocketTimeoutException: Connection timed out in android

If you are testing the server in localhost your Android device must be connected to the same local network. Then the Server URL used by your APP must include your computer IP Address and not the "localhost" mask.

How to get length of a list of lists in python

You can do it with reduce:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [], [1, 2]]
print(reduce(lambda count, l: count + len(l), a, 0))
# result is 11

AngularJS : ng-click not working

It just happend to me. I solved the problem by tracing backward from the point ng-click is coded. Found out that an extra

</div> 

was placed in the html to prematurely close the div block that contains the ng-click.

Removed the extra

</div> 

then everything is working fine.

Use StringFormat to add a string to a WPF XAML binding

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

How do I format a Microsoft JSON date?

In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:

(function () {
    var DATE_START = "/Date(";
    var DATE_START_LENGTH = DATE_START.length;

    function isDateString(x) {
        return typeof x === "string" && x.startsWith(DATE_START);
    }

    function deserializeDateString(dateString) {
        var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
        var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
        return utcDate;
    }

    function convertJSONDates(key, value) {
      if (isDateString(value)) {
        return deserializeDateString(value);
      }
      return value;
    }

    window.jQuery.ajaxSetup({
      converters: {
        "text json": function(data) {
          return window.JSON.parse(data, convertJSONDates);
        }
      }
    });
}());

I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date object that has the proper ticks value to reflect this. That is, calling getUTCHours(), etc. on the date will return the same value as it did on the server, and calling getHours() will return the value in the user's local timezone as determined by their browser.

This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.

Use jQuery to change an HTML tag?

Here's an extension that will do it all, on as many elements in as many ways...

Example usage:

keep existing class and attributes:

$('div#change').replaceTag('<span>', true);

or

Discard existing class and attributes:

$('div#change').replaceTag('<span class=newclass>', false);

or even

replace all divs with spans, copy classes and attributes, add extra class name

$('div').replaceTag($('<span>').addClass('wasDiv'), true);

Plugin Source:

$.extend({
    replaceTag: function (currentElem, newTagObj, keepProps) {
        var $currentElem = $(currentElem);
        var i, $newTag = $(newTagObj).clone();
        if (keepProps) {//{{{
            newTag = $newTag[0];
            newTag.className = currentElem.className;
            $.extend(newTag.classList, currentElem.classList);
            $.extend(newTag.attributes, currentElem.attributes);
        }//}}}
        $currentElem.wrapAll($newTag);
        $currentElem.contents().unwrap();
        // return node; (Error spotted by Frank van Luijn)
        return this; // Suggested by ColeLawrence
    }
});

$.fn.extend({
    replaceTag: function (newTagObj, keepProps) {
        // "return" suggested by ColeLawrence
        return this.each(function() {
            jQuery.replaceTag(this, newTagObj, keepProps);
        });
    }
});

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

What is the difference between an int and an Integer in Java and C#?

This has already been answered for Java, here's the C# answer:

"Integer" is not a valid type name in C# and "int" is just an alias for System.Int32. Also, unlike in Java (or C++) there aren't any special primitive types in C#, every instance of a type in C# (including int) is an object. Here's some demonstrative code:

void DoStuff()
{
    System.Console.WriteLine( SomeMethod((int)5) );
    System.Console.WriteLine( GetTypeName<int>() );
}

string SomeMethod(object someParameter)
{
    return string.Format("Some text {0}", someParameter.ToString());
}

string GetTypeName<T>()
{
    return (typeof (T)).FullName;
}

Best way to determine user's locale within browser

This article suggests the following properties of the browser's navigator object:

  • navigator.language (Netscape - Browser Localization)
  • navigator.browserLanguage (IE-Specific - Browser Localized Language)
  • navigator.systemLanguage (IE-Specific - Windows OS - Localized Language)
  • navigator.userLanguage

Roll these into a javascript function and you should be able to guess the right language, in most circumstances. Be sure to degrade gracefully, so have a div containing your language choice links, so that if there is no javascript or the method doesn't work, the user can still decide. If it does work, just hide the div.

The only problem with doing this on the client side is that either you serve up all the languages to the client, or you have to wait until the script has run and detected the language before requesting the right version. Perhaps serving up the most popular language version as a default would irritate the fewest people.

Edit: I'd second Ivan's cookie suggestion, but make sure the user can always change the language later; not everyone prefers the language their browser defaults to.

Git Diff with Beyond Compare

If you are running windows 7 (professional) and Git for Windows (v 2.15 or above), you can simply run below command to find out what are different diff tools supported by your Git for Windows

git difftool --tool-help

You will see output similar to this

git difftool --tool=' may be set to one of the following:
vimdiff vimdiff2 vimdiff3

it means that your git does not support(can not find) beyond compare as difftool right now.

In order for Git to find beyond compare as valid difftool, you should have Beyond Compare installation directory in your system path environment variable. You can check this by running bcompare from shell(cmd, git bash or powershell. I am using Git Bash). If Beyond Compare does not launch, add its installation directory (in my case, C:\Program Files\Beyond Compare 4) to your system path variable. After this, restart your shell. Git will show Beyond Compare as possible difftool option. You can use any of below commands to launch beyond compare as difftool (for example, to compare any local file with some other branch)

git difftool -t bc branchnametocomparewith -- path-to-file
or 
git difftool --tool=bc branchnametocomparewith -- path-to-file

You can configure beyond compare as default difftool using below commands

   git config --global diff.tool bc

p.s. keep in mind that bc in above command can be bc3 or bc based upon what Git was able to find from your path system variable.

How to view file diff in git before commit

Another technique to consider if you want to compare a file to the last commit which is more pedantic:

git diff master myfile.txt

The advantage with this technique is you can also compare to the penultimate commit with:

git diff master^ myfile.txt

and the one before that:

git diff master^^ myfile.txt

Also you can substitute '~' for the caret '^' character and 'you branch name' for 'master' if you are not on the master branch.

Python pip install fails: invalid command egg_info

I also meet a similar error message "Command 'python setup.py egg_info' failed with error code 1" when I want to install cairosvg with command pip install cairosvg in a virtual environment.

Then I have tried both pip install --upgrade pip and pip install --upgrade setuptools before running pip3 install cairosvg, but I still get this error.

I can get rid of this error with sudo in front of the installation command : sudo pip install cairosvg. But note that the command with sudo will install the package for the system python rather than the virtual environment.

So, I further check the error message and find that I get the error while installing the cairocffi. Then I install a certain version of cairocffi (refer to this answer) before install cairosvg. That is how I solve my problem.

How to find indices of all occurrences of one string in another in JavaScript?

I am a bit late to the party (by almost 10 years, 2 months), but one way for future coders is to do it using while loop and indexOf()

let haystack = "I learned to play the Ukulele in Lebanon.";
let needle = "le";
let pos = 0; // Position Ref
let result = []; // Final output of all index's.
let hayStackLower = haystack.toLowerCase();

// Loop to check all occurrences 
while (hayStackLower.indexOf(needle, pos) != -1) {
  result.push(hayStackLower.indexOf(needle , pos));
  pos = hayStackLower.indexOf(needle , pos) + 1;
}

console.log("Final ", result); // Returns all indexes or empty array if not found

Pass Javascript variable to PHP via ajax

To test if the POST variable has an element called 'userID' you would be better off using array_key_exists .. which actually tests for the existence of the array key not whether its value has been set .. a subtle and probably only semantic difference, but it does improve readability.

and right now your $uid is being set to a boolean value depending whether $__POST['userID'] is set or not ... If I recall from memory you might want to try ...

$uid = (array_key_exists('userID', $_POST)?$_POST['userID']:'guest';

Then you can use an identifiable 'guest' user and render your code that much more readable :)

Another point re isset() even though it is unlikely to apply in this scenario, it's worth remembering if you don't want to get caught out later ... an array element can be legitimately set to NULL ... i.e. it can exist, but be as yet unpopulated, and this could be a valid, acceptable, and testable condition. but :

a = array('one'=>1, 'two'=>null, 'three'=>3);
isset(a['one']) == true
isset(a['two']) == false

array_key_exists(a['one']) == true
array_key_exists(a['two']) == true

Bw sure you know which function you want to use for which purpose.

java: use StringBuilder to insert at the beginning

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.

public class Test {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        doRecursive(sb, 100, 0);
        System.out.println(sb.toString());
    }

    public static void doRecursive(StringBuilder sb, int limit, int index) {
        if (index < limit) {
            doRecursive(sb, limit, index + 1);
            sb.append(Integer.toString(index));
        }
    }
}

Django, creating a custom 500/404 error page

As one single line (for 404 generic page):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

In this class above @Repository just placed one more annotation @Transactional it will work. If it works reply back(Y/N):

@Repository
@Transactional
public class StudentDAOImpl implements StudentDAO

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

How to specify table's height such that a vertical scroll bar appears?

You need to wrap the table inside another element and set the height of that element. Example with inline css:

<div style="height: 500px; overflow: auto;">
 <table>
 </table>
</div>

How to iterate (keys, values) in JavaScript?

You can do something like this :

dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);

for(var i = 0; i < keys.length;i++){
   //keys[i] for key
   //dictionary[keys[i]] for the value
}

How to convert ActiveRecord results into an array of hashes

May be?

result.map(&:attributes)

If you need symbols keys:

result.map { |r| r.attributes.symbolize_keys }

How do you use global variables or constant values in Ruby?

One of the reasons why the global variable needs a prefix (called a "sigil") is because in Ruby, unlike in C, you don't have to declare your variables before assigning to them. The sigil is used as a way to be explicit about the scope of the variable.

Without a specific prefix for globals, given a statement pointNew = offset + point inside your draw method then offset refers to a local variable inside the method (and results in a NameError in this case). The same for @ used to refer to instance variables and @@ for class variables.

In other languages that use explicit declarations such as C, Java etc. the placement of the declaration is used to control the scope.

What does a bitwise shift (left or right) do and what is it used for?

Here is an applet where you can exercise some bit-operations, including shifting.

You have a collection of bits, and you move some of them beyond their bounds:

1111 1110 << 2
1111 1000

It is filled from the right with fresh zeros. :)

0001 1111 >> 3
0000 0011

Filled from the left. A special case is the leading 1. It often indicates a negative value - depending on the language and datatype. So often it is wanted, that if you shift right, the first bit stays as it is.

1100 1100 >> 1
1110 0110

And it is conserved over multiple shifts:

1100 1100 >> 2
1111 0011

If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C as far as I know, and maybe more) a triple-sign-operator:

1100 1100 >>> 1
0110 0110

There isn't any equivalent in the other direction, because it doesn't make any sense - maybe in your very special context, but not in general.

Mathematically, a left-shift is a *=2, 2 left-shifts is a *=4 and so on. A right-shift is a /= 2 and so on.

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

No need for array. Just use something like this:

Sub ARRAYER()

    Dim Rng As Range
    Dim Number_of_Sims As Long
    Dim i As Long
    Number_of_Sims = 10

    Set Rng = Range("C4:G4")
    For i = 1 To Number_of_Sims
       Rng.Offset(i, 0).Value = Rng.Value
       Worksheets("Sheetname").Calculate   'replacing Sheetname with name of your sheet
    Next

End Sub

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

I had a similar problem quite recently. In my case:

  1. I downloaded an artifact from some less popular Maven repo

  2. This repo dissappeared over this year

  3. Now builds fail, even if I have this artifact and its pom.xml in my local repo

Workaround:

delete _remote.repositories file in your local repo, where this artifact resides. Now the project builds.

@viewChild not working - cannot read property nativeElement of undefined

Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example: <div *ngIf="canShow"> <p #target>Targeted Element</p></div>

In this code, if canShow is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.

One of the solutions is to use a display: hidden on the element instead of the *ngIf so the element gets rendered but is hidden until your condition is fulfilled.

Read More over at Github

How can I see the request headers made by curl when sending a request to the server?

Here is my http client in php to make post queries with cookies included:

function http_login_client($url, $params = "", $cookies_send = "" ){

    // Vars
    $cookies = array();
    $headers = getallheaders();

    // Perform a http post request to $ur1 using $params
    $ch = curl_init($url);
    $options = array(   CURLOPT_POST => 1,
                        CURLINFO_HEADER_OUT => true,
                        CURLOPT_POSTFIELDS => $params,
                        CURLOPT_RETURNTRANSFER => 1,
                        CURLOPT_HEADER => 1,
                        CURLOPT_COOKIE => $cookies_send,
                        CURLOPT_USERAGENT => $headers['User-Agent']
                    );

    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);

/// DEBUG info echo $response; var_dump (curl_getinfo($ch)); ///

    // Parse response and read cookies
    preg_match_all('/^Set-Cookie: (.*?)=(.*?);/m', $response, $matches);

    // Build an array with cookies
    foreach( $matches[1] as $index => $cookie )
        $cookies[$cookie] = $matches[2][$index];

    return $cookies;
} // end http_login_client

How to prevent ENTER keypress to submit a web form?

Preventing "ENTER" to submit form may inconvenience some of your users. So it would be better if you follow the procedure below:

Write the 'onSubmit' event in your form tag:

<form name="formname" id="formId" onSubmit="return testSubmit()" ...>
 ....
 ....
 ....
</form>

write Javascript function as follows:

function testSubmit(){
  if(jQuery("#formId").valid())
      {
        return true;
      }
       return false;

     } 

     (OR)

What ever the reason, if you want to prevent the form submission on pressing Enter key, you can write the following function in javascript:

    $(document).ready(function() {
          $(window).keydown(function(event){
          if(event.keyCode == 13) {
               event.preventDefault();
               return false;
              }
           });
         });

thanks.

How to insert current datetime in postgresql insert query

You can of course format the result of current_timestamp(). Please have a look at the various formatting functions in the official documentation.

Android: install .apk programmatically

For ICS I´ve implemented your code and made a class that extends AsyncTask. I hope you appreciate it! Thanks for your code and solution.

public class UpdateApp extends AsyncTask<String,Void,Void>{
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
        return null;
    }
}   

To use it, in your main activity call by this way:

atualizaApp = new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://serverurl/appfile.apk");

Isn't the size of character in Java 2 bytes?

The constructor String(byte[] bytes) takes the bytes from the buffer and encodes them to characters.

It uses the platform default charset to encode bytes to characters. If you know, your file contains text, that is encoded in a different charset, you can use the String(byte[] bytes, String charsetName) to use the correct encoding (from bytes to characters).

Determine if a String is an Integer in Java

public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}

Generate preview image from Video file?

Two ways come to mind:

  • Using a command-line tool like the popular ffmpeg, however you will almost always need an own server (or a very nice server administrator / hosting company) to get that

  • Using the "screenshoot" plugin for the LongTail Video player that allows the creation of manual screenshots that are then sent to a server-side script.

Do I need to compile the header files in a C program?

Okay, let's understand the difference between active and passive code.

The active code is the implementation of functions, procedures, methods, i.e. the pieces of code that should be compiled to executable machine code. We store it in .c files and sure we need to compile it.

The passive code is not being execute itself, but it needed to explain the different modules how to communicate with each other. Usually, .h files contains only prototypes (function headers), structures.

An exception are macros, that formally can contain an active pieces, but you should understand that they are using at the very early stage of building (preprocessing) with simple substitution. At the compile time macros already are substituted to your .c file.

Another exception are C++ templates, that should be implemented in .h files. But here is the story similar to macros: they are substituted on the early stage (instantiation) and formally, each other instantiation is another type.

In conclusion, I think, if the modules formed properly, we should never compile the header files.

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

MySQL: selecting rows where a column is null

Had the same issue where query:

SELECT * FROM 'column' WHERE 'column' IS NULL; 

returned no values. Seems to be an issue with MyISAM and the same query on the data in InnoDB returned expected results.

Went with:

SELECT * FROM 'column' WHERE 'column' = ' '; 

Returned all expected results.

How to host google web fonts on my own server?

Please keep in mind that my answer has aged a lot.

There are other more technically sophisticated answers below, e.g.:

so don't let the fact that this is the currently accepted answer give you the impression that this is still the best one.


You can also now also download google's entire font set via on github at their google/font repository. They also provide a ~420MB zip snapshot of their fonts.


You first download your font selection as a zipped package, providing you with a bunch of true type fonts. Copy them somewhere public, somewhere you can link to from your css.

On the google webfont download page, you'll find a include link like so:

http://fonts.googleapis.com/css?family=Cantarell:400,700,400italic,700italic|Candal

It links to a CSS defining the fonts via a bunch of @font-face defintions.

Open it in a browser to copy and paste them into your own CSS and modify the urls to include the right font file and format types.

So this:

    @font-face {
      font-family: 'Cantarell';
      font-style: normal;
      font-weight: 700;
      src: local('Cantarell Bold'), local('Cantarell-Bold'), url(http://themes.googleusercontent.com/static/fonts/cantarell/v3/Yir4ZDsCn4g1kWopdg-ehHhCUOGz7vYGh680lGh-uXM.woff) format('woff');
    }

becomes this:

    /* Your local CSS File */
    @font-face {
        font-family: 'Cantarell';
        font-style: normal;
        font-weight: 700;
        src: local('Cantarell Bold'), local('Cantarell-Bold'), url(../font/Cantarell-Bold.ttf) format('truetype');
    }

As you can see, a downside of hosting the fonts on your own system this way is, that you restrict yourself to the true type format, whilst the google webfont service determines by the accessing device which formats will be transmitted.

Furthermore, I had to add a .htaccess file to my the directory holding the fonts containing mime types to avoid errors from popping up in Chrome Dev Tools.

For this solution, only true type is needed, but defining more does not hurt when you want to include different fonts as well, like font-awesome.

#.htaccess
AddType application/vnd.ms-fontobject .eot
AddType font/ttf .ttf
AddType font/otf .otf
AddType application/x-font-woff .woff

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

I foolishly uncommented the default config, which has passwords like "". Tomcat fails to parse this file (becayse of the "<"), and then whatever other config you add won't work-

After updating Entity Framework model, Visual Studio does not see changes

Right click the .tt file and select "Run Custom Tool", that should update it: see image

Matplotlib - How to plot a high resolution graph?

You can save your graph as svg for a lossless quality:

import matplotlib.pylab as plt

x = range(10)

plt.figure()
plt.plot(x,x)
plt.savefig("graph.svg")

Saving results with headers in Sql Server Management Studio

Another possibility is to use the clipboard to copy and paste the results directly into Excel. Just be careful with General type Excel columns, as they can sometimes have unpredictable results, depending on your data. CTL-A anywhere in the result grid, and then right-click:

enter image description here

If you have trouble with Excel's General format doing undesired conversions, select the blank columns in Excel before you paste and change the format to "text".

How can I add NSAppTransportSecurity to my info.plist file?

In mac shell command line , use the following command:

plutil -insert NSAppTransportSecurity -xml "<array><string> hidden </string></array>" [location of your xcode project]/Info.plist 

The command will add all the necessary values into your plist file.

How to find the .NET framework version of a Visual Studio project?

The simplest way to find the framework version of the current .NET project is:

  1. Right-click on the project and go to "Properties."
  2. In the first tab, "Application," you can see the target framework this project is using.

How do you automatically set text box to Uppercase?

Try below solution, This will also take care when a user enters only blank space in the input field at the first index.

_x000D_
_x000D_
document.getElementById('capitalizeInput').addEventListener("keyup",   () => {_x000D_
  var inputValue = document.getElementById('capitalizeInput')['value']; _x000D_
  if (inputValue[0] === ' ') {_x000D_
      inputValue = '';_x000D_
    } else if (inputValue) {_x000D_
      inputValue = inputValue[0].toUpperCase() + inputValue.slice(1);_x000D_
    }_x000D_
document.getElementById('capitalizeInput')['value'] = inputValue;_x000D_
});
_x000D_
<input type="text" id="capitalizeInput" autocomplete="off" />
_x000D_
_x000D_
_x000D_

How do I toggle an ng-show in AngularJS based on a boolean?

Basically I solved it by NOT-ing the isReplyFormOpen value whenever it is clicked:

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
    <!-- Form -->
</div>

Does Python's time.time() return the local or UTC timestamp?

The answer could be neither or both.

  • neither: time.time() returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's POSIX defintion for "Seconds Since the Epoch".

  • both: time.time() doesn't require your system's clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds):

    from datetime import datetime
    
    utc_dt = datetime.utcfromtimestamp(timestamp)
    

On how to get timestamps from UTC time in various Python versions, see How can I get a date converted to seconds since epoch according to UTC?

Writing MemoryStream to Response Object

Try with this

Response.Clear();
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));
Response.Flush();                
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

I use this method and it works well:

1- Copy And paste the .jar files under the libs folder.

2- Add compile fileTree(dir: 'libs', include: '*.jar') to dependencies in build.gradle then all the jars in the libs folder will be included..

3- Right click on libs folder and select 'Add as library' option from the list.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Clone() vs Copy constructor- which is recommended in java

Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().

Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).

Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).

How to update Android Studio automatically?

For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.

  1. On the top menu, select Help -> Check for Update...
  2. Upon the updates dialog below, select Updates link to configure your IDE settings.

Platform and Plugin Updates

  1. For checking updates, my suggestion is to select the Dev channel. I

don't recommend Beta or Canary

channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.

Updates dialog

  1. When finished with the configuration, select Update and Restart for downloading the installation EXE.
  2. Run the installation.

Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.

Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.

Reading file input from a multipart/form-data POST

I've had some issues with parser that are based on string parsing particularly with large files I found it would run out of memory and fail to parse binary data.

To cope with these issues I've open sourced my own attempt at a C# multipart/form-data parser here

Features:

  • Handles very large files well. (Data is streamed in and streamed out while reading)
  • Can handle multiple file uploads and automatically detects if a section is a file or not.
  • Returns files as a stream not as a byte[] (good for large files).
  • Full documentation for the library including a MSDN-style generated website.
  • Full unit tests.

Restrictions:

  • Doesn't handle non-multipart data.
  • Code is more complicated then Lorenzo's

Just use the MultipartFormDataParser class like so:

Stream data = GetTheStream();

// Boundary is auto-detected but can also be specified.
var parser = new MultipartFormDataParser(data, Encoding.UTF8);

// The stream is parsed, if it failed it will throw an exception. Now we can use
// your data!

// The key of these maps corresponds to the name field in your
// form
string username = parser.Parameters["username"].Data;
string password = parser.Parameters["password"].Data

// Single file access:
var file = parser.Files.First();
string filename = file.FileName;
Stream data = file.Data;

// Multi-file access
foreach(var f in parser.Files)
{
    // Do stuff with each file.
}

In the context of a WCF service you could use it like this:

public ResponseClass MyMethod(Stream multipartData)
{
    // First we need to get the boundary from the header, this is sent
    // with the HTTP request. We can do that in WCF using the WebOperationConext:
    var type = WebOperationContext.Current.IncomingRequest.Headers["Content-Type"];

    // Now we want to strip the boundary out of the Content-Type, currently the string
    // looks like: "multipart/form-data; boundary=---------------------124123qase124"
    var boundary = type.Substring(type.IndexOf('=')+1);

    // Now that we've got the boundary we can parse our multipart and use it as normal
    var parser = new MultipartFormDataParser(data, boundary, Encoding.UTF8);

    ...
}

Or like this (slightly slower but more code friendly):

public ResponseClass MyMethod(Stream multipartData)
{
    var parser = new MultipartFormDataParser(data, Encoding.UTF8);
}

Documentation is also available, when you clone the repository simply navigate to HttpMultipartParserDocumentation/Help/index.html

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Ruby/Rails: converting a Date to a UNIX timestamp

The suggested options of using to_utc or utc to fix the local time offset does not work. For me I found using Time.utc() worked correctly and the code involves less steps:

> Time.utc(2016, 12, 25).to_i
=> 1482624000 # correct

vs

> Date.new(2016, 12, 25).to_time.utc.to_i
=> 1482584400 # incorrect

Here is what happens when you call utc after using Date....

> Date.new(2016, 12, 25).to_time
=> 2016-12-25 00:00:00 +1100 # This will use your system's time offset
> Date.new(2016, 12, 25).to_time.utc
=> 2016-12-24 13:00:00 UTC

...so clearly calling to_i is going to give the wrong timestamp.

Insert current date in datetime format mySQL

If you're looking to store the current time just use MYSQL's functions.

mysql_query("INSERT INTO `table` (`dateposted`) VALUES (now())");

If you need to use PHP to do it, the format it Y-m-d H:i:s so try

$date = date('Y-m-d H:i:s');
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$date')");

Data truncation: Data too long for column 'logo' at row 1

Use data type LONGBLOB instead of BLOB in your database table.

Set the text in a span

$('.ui-icon-circle-triangle-w').text('<<');