Programs & Examples On #Django shell

How to execute a Python script from the Django shell?

I'm late for the party but I hope that my response will help someone: You can do this in your Python script:

import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings

the rest of your stuff goes here ....

Tools: replace not replacing in Android manifest

You can replace those in your Manifest application tag:

<application
    ...
    tools:replace="android:label, android:icon, android:theme"/>

and will work for you.

Explanation

Using such a dependency/library in your gradle file which has those labels in its Manifest's application tag may produce this problem and replacing them in your Manifest is the solution.

Delete specific line from a text file?

You can actually use C# generics for this to make it real easy:

        var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
        file.RemoveAt(12);
        File.WriteAllLines("C:\\path", file.ToArray());

Register .NET Framework 4.5 in IIS 7.5

You can find the aspnet_regiis in the following directory:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319

Go to the directory and run the command form there. I guess the path is missing in your PATH variable.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

Resizing an image in an HTML5 canvas

I'd highly suggest you check out this link and make sure it is set to true.

Controlling image scaling behavior

Introduced in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0)

Gecko 1.9.2 introduced the mozImageSmoothingEnabled property to the canvas element; if this Boolean value is false, images won't be smoothed when scaled. This property is true by default. view plainprint?

  1. cx.mozImageSmoothingEnabled = false;

Run Python script at startup in Ubuntu

If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-

  • Open Dash (The First Icon In Sidebar).
  • Then type Startup Applications and open that app.
  • Here Click the Add Button on the right.
  • There fill in the details and in the command area browse for your Python File and click Ok.
  • Test it by Restarting System . Done . Enjoy !!

Is an HTTPS query string secure?

Yes, from the moment on you establish a HTTPS connection everyting is secure. The query string (GET) as the POST is sent over SSL.

How to get the android Path string to a file on Assets folder?

Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:

@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
    val cacheFile = File(context.cacheDir, "splash_video")
    try {
        val inputStream = context.assets.open("splash_video")
        val outputStream = FileOutputStream(cacheFile)
        try {
            inputStream.copyTo(outputStream)
        } finally {
            inputStream.close()
            outputStream.close()
        }
    } catch (e: IOException) {
        throw IOException("Could not open splash_video", e)
    }
    return cacheFile
}

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

How can you run a command in bash over and over until success?

until passwd
do
  echo "Try again"
done

or

while ! passwd
do
  echo "Try again"
done

Converting a float to a string without rounding it

Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.

Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:

http://docs.python.org/library/decimal.html

Among other things you can explicitly specify the precision that you wish to obtain (from the docs):

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

A simple example from my prompt (python 2.6):

>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29

Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.

Hope this helps, Francesco

How to automatically update your docker containers, if base-images are updated

A 'docker way' would be to use docker hub automated builds. The Repository Links feature will rebuild your container when an upstream container is rebuilt, and the Webhooks feature will send you a notification.

It looks like the webhooks are limited to HTTP POST calls. You'd need to set up a service to catch them, or maybe use one of the POST to email services out there.

I haven't looked into it, but the new Docker Universal Control Plane might have a feature for detecting updated containers and re-deploying.

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

What is tail call optimization?

Let's walk through a simple example: the factorial function implemented in C.

We start with the obvious recursive definition

unsigned fac(unsigned n)
{
    if (n < 2) return 1;
    return n * fac(n - 1);
}

A function ends with a tail call if the last operation before the function returns is another function call. If this call invokes the same function, it is tail-recursive.

Even though fac() looks tail-recursive at first glance, it is not as what actually happens is

unsigned fac(unsigned n)
{
    if (n < 2) return 1;
    unsigned acc = fac(n - 1);
    return n * acc;
}

ie the last operation is the multiplication and not the function call.

However, it's possible to rewrite fac() to be tail-recursive by passing the accumulated value down the call chain as an additional argument and passing only the final result up again as the return value:

unsigned fac(unsigned n)
{
    return fac_tailrec(1, n);
}

unsigned fac_tailrec(unsigned acc, unsigned n)
{
    if (n < 2) return acc;
    return fac_tailrec(n * acc, n - 1);
}

Now, why is this useful? Because we immediately return after the tail call, we can discard the previous stackframe before invoking the function in tail position, or, in case of recursive functions, reuse the stackframe as-is.

The tail-call optimization transforms our recursive code into

unsigned fac_tailrec(unsigned acc, unsigned n)
{
TOP:
    if (n < 2) return acc;
    acc = n * acc;
    n = n - 1;
    goto TOP;
}

This can be inlined into fac() and we arrive at

unsigned fac(unsigned n)
{
    unsigned acc = 1;

TOP:
    if (n < 2) return acc;
    acc = n * acc;
    n = n - 1;
    goto TOP;
}

which is equivalent to

unsigned fac(unsigned n)
{
    unsigned acc = 1;

    for (; n > 1; --n)
        acc *= n;

    return acc;
}

As we can see here, a sufficiently advanced optimizer can replace tail-recursion with iteration, which is far more efficient as you avoid function call overhead and only use a constant amount of stack space.

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

Connecting to Oracle Database through C#?

First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

After installation add a reference of the assembly Oracle.DataAccess.dll.

Your are good to go after this.

using System; 
using Oracle.DataAccess.Client; 

class OraTest
{ 
    OracleConnection con; 
    void Connect() 
    { 
        con = new OracleConnection(); 
        con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>"; 
        con.Open(); 
        Console.WriteLine("Connected to Oracle" + con.ServerVersion); 
    }

    void Close() 
    {
        con.Close(); 
        con.Dispose(); 
    } 

    static void Main() 
    { 
        OraTest ot= new OraTest(); 
        ot.Connect(); 
        ot.Close(); 
    } 
}

How can I change the default Django date template format?

What you need is a date template filter.

e.g:

<td>Joined {{user.date_created|date:"F Y" }}<td>

This returns Joined December 2018

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

Creating a list/array in excel using VBA to get a list of unique names in a column

I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes

How to sort Counter by value? - python

Yes:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})

Using the sorted keyword key and a lambda function:

>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

This works for all dictionaries. However Counter has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common():

>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common()))  # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]

You can also specify how many items you want to see:

>>> x.most_common(2)  # specify number you want
[('c', 7), ('a', 5)]

How to fix '.' is not an internal or external command error

Replacing forward(/) slash with backward(\) slash will do the job. The folder separator in Windows is \ not /

How can I disable all views inside the layout?

In Kotlin, you can use isDuplicateParentStateEnabled = true before the View is added to the ViewGroup.

As documented in the setDuplicateParentStateEnabled method, if the child view has additional states (like checked state for a checkbox), these won't be affected by the parent.

The xml analogue is android:duplicateParentState="true".

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts!

.NET wants to conjure up low-level programming the most distant possible.

An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this event.

The first thing to do when an interrupt happend is to reset its state, becosa the hardware works in this way:

  1. a pin is connected to a signal and the hardware listen for it to change (the signal could have only two states).
  2. if the signal changes means that something happened and the hardware put a memory variable to the state happened (and it remain like this even if the signal change again).
  3. the program notice that variable change states and move the execution to a handling function.
  4. here the first thing to do, to be able to listen again this interrupt, is to reset this memory variable to the state not-happened.

This is the difference between ManualResetEvent and AutoResetEvent.
If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it.

Convert NSDate to String in iOS Swift

After allocating DateFormatter you need to give the formatted string then you can convert as string like this way

var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)

OutPut

01-Mar-2017

C read file line by line

My implement from scratch:

FILE *pFile = fopen(your_file_path, "r");
int nbytes = 1024;
char *line = (char *) malloc(nbytes);
char *buf = (char *) malloc(nbytes);

size_t bytes_read;
int linesize = 0;
while (fgets(buf, nbytes, pFile) != NULL) {
    bytes_read = strlen(buf);
    // if line length larger than size of line buffer
    if (linesize + bytes_read > nbytes) {
        char *tmp = line;
        nbytes += nbytes / 2;
        line = (char *) malloc(nbytes);
        memcpy(line, tmp, linesize);
        free(tmp);
    }
    memcpy(line + linesize, buf, bytes_read);
    linesize += bytes_read;

    if (feof(pFile) || buf[bytes_read-1] == '\n') {
        handle_line(line);
        linesize = 0;
        memset(line, '\0', nbytes);
    }
}

free(buf);
free(line);

Get protocol, domain, and port from URL

Why not use:

let full = window.location.origin

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

Android XML Percent Symbol

Not exactly your problem but a similar one.

If you have more than one formatting in your string entry, you should not use "%s" multiple times.

DON'T :

<string name="entry">Planned time %s - %s (%s)</string>

DO :

<string name="entry">Planned time %1$s - %2$s (%3$s)</string>

How can I query a value in SQL Server XML column

if your field name is Roles and table name is table1 you can use following to search

DECLARE @Role varchar(50);
SELECT * FROM table1
WHERE Roles.exist ('/root/role = sql:variable("@Role")') = 1

Is there a quick change tabs function in Visual Studio Code?

@Combii I found a way to swap

CMD+1, CMD+2, CMD+3 with CTRL+1, CTRL+2, CTRL+3, ...

In macOS, go to:

Code > Preferences > Keyboard Shortcuts

On that page, click the button on the top right of the page...

edit keybindings.json button

and append the configuration below, then save.

[
    {
        "key": "cmd+0",
        "command": "workbench.action.openLastEditorInGroup"
    },
    {
        "key": "cmd+1",
        "command": "workbench.action.openEditorAtIndex1"
    },
    {
        "key": "cmd+2",
        "command": "workbench.action.openEditorAtIndex2"
    },
    {
        "key": "cmd+3",
        "command": "workbench.action.openEditorAtIndex3"
    },
    {
        "key": "cmd+4",
        "command": "workbench.action.openEditorAtIndex4"
    },
    {
        "key": "cmd+5",
        "command": "workbench.action.openEditorAtIndex5"
    },
    {
        "key": "cmd+6",
        "command": "workbench.action.openEditorAtIndex6"
    },
    {
        "key": "cmd+7",
        "command": "workbench.action.openEditorAtIndex7"
    },
    {
        "key": "cmd+8",
        "command": "workbench.action.openEditorAtIndex8"
    },
    {
        "key": "cmd+9",
        "command": "workbench.action.openEditorAtIndex9"
    },
    {
        "key": "ctrl+1",
        "command": "workbench.action.focusFirstEditorGroup"
    },
    {
        "key": "ctrl+2",
        "command": "workbench.action.focusSecondEditorGroup"
    },
    {
        "key": "ctrl+3",
        "command": "workbench.action.focusThirdEditorGroup"
    }
]

You now can use CMD+[1-9] to switch between tabs and CTRL+[1-3] to focus editor groups! Hope this answer is helpful.

Rebase feature branch onto another feature branch

I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.

a -- b -- c                  <-- Master
     \     \
      \     d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
       \
        f -- g               <-- Branch2

How do I use IValidatableObject?

I liked cocogza's answer except that calling base.IsValid resulted in a stack overflow exception as it would re-enter the IsValid method again and again. So I modified it to be for a specific type of validation, in my case it was for an e-mail address.

[AttributeUsage(AttributeTargets.Property)]
class ValidEmailAddressIfTrueAttribute : ValidationAttribute
{
    private readonly string _nameOfBoolProp;

    public ValidEmailAddressIfTrueAttribute(string nameOfBoolProp)
    {
        _nameOfBoolProp = nameOfBoolProp;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            return null;
        }

        var property = validationContext.ObjectType.GetProperty(_nameOfBoolProp);
        if (property == null)
        {
            return new ValidationResult($"{_nameOfBoolProp} not found");
        }

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
        {
            return new ValidationResult($"{_nameOfBoolProp} not boolean");
        }

        if ((bool)boolVal)
        {
            var attribute = new EmailAddressAttribute {ErrorMessage = $"{value} is not a valid e-mail address."};
            return attribute.GetValidationResult(value, validationContext);
        }
        return null;
    }
}

This works much better! It doesn't crash and produces a nice error message. Hope this helps someone!

Android SDK location should not contain whitespace, as this cause problems with NDK tools

Copy your SDK folder and paste it in another folder without spaces (for example: "D: / Android / Sdk"), then open the SDK Manager, and change the Android SDK Location to the location of your new SDK folder

How do I catch a numpy warning like it's an exception (not just for testing)?

To add a little to @Bakuriu's answer:

If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

import numpy as np

a = np.r_[1.]
with np.errstate(divide='raise'):
    try:
        a / 0   # this gets caught and handled as an exception
    except FloatingPointError:
        print('oh no!')
a / 0           # this prints a RuntimeWarning as usual

Edit:

In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])

with np.errstate(divide='raise'):
    not_all_zeros / 0.  # Raises FloatingPointError

with np.errstate(divide='raise'):
    all_zeros / 0.  # No exception raised

with np.errstate(invalid='raise'):
    all_zeros / 0.  # Raises FloatingPointError

The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

What is a Maven artifact?

To maven, the build process is arranged as a set of artifacts. Artifacts include:

  1. The plugins that make up Maven itself.
  2. Dependencies that your code depends on.
  3. Anything that your build produces that can, in turn be consumed by something else.

Artifacts live in repositories.

What is declarative programming?

A couple other examples of declarative programming:

  • ASP.Net markup for databinding. It just says "fill this grid with this source", for example, and leaves it to the system for how that happens.
  • Linq expressions

Declarative programming is nice because it can help simplify your mental model* of code, and because it might eventually be more scalable.

For example, let's say you have a function that does something to each element in an array or list. Traditional code would look like this:

foreach (object item in MyList)
{
   DoSomething(item);
}

No big deal there. But what if you use the more-declarative syntax and instead define DoSomething() as an Action? Then you can say it this way:

MyList.ForEach(DoSometing);

This is, of course, more concise. But I'm sure you have more concerns than just saving two lines of code here and there. Performance, for example. The old way, processing had to be done in sequence. What if the .ForEach() method had a way for you to signal that it could handle the processing in parallel, automatically? Now all of a sudden you've made your code multi-threaded in a very safe way and only changed one line of code. And, in fact, there's a an extension for .Net that lets you do just that.

  • If you follow that link, it takes you to a blog post by a friend of mine. The whole post is a little long, but you can scroll down to the heading titled "The Problem" _and pick it up there no problem.*

How to cast Object to its actual type?

In my case AutoMapper works well.

AutoMapper can map to/from dynamic objects without any explicit configuration:

public class Foo {
    public int Bar { get; set; }
    public int Baz { get; set; }
}
dynamic foo = new MyDynamicObject();
foo.Bar = 5;
foo.Baz = 6;

Mapper.Initialize(cfg => {});

var result = Mapper.Map<Foo>(foo);
result.Bar.ShouldEqual(5);
result.Baz.ShouldEqual(6);

dynamic foo2 = Mapper.Map<MyDynamicObject>(result);
foo2.Bar.ShouldEqual(5);
foo2.Baz.ShouldEqual(6);

Similarly you can map straight from dictionaries to objects, AutoMapper will line up the keys with property names.

more info https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping

Get list from pandas dataframe column or row?

Example conversion:

Numpy Array -> Panda Data Frame -> List from one Panda Column

Numpy Array

data = np.array([[10,20,30], [20,30,60], [30,60,90]])

Convert numpy array into Panda data frame

dataPd = pd.DataFrame(data = data)
    
print(dataPd)
0   1   2
0  10  20  30
1  20  30  60
2  30  60  90

Convert one Panda column to list

pdToList = list(dataPd['2'])

How to run a C# application at Windows startup?

for WPF: (where lblInfo is a label, chkRun is a checkBox)

this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name

public partial class MainWindow : Window
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public MainWindow()
        {
            InitializeComponent();
            if (this.IsFocused)
            {
                this.Topmost = true;
            }
            else
            {
                this.Topmost = false;
            }

            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("StartupWithWindows") == null)
            {
                // The value doesn't exist, the application is not set to run at startup, Check box
                chkRun.IsChecked = false;
                lblInfo.Content = "The application doesn't run at startup";
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.IsChecked = true;
                lblInfo.Content = "The application runs at startup";
            }
            //Run at startup
            //rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);

            // Remove the value from the registry so that the application doesn't start
            //rkApp.DeleteValue("StartupWithWindows", false);

        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)chkRun.IsChecked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
                lblInfo.Content = "The application will run at startup";
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("StartupWithWindows", false);
                lblInfo.Content = "The application will not run at startup";
            }
        }

    }

How to join three table by laravel eloquent model

$articles =DB::table('articles')
                ->join('categories','articles.id', '=', 'categories.id')
                ->join('user', 'articles.user_id', '=', 'user.id')
                ->select('articles.id','articles.title','articles.body','user.user_name', 'categories.category_name')
                ->get();
return view('myarticlesview',['articles'=>$articles]);

How do I get first element rather than using [0] in jQuery?

$("#grid_GridHeader:first") works as well.

REST API Best practices: Where to put parameters?

IMO the parameters should be better as query arguments. The url is used to identify the resource, while the added query parameters to specify which part of the resource you want, any state the resource should have, etc.

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

How to add a tooltip to an svg graphic?

I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...

let comps = g.selectAll('.myClass')
   .data(data)
   .enter()
   .append('rect')
   ...styling...
   ...transitions...
   ...whatever...

g.selectAll('.myClass')
   .append('svg:title')
   .text((d, i) => d.name + '-' + i);

And a screenshot of chrome...

enter image description here

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

trigger('submit') does not work.beacuse onSubmit method does not get fired. the following code works for me, call onSubmit method when using this code :

$("form").find(':submit').click();

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.

Always reinitialize your select list within a POST action.

For further explanation: Persist SelectList in model on Post

How to update/modify an XML file in python?

You should read the XML file using specific XML modules. That way you can edit the XML document in memory and rewrite your changed XML document into the file.

Here is a quick start: http://docs.python.org/library/xml.dom.minidom.html

There are a lot of other XML utilities, which one is best depends on the nature of your XML file and in which way you want to edit it.

Laravel - Session store not set on request

Laravel [5.4]

My solution was to use global session helper: session()

Its functionality is a little bit harder than $request->session().

writing:

session(['key'=>'value']);

pushing:

session()->push('key', $notification);

retrieving:

session('key');

How can I select all rows with sqlalchemy?

You can easily import your model and run this:

from models import User

# User is the name of table that has a column name
users = User.query.all()

for user in users:
    print user.name

Regex Letters, Numbers, Dashes, and Underscores

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

Node.js global variables

You can just use the global object.

var X = ['a', 'b', 'c'];
global.x = X;

console.log(x);
//['a', 'b', 'c']

Difference between string object and string literal

In the first case, there are two objects created.

In the second case, it's just one.

Although both ways str is referring to "abc".

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

Where should I put the log4j.properties file?

You can specify config file location with VM argument -Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"

HTML5 Form Input Pattern Currency Format

Use this pattern "^\d*(\.\d{2}$)?"

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

How to disable scientific notation?

You can effectively remove scientific notation in printing with this code:

options(scipen=999)

Changing Background Image with CSS3 Animations

This is really fast and dirty, but it gets the job done: jsFiddle

    #img1, #img2, #img3, #img4 {
    width:100%;
    height:100%;
    position:fixed;
    z-index:-1;
    animation-name: test;
    animation-duration: 5s;
    opacity:0;
}
#img2 {
    animation-delay:5s;
    -webkit-animation-delay:5s
}
#img3 {
    animation-delay:10s;
    -webkit-animation-delay:10s
}
#img4 {
    animation-delay:15s;
    -webkit-animation-delay:15s
}

@-webkit-keyframes test {
    0% {
        opacity: 0;
    }
    50% {
        opacity: 1;
    }
    100% {
    }
}
@keyframes test {
    0% {
        opacity: 0;
    }
    50% {
        opacity: 1;
    }
    100% {
    }
}

I'm working on something similar for my site using jQuery, but the transition is triggered when the user scrolls down the page - jsFiddle

php - get numeric index of associative array

All solutions based on array_keys don't work for mixed arrays. Solution is simple:

echo array_search($needle,array_keys($haystack), true);

From php.net: If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

How to normalize a NumPy array to within a certain range?

I tried following this, and got the error

TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'l') according to the casting rule ''same_kind''

The numpy array I was trying to normalize was an integer array. It seems they deprecated type casting in versions > 1.10, and you have to use numpy.true_divide() to resolve that.

arr = np.array(img)
arr = np.true_divide(arr,[255.0],out=None)

img was an PIL.Image object.

How can I copy a Python string?

I'm just starting some string manipulations and found this question. I was probably trying to do something like the OP, "usual me". The previous answers did not clear up my confusion, but after thinking a little about it I finally "got it".

As long as a, b, c, d, and e have the same value, they reference to the same place. Memory is saved. As soon as the variable start to have different values, they get start to have different references. My learning experience came from this code:

import copy
a = 'hello'
b = str(a)
c = a[:]
d = a + ''
e = copy.copy(a)

print map( id, [ a,b,c,d,e ] )

print a, b, c, d, e

e = a + 'something'
a = 'goodbye'
print map( id, [ a,b,c,d,e ] )
print a, b, c, d, e

The printed output is:

[4538504992, 4538504992, 4538504992, 4538504992, 4538504992]

hello hello hello hello hello

[6113502048, 4538504992, 4538504992, 4538504992, 5570935808]

goodbye hello hello hello hello something

Non-static variable cannot be referenced from a static context

The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.

The lifecycle of a class, in broad terms, is:

  1. the source code for the class is written creating a template or pattern or stamp which can then be used to
  2. create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
  3. destroy the object reclaiming the resources it is holding such as memory during garbage collection.

In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.

The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.

So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.

However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.

import java.io.*;

class HelloWorld {
    int myInt;      // this is a class variable that is unique to each object
    static int myInt2;  // this is a class variable shared by all objects of this class

    static void main (String [] args) {
        // this is the main entry point for this Java application
        System.out.println ("Hello, World\n");
        myInt2 = 14;    // able to access the static int
        HelloWorld myWorld = new HelloWorld();
        myWorld.myInt = 32;   // able to access non-static through an object
    }
}

Get Path from another app (WhatsApp)

You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below

 public static String getFilePathFromURI(Context context, Uri contentUri) {
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH  + fileName+".jpg");
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Then IOUtils class is like below

public class IOUtils {



private static final int BUFFER_SIZE = 1024 * 2;

private IOUtils() {
    // Utility class.
}

public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
    }
    return count;
}


}

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

With boto3, this is the code :

s3_client = boto3.resource('s3', region_name='eu-central-1')

or

s3_client = boto3.client('s3', region_name='eu-central-1')

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

How to determine the longest increasing subsequence using dynamic programming?

Simplest LIS solution in C++ with O(nlog(n)) time complexity

#include <iostream>
#include "vector"
using namespace std;

// binary search (If value not found then it will return the index where the value should be inserted)
int ceilBinarySearch(vector<int> &a,int beg,int end,int value)
{
    if(beg<=end)
    {
        int mid = (beg+end)/2;
        if(a[mid] == value)
            return mid;
        else if(value < a[mid])
            return ceilBinarySearch(a,beg,mid-1,value);
        else
            return ceilBinarySearch(a,mid+1,end,value);

    return 0;
    }

    return beg;

}
int lis(vector<int> arr)
{
    vector<int> dp(arr.size(),0);
    int len = 0;
    for(int i = 0;i<arr.size();i++)
    {
        int j = ceilBinarySearch(dp,0,len-1,arr[i]);
        dp[j] = arr[i];
        if(j == len)
            len++;

    }
    return len;
}

int main()
{
    vector<int> arr  {2, 5,-1,0,6,1,2};
    cout<<lis(arr);
    return 0;
}

OUTPUT:
4

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

This should not happen. Can you try doing this? Use the system properties and set the property as below:

Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", "10.101.3.229");

And if you have a port associated, then set this as well.

properties.setProperty("mail.smtp.port", "8080");

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

How to protect Excel workbook using VBA?

I agree with @Richard Morgan ... what you are doing should be working, so more information may be needed.

Microsoft has some suggestions on options to protect your Excel 2003 worksheets.

Here is a little more info ...

From help files (Protect Method):

expression.Protect(Password, Structure, Windows)

expression Required. An expression that returns a Workbook object.

Password Optional Variant. A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.

Structure Optional Variant. True to protect the structure of the workbook (the relative position of the sheets). The default value is False.

Windows Optional Variant. True to protect the workbook windows. If this argument is omitted, the windows aren’t protected.

ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True

If you want to work at the worksheet level, I used something similar years ago when I needed to protect/unprotect:

Sub ProtectSheet()
    ActiveSheet.Protect "password", True, True
End Sub

Sub UnProtectSheet()
    ActiveSheet.Unprotect "password"
End Sub

Sub protectAll()
    Dim myCount
    Dim i
    myCount = Application.Sheets.Count
    Sheets(1).Select
    For i = 1 To myCount
        ActiveSheet.Protect "password", true, true
        If i = myCount Then
            End
        End If
        ActiveSheet.Next.Select
    Next i
End Sub

JavaScript require() on client side

I asked myself the very same questions. When I looked into it I found the choices overwhelming.

Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

To use arrow functions with function.prototype.call, I made a helper function on the object prototype:

  // Using
  // @func = function() {use this here} or This => {use This here}
  using(func) {
    return func.call(this, this);
  }

usage

  var obj = {f:3, a:2}
  .using(This => This.f + This.a) // 5

Edit

You don't NEED a helper. You could do:

var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

Checking if my Windows application is running

you can simply use varialbles and one file to check for running your program. when open the file contain a value and when program closes changes this value to another one.

Shuffling a list of objects

It works fine. I am trying it here with functions as list objects:

    from random import shuffle

    def foo1():
        print "foo1",

    def foo2():
        print "foo2",

    def foo3():
        print "foo3",

    A=[foo1,foo2,foo3]

    for x in A:
        x()

    print "\r"

    shuffle(A)
    for y in A:
        y()

It prints out: foo1 foo2 foo3 foo2 foo3 foo1 (the foos in the last row have a random order)

Simulating a click in jQuery/JavaScript on a link

Try this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

Objective-C: Calling selectors with multiple arguments

@Shane Arney

performSelector:withObject:withObject:

You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:).

kinda weird that apple only supports 2 objects to be send and didnt make it more generic.

SQL 'LIKE' query using '%' where the search criteria contains '%'

Select * from table where name like search_criteria

if you are expecting the user to add their own wildcards...

Excel VBA For Each Worksheet Loop

Instead of adding "ws." before every Range, as suggested above, you can add "ws.activate" before Call instead.

This will get you into the worksheet you want to work on.

How to identify all stored procedures referring a particular table

Try This

   SELECT DISTINCT so.name
    FROM syscomments sc
    INNER JOIN sysobjects so ON sc.id=so.id
    WHERE sc.TEXT LIKE '%your table name%'

insert datetime value in sql database with c#

It's more standard to use the format yyyy-mm-dd hh:mm:ss (IE: 2009-06-23 19:30:20)

Using that you won't have to worry about the format of the date (MM/DD/YYYY or DD/MM/YYYY). It will work with all of them.

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

How to get the date 7 days earlier date from current date in Java

You can use this to continue using the type Date and a more legible code, if you preffer:

import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);

Run a task every x-minutes with Windows Task Scheduler

To schedule the update to be automatic you should:

  • Go to Control Panel » Administrative Tools » Scheduled Tasks
  • Create the (basic) task
  • Go to Schedule » Advanced
  • Check the box for "Repeat Task" every 10 minutes with a duration of, e.g. 24 hours or Indefinitely
  • Leave End Date unchecked

If you cannot find the Schedule settings, look under: Properties, Edit, Triggers.

How to restore SQL Server 2014 backup in SQL Server 2008

If you have both versions you can create a merge replication from new to old. Create a merge publication on your newer sql server and a subscription on the older version. After initializing the subscription you can create a backup of the database with the same structure and the same content but in an older version and restore it on your old target server. You can use this method also with sql server 2016 to target 2014, 2012 or 2008.

Difference between .on('click') vs .click()

$('.UPDATE').click(function(){ }); **V/S**    
$(document).on('click','.UPDATE',function(){ });

$(document).on('click','.UPDATE',function(){ });
  1. it is more effective then $('.UPDATE').click(function(){ });
  2. it can use less memory and work for dynamically added elements.
  3. some time dynamic fetched data with edit and delete button not generate JQuery event at time of EDIT OR DELETE DATA of row data in form, that time $(document).on('click','.UPDATE',function(){ }); is effectively work like same fetched data by using jquery. button not working at time of update or delete:

enter image description here

Should ol/ul be inside <p> or outside?

The second. The first is invalid.

  • A paragraph cannot contain a list.
  • A list cannot contain a paragraph unless that paragraph is contained entirely within a single list item.

A browser will handle it like so:

<p>tetxtextextete 
<!-- Start of paragraph -->
<ol>
<!-- Start of ordered list. Paragraphs cannot contain lists. Insert </p> -->
<li>first element</li></ol>
<!-- A list item element. End of list -->
</p>
<!-- End of paragraph, but not inside paragraph, discard this tag to recover from the error -->
<p>other textetxet</p>
<!-- Another paragraph -->

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

Modifying CSS class property values on the fly with JavaScript / jQuery

Use jquery to add a style override in the <head>:

$('<style>.someClass {color: red;} input::-webkit-outer-spin-button: {display: none;}</style>')
.appendTo('head'); 

How can I exclude multiple folders using Get-ChildItem -exclude?

may be in your case you could reach this with the following:

    mv excluded_dir ..\
    ls -R 
    mv ..\excluded_dir .

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

How to easily consume a web service from PHP

This article explains how you can use PHP SoapClient to call a api web service.

Creating a new ArrayList in Java

You're very close. Use same type on both sides, and include ().

ArrayList<Class> myArray = new ArrayList<Class>();

Get name of current script in Python

For completeness' sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each:

  • __file__ is the currently executing file, as detailed in the official documentation:

    __file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

    From Python3.4 onwards, per issue 18416, __file__ is always an absolute path, unless the currently executing file is a script that has been executed directly (not via the interpreter with the -m command line option) using a relative path.

  • __main__.__file__ (requires importing __main__) simply accesses the aforementioned __file__ attribute of the main module, e.g. of the script that was invoked from the command line.

    From Python3.9 onwards, per issue 20443, the __file__ attribute of the __main__ module became an absolute path, rather than a relative path.

  • sys.argv[0] (requires importing sys) is the script name that was invoked from the command line, and might be an absolute path, as detailed in the official documentation:

    argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

    As mentioned in another answer to this question, Python scripts that were converted into stand-alone executable programs via tools such as py2exe or PyInstaller might not display the desired result when using this approach (i.e. sys.argv[0] would hold the name of the executable rather than the name of the main Python file within that executable).

  • If none of the aforementioned options seem to work, probably due to an atypical execution process or an irregular import operation, the inspect module might prove useful. In particular, invoking inspect.stack()[-1][1] should work, although it would raise an exception when running in an implementation without Python stack frame.

  • From Python3.6 onwards, and as detailed in another answer to this question, it's possible to install an external open source library, lib_programname, which is tailored to provide a complete solution to this problem.

    This library iterates through all of the approaches listed above until a valid path is returned. If all of them fail, it raises an exception. It also tries to address various pitfalls, such as invocations via the pytest framework or the pydoc module.

    import lib_programname
    # this returns the fully resolved path to the launched python program
    path_to_program = lib_programname.get_path_executed_script()  # type: pathlib.Path
    

Handling relative paths

When dealing with an approach that happens to return a relative path, it might be tempting to invoke various path manipulation functions, such as os.path.abspath(...) or os.path.realpath(...) in order to extract the full or real path.

However, these methods rely on the current path in order to derive the full path. Thus, if a program first changes the current working directory, for example via os.chdir(...), and only then invokes these methods, they would return an incorrect path.

Handling symbolic links

If the current script is a symbolic link, then all of the above would return the path of the symbolic link rather than the path of the real file and os.path.realpath(...) should be invoked in order to extract the latter.


Further manipulations that extract the actual file name

os.path.basename(...) may be invoked on any of the above in order to extract the actual file name and os.path.splitext(...) may be invoked on the actual file name in order to truncate its suffix, as in os.path.splitext(os.path.basename(...)).

From Python 3.4 onwards, per PEP 428, the PurePath class of the pathlib module may be used as well on any of the above. Specifically, pathlib.PurePath(...).name extracts the actual file name and pathlib.PurePath(...).stem extracts the actual file name without its suffix.

How do I create and store md5 passwords in mysql

you have to reason in terms of hased password:

store the password as md5('bob123'); when bob is register to your app

$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');

then, when bob is logging-in:

$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';

obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql

DD/MM/YYYY Date format in Moment.js

This worked for me

var dateToFormat = "2018-05-16 12:57:13"; //TIMESTAMP

moment(dateToFormat).format("DD/MM/YYYY"); // you get "16/05/2018"

What good technology podcasts are out there?

I love FLOSS Weekly. Another Twit Podcast where Leo and Randal Schwartz interview open source geeks. My favorite was their interview with Dan Ingalls (Smalltalk/Squeak fame). I also enjoyed their interview of Richard Hipp (SQLite).

How to validate an email address in PHP

/(?![[:alnum:]]|@|-|_|\.)./

Nowadays, if you use a HTML5 form with type=email then you're already by 80% safe since browser engines have their own validator. To complement it, add this regex to your preg_match_all() and negate it:

if (!preg_match_all("/(?![[:alnum:]]|@|-|_|\.)./",$email)) { .. }

Find the regex used by HTML5 forms for validation
https://regex101.com/r/mPEKmy/1

How to get object length

Summarizing all together, here is a universal function (including ie8 support):

_x000D_
_x000D_
var objSize = function(obj) {_x000D_
    var count = 0;_x000D_
    _x000D_
    if (typeof obj == "object") {_x000D_
    _x000D_
        if (Object.keys) {_x000D_
            count = Object.keys(obj).length;_x000D_
        } else if (window._) {_x000D_
            count = _.keys(obj).length;_x000D_
        } else if (window.$) {_x000D_
            count = $.map(obj, function() { return 1; }).length;_x000D_
        } else {_x000D_
            for (var key in obj) if (obj.hasOwnProperty(key)) count++;_x000D_
        }_x000D_
        _x000D_
    }_x000D_
    _x000D_
    return count;_x000D_
};_x000D_
_x000D_
document.write(objSize({ a: 1, b: 2, c: 3 }));_x000D_
// 3
_x000D_
_x000D_
_x000D_

How to set the text color of TextView in code?

From API 23 onward, getResources().getColor() is deprecated.

Use this instead:

textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.color_black));

How to print environment variables to the console in PowerShell?

In addition to Mathias answer.

Although not mentioned in OP, if you also need to see the Powershell specific/related internal variables, you need to use Get-Variable:

$ Get-Variable

Name                           Value
----                           -----
$                              name
?                              True
^                              gci
args                           {}
ChocolateyTabSettings          @{AllCommands=False}
ConfirmPreference              High
DebugPreference                SilentlyContinue
EnabledExperimentalFeatures    {}
Error                          {System.Management.Automation.ParseException: At line:1 char:1...
ErrorActionPreference          Continue
ErrorView                      NormalView
ExecutionContext               System.Management.Automation.EngineIntrinsics
false                          False
FormatEnumerationLimit         4
...

These also include stuff you may have set in your profile startup script.

HTML favicon won't show on google chrome

Note if you have so many tabs open that Google Chrome is only showing the favicons then Google Chrome won't show the favicon for the selected tab, so if you keep reloading the tab with your page loaded in order to see your new favicon you will only see the text of your page's title.

You will need to reload your page, and then select a different tab in order to see your favicon.

enter image description here

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

how to stop a for loop

Others ways to do the same is:

el = L[0][0]
m=len(L)

print L == [[el]*m]*m

Or:

first_el = L[0][0]
print all(el == first_el for inner_list in L for el in inner_list)

How to parse float with two decimal places in javascript?

Please use below function if you don't want to round off.

function ConvertToDecimal(num) {
    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
   alert('M : ' +  Number(num)); //If you need it back as a Number    
}

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

Trying to mock datetime.date.today(), but not working

For those of you using pytest with mocker here is how I mocked datetime.datetime.now() which is very similar to the original question.

test_get_now(mocker):
    datetime_mock = mocker.patch("blackline_accounts_import.datetime",)
    datetime_mock.datetime.now.return_value=datetime.datetime(2019,3,11,6,2,0,0)

    now == function_being_tested()  # run function

    assert now == datetime.datetime(2019,3,11,6,2,0,0)

Essentially the mock has to be set to return the specified date. You aren't able to patch over datetime's object directly.

Convert string to nullable type (int, double, etc...)

Another variation. This one

  • Does not swallow exceptions
  • Throws a NotSupportedException if the type can not be converted from string. For instance, a custom struct without a type converter.
  • Otherwise returns a (T?)null if the string fails to parse. No need to check for null or whitespace.
using System.ComponentModel;

public static Nullable<T> ToNullable<T>(this string s) where T : struct
{
    var ret = new Nullable<T>();
    var conv = TypeDescriptor.GetConverter(typeof(T));

    if (!conv.CanConvertFrom(typeof(string)))
    {
        throw new NotSupportedException();
    }

    if (conv.IsValid(s))
    {
        ret = (T)conv.ConvertFrom(s);
    }

    return ret;
}

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

How to len(generator())

You can use send as a hack:

def counter():
    length = 10
    i = 0
    while i < length:
        val = (yield i)
        if val == 'length':
            yield length
        i += 1

it = counter()
print(it.next())
#0
print(it.next())
#1
print(it.send('length'))
#10
print(it.next())
#2
print(it.next())
#3

Bootstrap how to get text to vertical align in a div container

Could you not have simply added:

align-items:center;

to a new class in your row div. Essentially:

<div class="row align_center">

.align_center { align-items:center; }

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

The error message says that getComputedStyle requires the parameter to be Element type. You receive it because the parameter has an incorrect type.

The most common case is that you try to pass an element that doesn't exist as an argument:

my_element = document.querySelector(#non_existing_id);

Now that element is null, this will result in mentioned error:

my_style = window.getComputedStyle(my_element);

If it's not possible to always get element correctly, you can, for example, use the following to end function if querySelector didn't find any match:

if (my_element === null) return;

Android SQLite Example

Using Helper class you can access SQLite Database and can perform the various operations on it by overriding the onCreate() and onUpgrade() methods.

http://technologyguid.com/android-sqlite-database-app-example/

How to generate a QR Code for an Android application?

with zxing this is my code for create QR

 QRCodeWriter writer = new QRCodeWriter();
    try {
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 512, 512);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        ((ImageView) findViewById(R.id.img_result_qr)).setImageBitmap(bmp);

    } catch (WriterException e) {
        e.printStackTrace();
    }

SQL Server - SELECT FROM stored procedure

It sounds like you might just need to use a view. A view allows a query to be represented as a table so it, the view, can be queried.

returning a Void object

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

So any of the following would suffice:

  • parameterizing with Object and returning new Object() or null
  • parameterizing with Void and returning null
  • parameterizing with a NullObject of yours

You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

The argument to remove() is a filter document, so passing in an empty document means 'remove all':

db.user.remove({})

However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove() call vs the drop() call.

More details in the docs.

JQuery show and hide div on mouse click (animate)

Of course slideDown and slideUp don't do what you want, you said you want it to be left/right, not top/down.

If your edit to your question adding the jquery-ui tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide effect.

If not:

Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source

$(document).ready(function() {
    // Hide menu once we know its width
    $('#showmenu').click(function() {
        var $menu = $('.menu');
        if ($menu.is(':visible')) {
            // Slide away
            $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
                $menu.hide();
            });
        }
        else {
            // Slide in
            $menu.show().animate({left: 0});
        }
    });
});

You'll need to put position: relative on the menu element.

Note that I replaced your toggle with click, because that form of toggle was removed from jQuery.


If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.

This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
  <script>
    $(document).ready(function() {
        var first = true;

        // Hide menu once we know its width
        $('#showmenu').click(function() {
            var $menu = $('.menu');
            if ($menu.is(':visible')) {
                // Slide away
                $menu.animate({left: -($menu.outerWidth() + 10)}, function() {
                    $menu.hide();
                });
            }
            else {
                // Slide in
                $menu.show().css("left", -($menu.outerWidth() + 10)).animate({left: 0});
            }
        });
    });
  </script>
</body>
</html>

No increment operator (++) in Ruby?

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ...... To increment a number, simply write x += 1.

Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)

That explains it better than I ever could.

EDIT: and the reason from the language author himself (source):

  1. ++ and -- are NOT reserved operator in Ruby.
  2. C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
  3. self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.

How to use __doPostBack()

Old question, but I'd like to add something: when calling doPostBack() you can use the server handler method for the action.

For an example:

__doPostBack('<%= btn.UniqueID%>', 'my args');

Will fire, on server:

protected void btn_Click(object sender, EventArgs e)

I didn't find a better way to get the argument, so I'm still using Request["__EVENTARGUMENT"].

'IF' in 'SELECT' statement - choose output value based on column values

Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

So Logic is

if report.type = 'p' 
    amount = amount 
else 
    amount = -1*amount 

SQL

SELECT 
    id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM  report

You may skip abs() if all no's are +ve only

Validating email addresses using jQuery and regex

Try this

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
    return pattern.test(emailAddress);
};

Create a basic matrix in C (input by user !)

int rows, cols , i, j;
printf("Enter number of rows and cols for the matrix: \n");
scanf("%d %d",&rows, &cols);

int mat[rows][cols];

printf("enter the matrix:");

for(i = 0; i < rows ; i++)
    for(j = 0; j < cols; j++)
        scanf("%d", &mat[i][j]);

printf("\nThe Matrix is:\n");
for(i = 0; i < rows ; i++)
{
    for(j = 0; j < cols; j++)
    {
        printf("%d",mat[i][j]);
        printf("\t");
    }
    printf("\n");
}

}

How does a Java HashMap handle different objects with the same hash code?

Each Entry object represents key-value pair. Field next refers to other Entry object if a bucket has more than 1 Entry.

Sometimes it might happen that hashCodes for 2 different objects are the same. In this case 2 objects will be saved in one bucket and will be presented as LinkedList. The entry point is more recently added object. This object refers to other object with next field and so one. Last entry refers to null. When you create HashMap with default constructor

Array is gets created with size 16 and default 0.75 load balance.

enter image description here

(Source)

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

UPDATE table SET column=0 WHERE column IS NULL

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

jQuery Ajax PUT with parameters

You can use the PUT method and pass data that will be included in the body of the request:

let data = {"key":"value"}

$.ajax({
    type: 'PUT',
    url: 'http://example.com/api',
    contentType: 'application/json',
    data: JSON.stringify(data), // access in body
}).done(function () {
    console.log('SUCCESS');
}).fail(function (msg) {
    console.log('FAIL');
}).always(function (msg) {
    console.log('ALWAYS');
});

How can I handle the warning of file_get_contents() function in PHP?

Here's how I handle that:

$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
    $error = error_get_last();
    $error = explode(': ', $error['message']);
    $error = trim($error[2]) . PHP_EOL;
    fprintf(STDERR, 'Error: '. $error);
    die();
}

Maintaining Session through Angular.js

Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.

PHP Page: session.php

if (!isset($_SESSION))
{    
    session_start();
}    

$_SESSION['variable'] = "hello world";

$sessions = array();

$sessions['variable'] = $_SESSION['variable'];

header('Content-Type: application/json');
echo json_encode($sessions);

Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.

JS All Together

var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {      
    Session.then(function(response){
        $rootScope.session = response;
    });
}]);

 app.factory('Session', function($http) {    
    return $http.get('/session.php').then(function(result) {       
        return result.data; 
    });
}); 
  • Do a simple get to get sessions using a factory.
  • If you want to make it post to make the page not visible when you just go to it in the browser you can, I'm just simplifying it
  • Add the factory to the controller
  • I use rootScope because it is a session variable that I use throughout all my code.

HTML

Inside your html you can reference your session

<html ng-app="StarterApp">

<body ng-controller="AppCtrl">
{{ session.variable }}
</body>

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

jquery live hover

As of jQuery 1.4.1, the hover event works with live(). It basically just binds to the mouseenter and mouseleave events, which you can do with versions prior to 1.4.1 just as well:

$("table tr")
    .mouseenter(function() {
        // Hover starts
    })
    .mouseleave(function() {
        // Hover ends
    });

This requires two binds but works just as well.

How to Automatically Close Alerts using Twitter Bootstrap

I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.

window.setTimeout(function() { // hide alert message
    $("#alert_message").removeClass('in'); 

}, 5000);

When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)

    $('#Some_Button_Or_Event_Here').click(function () { // Show alert message
        $('#alert_message').addClass('in'); 
    });

How to open Atom editor from command line in OS X?

When Atom installs it automatically creates a symlink in your /usr/local/bin. However in case it hasn't, you can create it yourself on your Mac

ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom

Now you can use atom folder_name to open a folder and atom file_name to open a file.

Is there a Social Security Number reserved for testing/examples?

Please look at this document

http://www.socialsecurity.gov/employer/randomization.html

The SSA is instituting a new policy the where all previously unused sequences are will be available for use.

Goes into affect June 25, 2011.

Taken from the new FAQ:

What changes will result from randomization?

The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top

Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?

SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.

What are Maven goals and phases and what is their difference?

There are following three built-in build lifecycles:

  • default
  • clean
  • site

Lifecycle default -> [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]

Lifecycle clean -> [pre-clean, clean, post-clean]

Lifecycle site -> [pre-site, site, post-site, site-deploy]

The flow is sequential, for example, for default lifecycle, it starts with validate, then initialize and so on...

You can check the lifecycle by enabling debug mode of mvn i.e., mvn -X <your_goal>

What is The Rule of Three?

Basically if you have a destructor (not the default destructor) it means that the class that you defined has some memory allocation. Suppose that the class is used outside by some client code or by you.

    MyClass x(a, b);
    MyClass y(c, d);
    x = y; // This is a shallow copy if assignment operator is not provided

If MyClass has only some primitive typed members a default assignment operator would work but if it has some pointer members and objects that do not have assignment operators the result would be unpredictable. Therefore we can say that if there is something to delete in destructor of a class, we might need a deep copy operator which means we should provide a copy constructor and assignment operator.

CardView not showing Shadow in Android L

Add android:hardwareAccelerated="true" in your manifests file like below it works for me

 <activity
        android:name=".activity.MyCardViewActivity"
        android:hardwareAccelerated="true"></activity>

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Using ListView : How to add a header view?

You simply can't use View as a Header of ListView.

Because the view which is being passed in has to be inflated.

Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.

EDIT:

Look at this tutorial Android ListView and ListActivity - Tutorial .

EDIT 2: This link is broken Android ListActivity with a header or footer

CSS pseudo elements in React

Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):

https://stackoverflow.com/a/42000085

<span class="something" datacustomattribute="">
  Hello
</span>
.something::before {
  content: attr(datascustomattribute);
  position: absolute;
}

Note that the datacustomattribute must start with data and be all lowercase to satisfy React.

VBA: Counting rows in a table (list object)

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

MySQL: Insert record if not exists in table

I had a problem, and the method Mike advised worked partly, I had an error Dublicate Column name = '0', and changed the syntax of your query as this`

     $tQ = "INSERT  INTO names (name_id, surname_id, sum, sum2, sum3,sum4,sum5) 
                SELECT '$name', '$surname', '$sum', '$sum2', '$sum3','$sum4','$sum5' 
FROM DUAL
                WHERE NOT EXISTS (
                SELECT sum FROM names WHERE name_id = '$name' 
AND surname_id = '$surname') LIMIT 1;";

The problem was with column names. sum3 was equal to sum4 and mysql throwed dublicate column names, and I wrote the code in this syntax and it worked perfectly,

How to create a sleep/delay in nodejs that is Blocking?

The best solution is to create singleton controller for your LED which will queue all commands and execute them with specified delay:

function LedController(timeout) {
  this.timeout = timeout || 100;
  this.queue = [];
  this.ready = true;
}

LedController.prototype.send = function(cmd, callback) {
  sendCmdToLed(cmd);
  if (callback) callback();
  // or simply `sendCmdToLed(cmd, callback)` if sendCmdToLed is async
};

LedController.prototype.exec = function() {
  this.queue.push(arguments);
  this.process();
};

LedController.prototype.process = function() {
  if (this.queue.length === 0) return;
  if (!this.ready) return;
  var self = this;
  this.ready = false;
  this.send.apply(this, this.queue.shift());
  setTimeout(function () {
    self.ready = true;
    self.process();
  }, this.timeout);
};

var Led = new LedController();

Now you can call Led.exec and it'll handle all delays for you:

Led.exec(cmd, function() {
  console.log('Command sent');
});

How to handle an IF STATEMENT in a Mustache template?

Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}

What does map(&:name) mean in Ruby?

Here :name is the symbol which point to the method name of tag object. When we pass &:name to map, it will treat name as a proc object. For short, tags.map(&:name) acts as:

tags.map do |tag|
  tag.name
end

jQuery select option elements by value

You can use .val() to select the value, like the following:

function select_option(i) {
    $("#span_id select").val(i);
}

Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD.

In general, you should use the highest level of abstraction that suits your needs. This means that you should usually use NSOperationQueue instead of GCD, unless you need to do something that NSOperationQueue doesn't support.

Note that NSOperationQueue isn't a "dumbed-down" version of GCD; in fact, there are many things that you can do very simply with NSOperationQueue that take a lot of work with pure GCD. (Examples: bandwidth-constrained queues that only run N operations at a time; establishing dependencies between operations. Both very simple with NSOperation, very difficult with GCD.) Apple's done the hard work of leveraging GCD to create a very nice object-friendly API with NSOperation. Take advantage of their work unless you have a reason not to.

Caveat: On the other hand, if you really just need to send off a block, and don't need any of the additional functionality that NSOperationQueue provides, there's nothing wrong with using GCD. Just be sure it's the right tool for the job.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

Ok - my case was not strictly related to this question, but I ended up on this page when Googling for the same exception; I queried an SQL database with LINQ when I got this exception.

private Table<SubscriptionModel> m_subscriptionsSql;
var query = from SubscriptionModel subscription in m_subscriptionsSql ...

Turned out I forgot to initialize my Table instance variable, that I used in the LINQ query.

m_subscriptionsSql = GetTable<SubscriptionModel>();

Declare multiple module.exports in Node.js

module.exports = (function () {
    'use strict';

    var foo = function () {
        return {
            public_method: function () {}
        };
    };

    var bar = function () {
        return {
            public_method: function () {}
        };
    };

    return {
        module_a: foo,
        module_b: bar
    };
}());

ImportError: No module named sklearn.cross_validation

Splitting the dataset into the Training set and Test set

from sklearn.model_selection import train_test_split

How to create a collapsing tree table in html/css/js?

In modern browsers, you need only very little to code to create a collapsible tree :

_x000D_
_x000D_
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');_x000D_
for(var i = 0; i < tree.length; i++){_x000D_
    tree[i].addEventListener('click', function(e) {_x000D_
        var parent = e.target.parentElement;_x000D_
        var classList = parent.classList;_x000D_
        if(classList.contains("open")) {_x000D_
            classList.remove('open');_x000D_
            var opensubs = parent.querySelectorAll(':scope .open');_x000D_
            for(var i = 0; i < opensubs.length; i++){_x000D_
                opensubs[i].classList.remove('open');_x000D_
            }_x000D_
        } else {_x000D_
            classList.add('open');_x000D_
        }_x000D_
        e.preventDefault();_x000D_
    });_x000D_
}
_x000D_
body {_x000D_
    font-family: Arial;_x000D_
}_x000D_
_x000D_
ul.tree li {_x000D_
    list-style-type: none;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
ul.tree li ul {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
ul.tree li.open > ul {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ul.tree li a {_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
}_x000D_
_x000D_
ul.tree li a:before {_x000D_
    height: 1em;_x000D_
    padding:0 .1em;_x000D_
    font-size: .8em;_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    left: -1.3em;_x000D_
    top: .2em;_x000D_
}_x000D_
_x000D_
ul.tree li > a:not(:last-child):before {_x000D_
    content: '+';_x000D_
}_x000D_
_x000D_
ul.tree li.open > a:not(:last-child):before {_x000D_
    content: '-';_x000D_
}
_x000D_
<ul class="tree">_x000D_
  <li><a href="#">Part 1</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 2</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li><a href="#">Part 3</a>_x000D_
    <ul>_x000D_
      <li><a href="#">Item A</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item B</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item C</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item D</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li><a href="#">Item E</a>_x000D_
        <ul>_x000D_
          <li><a href="#">Sub-item 1</a></li>_x000D_
          <li><a href="#">Sub-item 2</a></li>_x000D_
          <li><a href="#">Sub-item 3</a></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

Cannot create SSPI context

I also issued this problem, and the server admins solved it by following the same solution as indu_teja proposed in http://www.sqlservercentral.com/Forums/Topic546566-146-1.aspx

The solution proposed by indu_teja says :

If you get this "SSPI Context Error". The issues we face are:

  1. We will not be able to connect to SQL Server remotely.
  2. However we will be able to connect to server with local account.

CAUSE: The issue might be becasue of no proper sync happenign fro the SPNs in Active directory.

RESOLUTION:

  1. You need to reset SPN. Use the synytax "SET SPN". You can check the syntax in net once.
  2. Change your sql server service account from domain account to Local account, recycle sql, and then reset again with your domain account and recycle sql server.

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

Getting list of files in documents folder

Swift 2.0 Compability

func listWithFilter () {

    let fileManager = NSFileManager.defaultManager()
           // We need just to get the documents folder url
    let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

    do {
    // if you want to filter the directory contents you can do like this:
    if let directoryUrls = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants) {
        print(directoryUrls)
       ........
        }

    }

}

OR

 func listFiles() -> [String] {

    var theError = NSErrorPointer()
    let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
    if dirs != nil {
        let dir = dirs![0]
        do {
        let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir)
        return fileList as [String]
        }catch {

        }

    }else{
        let fileList = [""]
        return fileList
    }
    let fileList = [""]
    return fileList

}

Base64 Encoding Image

My synopsis of rfc2397 is:

Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64," this is similar to the prefixing done in the parenthesis of url() definition in CSS or in the quoted value of the src attribute of the img tag in [X]HTML. You can test the data url in firefox by putting the data:image/... line into the URL field and pressing enter, it should show your image.

For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.

  1. Use the base64 command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
  2. Use a tool that features the option to convert to base64, like Notepad++ which has the feature under plugins->MIME tools->base64 Encode
  3. Email yourself the file and view the raw email contents, copy and paste.
  4. Use a web form.

A note on mime-types: I would prefer you use one of image/png image/jpeg or image/gif as I can't find the popular image/x-icon. Should that be image/vnd.microsoft.icon? Also the other formats are much shorter.

compare 265 bytes vs 1150 bytes:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=

data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==

How to make an executable JAR file?

In Eclipse you can do it simply as follows :

Right click on your Java Project and select Export.

Select Java -> Runnable JAR file -> Next.

Select the Launch Configuration and choose project file as your Main class

Select the Destination folder where you would like to save it and click Finish.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.

//airBnb
    compile ('com.airbnb:deeplinkdispatch:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }
    annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
        exclude group:'com.google.code.findbugs'
    }

Eclipse IDE for Java - Full Dark Theme

There's a new plugin which provides full theming for Eclipse:

http://brainwy.github.io/liclipse/

It's integrated with Eclipse Color Theme so that when a new theme is selected in preferences > general > appearance > color theme, the proper background is also applied to other parts of the IDE (theming everything or just views which are previously registered according to a combo in that same page).

And besides theming it provides a bunch of other things :)

Error handling in AngularJS http get then construct

https://docs.angularjs.org/api/ng/service/$http

$http.get(url).success(successCallback).error(errorCallback);

Replace successCallback and errorCallback with your functions.

Edit: Laurent's answer is more correct considering he is using then. Yet I'm leaving this here as an alternative for the folks who will visit this question.

How to make inline functions in C#

The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.

Here's some really simple code I used to test this (VS2015):

    static void Main(string[] args)
    {
        Func<int, int> incr = a => a + 1;
        Console.WriteLine($"P1 = {incr(5)}");
    }

What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)

This is the Main function:

        IL_001f: stloc.0
        IL_0020: ldstr "P1 = {0}"
        IL_0025: ldloc.0
        IL_0026: ldc.i4.5
        IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
        IL_002c: box [mscorlib]System.Int32
        IL_0031: call string [mscorlib]System.String::Format(string, object)
        IL_0036: call void [mscorlib]System.Console::WriteLine(string)
        IL_003b: ret

See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.

And here's the function called:

        .method assembly hidebysig 
            instance int32 '<Main>b__0_0' (
                int32 a
            ) cil managed 
        {
            // Method begins at RVA 0x20ac
            // Code size 4 (0x4)
            .maxstack 8

            IL_0000: ldarg.1
            IL_0001: ldc.i4.1
            IL_0002: add
            IL_0003: ret
        } // end of method '<>c'::'<Main>b__0_0'

It's a really short function, but it is a function.

Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.

In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.

"Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth

"A program that doesn't run correctly doesn't need to run fast" -- Me

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

Requirements files use an expanded pip format, which is only useful if you need to complement your setup.py with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of pip freeze to freeze the entire package set to known-working versions. If you don't need the extra constraints, use only a setup.py. If you feel like you really need to ship a requirements.txt anyway, you can make it a single line:

.

It will be valid and refer exactly to the contents of the setup.py that is in the same directory.

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

For better explain Dave Morrissey's answer I have made these steps for wrap with Console Output class in a laravel facade.

1) Create a Facade in your prefer folder (in my case app\Facades):

class ConsoleOutput extends Facade {

 protected static function getFacadeAccessor() { 
     return 'consoleOutput';
 }

}

2) Register a new Service Provider in app\Providers as follow:

class ConsoleOutputServiceProvider extends ServiceProvider
{

 public function register(){
    App::bind('consoleOutput', function(){
        return new \Symfony\Component\Console\Output\ConsoleOutput();
     });
 }

}

3) Add all this stuffs in config\app.php file, registering the provider and alias.

 'providers' => [
   //other providers
    App\Providers\ConsoleOutputServiceProvider::class
 ],
 'aliases' => [
  //other aliases
   'ConsoleOutput' => App\Facades\ConsoleOutput::class,
 ],

That's it, now in any place of your Laravel application, just call your method in this way:

ConsoleOutput::writeln('hello');

Hope this help you.

Foreach with JSONArray and JSONObject

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

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

Source

Determine the data types of a data frame's columns

Since it wasn't stated clearly, I just add this:

I was looking for a way to create a table which holds the number of occurrences of all the data types.

Say we have a data.frame with two numeric and one logical column

dta <- data.frame(a = c(1,2,3), 
                  b = c(4,5,6), 
                  c = c(TRUE, FALSE, TRUE))

You can summarize the number of columns of each data type with that

table(unlist(lapply(dta, class)))
# logical numeric 
#       1       2 

This comes extremely handy, if you have a lot of columns and want to get a quick overview.

To give credit: This solution was inspired by the answer of @Cybernetic.

How do I debug "Error: spawn ENOENT" on node.js?

solution in my case

var spawn = require('child_process').spawn;

const isWindows = /^win/.test(process.platform); 

spawn(isWindows ? 'twitter-proxy.cmd' : 'twitter-proxy');
spawn(isWindows ? 'http-server.cmd' : 'http-server');

PHP Using RegEx to get substring of a string

$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);

Replacing all non-alphanumeric characters with empty strings

public static void main(String[] args) {
    String value = " Chlamydia_spp. IgG, IgM & IgA Abs (8006) ";

    System.out.println(value.replaceAll("[^A-Za-z0-9]", ""));

}

output: ChlamydiasppIgGIgMIgAAbs8006

Github: https://github.com/AlbinViju/Learning/blob/master/StripNonAlphaNumericFromString.java

How do you render primitives as wireframes in OpenGL?

A good and simple way of drawing anti-aliased lines on a non anti-aliased render target is to draw rectangles of 4 pixel width with an 1x4 texture, with alpha channel values of {0.,1.,1.,0.}, and use linear filtering with mip-mapping off. This will make the lines 2 pixels thick, but you can change the texture for different thicknesses. This is faster and easier than barymetric calculations.

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

How to set portrait and landscape media queries in css?

It can also be as simple as this.

@media (orientation: landscape) {

}

Round button with text and icon in flutter

You can achieve that by using a FlatButton that contains a Column (for showing a text below the icon) or a Row (for text next to the icon), and then having an Icon Widget and a Text widget as children.

Here's an example:

class MyPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) =>
      Scaffold(
        appBar: AppBar(
          title: Text("Hello world"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                onPressed: () => {},
                color: Colors.orange,
                padding: EdgeInsets.all(10.0),
                child: Column( // Replace with a Row for horizontal icon + text
                  children: <Widget>[
                    Icon(Icons.add),
                    Text("Add")
                  ],
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => {},
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      );
}

This will produce the following:

Result

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

It's same as vikasdumca's steps, but thought to share the link.

run the following command

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

then

sudo apt-get install oracle-java8-installer

this would install oracle java 8 on ubuntu properly.

find it from this post

you can find more info on "Managing Java" or "Setting the "JAVA_HOME" environment variable" from the post.

how to break the _.each function in underscore.js

Like the other answers, it's impossible. Here is the comment about breaker in underscore underscore issue #21

Check if a string contains a number

Simpler way to solve is as

s = '1dfss3sw235fsf7s'
count = 0
temp = list(s)
for item in temp:
    if(item.isdigit()):
        count = count + 1
    else:
        pass
print count

How to change python version in anaconda spyder

If you are using anaconda to go into python environment you should have build up different environment for different python version

The following scripts may help you build up a new environment(running in anaconda prompt)

conda create -n py27 python=2.7  #for version 2.7
activate py27

conda create -n py36 python=3.6  #for version 3.6
activate py36

you may leave the environment back to your global env by typing
deactivate py27 
or 
deactivate py36 

and then you can either switch to different environment using your anaconda UI with @Francisco Camargo 's answer

or you can stick to anaconda prompt using @Dan 's answer

Animation CSS3: display + opacity

If you are triggering the change with JS, let's say on click, there is a nice workaround.

You see, the problem happens because the animation is ignored on display:none element but browser applies all the changes at once and the element is never display:block while not animated at the same time.

The trick is to ask the browser to render the frame after changing the visibility but before triggering the animation.

Here is a JQuery example:

    $('.child').css({"display":"block"});
    //now ask the browser what is the value of the display property
    $('.child').css("display"); //this will trigger the browser to apply the change. this costs one frame render
    //now a change to opacity will trigger the animation
    $('.child').css("opacity":100);

increase the java heap size permanently?

Apparently, _JAVA_OPTIONS works on Linux, too:

$ export _JAVA_OPTIONS="-Xmx1g"
$ java -jar jconsole.jar &
Picked up _JAVA_OPTIONS: -Xmx1g

How to increase font size in a plot in R?

By trial and error, I've determined the following is required to set font size:

  1. cex doesn't work in hist(). Use cex.axis for the numbers on the axes, cex.lab for the labels.
  2. cex doesn't work in axis() either. Use cex.axis for the numbers on the axes.
  3. In place of setting labels using hist(), you can set them using mtext(). You can set the font size using cex, but using a value of 1 actually sets the font to 1.5 times the default!!! You need to use cex=2/3 to get the default font size. At the very least, this is the case under R 3.0.2 for Mac OS X, using PDF output.
  4. You can change the default font size for PDF output using pointsize in pdf().

I suppose it would be far too logical to expect R to (a) actually do what its documentation says it should do, (b) behave in an expected fashion.

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

UICollectionView - Horizontal scroll, horizontal layout?

for xcode 8 i did this and it worked:

How can I transition height: 0; to height: auto; using CSS?

The accepted answer works for most cases, but it doesn't work well when your div can vary greatly in height — the animation speed is not dependent on the actual height of the content, and it can look choppy.

You can still perform the actual animation with CSS, but you need to use JavaScript to compute the height of the items, instead of trying to use auto. No jQuery is required, although you may have to modify this a bit if you want compatibility (works in the latest version of Chrome :)).

_x000D_
_x000D_
window.toggleExpand = function(element) {_x000D_
    if (!element.style.height || element.style.height == '0px') { _x000D_
        element.style.height = Array.prototype.reduce.call(element.childNodes, function(p, c) {return p + (c.offsetHeight || 0);}, 0) + 'px';_x000D_
    } else {_x000D_
        element.style.height = '0px';_x000D_
    }_x000D_
}
_x000D_
#menu #list {_x000D_
    height: 0px;_x000D_
    transition: height 0.3s ease;_x000D_
    background: #d5d5d5;_x000D_
    overflow: hidden;_x000D_
}
_x000D_
<div id="menu">_x000D_
    <input value="Toggle list" type="button" onclick="toggleExpand(document.getElementById('list'));">_x000D_
    <ul id="list">_x000D_
        <!-- Works well with dynamically-sized content. -->_x000D_
        <li>item</li>_x000D_
        <li><div style="height: 100px; width: 100px; background: red;"></div></li>_x000D_
        <li>item</li>_x000D_
        <li>item</li>_x000D_
        <li>item</li>_x000D_
    </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Upload DOC or PDF using PHP

For application/msword and application/vnd.ms-excel, when I deleted the size restriction:

($_FILES["file"]["size"] < 20000)

...it worked ok.

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

  using (MemoryStream mem = new MemoryStream())
  {
    SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);

    // Add a WorkbookPart to the document.
    WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
    workbookpart.Workbook = new Workbook();

    // Add a WorksheetPart to the WorkbookPart.
    WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
    worksheetPart.Worksheet = new Worksheet(new SheetData());

    // Add Sheets to the Workbook.
    Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

    // Add a row to the cell table.
    Row row;
    row = new Row() { RowIndex = 1 };
    sheetData.Append(row);

    // In the new row, find the column location to insert a cell in A1.  
    Cell refCell = null;
    foreach (Cell cell in row.Elements<Cell>())
    {
      if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
      {
        refCell = cell;
        break;
      }
    }

    // Add the cell to the cell table at A1.
    Cell newCell = new Cell() { CellReference = "A1" };
    row.InsertBefore(newCell, refCell);

    // Set the cell value to be a numeric value of 100.
    newCell.CellValue = new CellValue("100");
    newCell.DataType = new EnumValue<CellValues>(CellValues.Number);

    // Append a new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet()
    {
      Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
      SheetId = 1,
      Name = "mySheet"
    };

    sheets.Append(sheet);

    workbookpart.Workbook.Save();
    spreadsheetDocument.Close();

    return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "text.xlsx");
  }

How to create an integer-for-loop in Ruby?

You can perform a simple each loop on the range from 1 to `x´:

(1..x).each do |i|
  #...
end

What is the purpose of Order By 1 in SQL select statement?

Also see:

http://www.techonthenet.com/sql/order_by.php

For a description of order by. I learned something! :)

I've also used this in the past when I wanted to add an indeterminate number of filters to a sql statement. Sloppy I know, but it worked. :P

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

Check if the scrollable element is already scrolled to the top when trying to scroll up or to the bottom when trying to scroll down and then preventing the default action to stop the entire page from moving.

var touchStartEvent;
$('.scrollable').on({
    touchstart: function(e) {
        touchStartEvent = e;
    },
    touchmove: function(e) {
        if ((e.originalEvent.pageY > touchStartEvent.originalEvent.pageY && this.scrollTop == 0) ||
            (e.originalEvent.pageY < touchStartEvent.originalEvent.pageY && this.scrollTop + this.offsetHeight >= this.scrollHeight))
            e.preventDefault();
    }
});

How to localise a string inside the iOS info.plist file?

Step by step localize Info.plist:

  1. Find in the Xcode the folder Resources (is placed in root)
  2. Select the folder Resources
  3. Then press the main menu File->New->File...
  4. Select in section "Resource" Strings File and press Next
  5. Then in Save As field write InfoPlist ONLY ("I" capital and "P" capital)
  6. Then press Create
  7. Then select the file InfoPlist.strings that created in Resources folder and press in the right menu the button "Localize"
  8. Then you Select the Project from the Project Navigator and select the The project from project list
  9. In the info tab at the bottom you can as many as language you want (There is in section Localizations)
  10. The language you can see in Resources Folder
  11. To localize the values ("key") from info.plist file you can open with a text editor and get all the keys you want to localize
  12. You write any key as the example in any InfoPlist.strings like the above example

"NSLocationAlwaysAndWhenInUseUsageDescription"="blabla";

"NSLocationAlwaysUsageDescription"="blabla2";

That's all work and you have localize your info.plist file!

Converting two lists into a matrix

Simple you can try this

a=list(zip(portfolio, index))

Search in lists of lists by given index

Given below is a simple way to find exactly where in the list the item is.

for i in range (0,len(a)):
sublist=a[i]
for i in range(0,len(sublist)):
    if search==sublist[i]:
        print "found in sublist "+ "a"+str(i)

Simplest two-way encryption using PHP

IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.

Here is simple but secure enough implementation:

  • AES-256 encryption in CBC mode
  • PBKDF2 to create encryption key out of plain-text password
  • HMAC to authenticate the encrypted message.

Code and examples are here: https://stackoverflow.com/a/19445173/1387163

Find the host name and port using PSQL commands

select inet_server_addr( ), inet_server_port( );

C++, how to declare a struct in a header file

Try this new source :

student.h

#include <iostream>

struct Student {
    std::string lastName;
    std::string firstName;
};

student.cpp

#include "student.h"

struct Student student;