Programs & Examples On #Quantifiers

In logic, quantification is the binding of a variable ranging over a domain. The variable thereby becomes bound by an operator called a quantifier.

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

How do I download a package from apt-get without installing it?

Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).

apt-get install -d -o=dir::cache=/tmp whateveryouwant

Does VBA have Dictionary Structure?

You can access a non-Native HashTable through System.Collections.HashTable.

HashTable

Represents a collection of key/value pairs that are organized based on the hash code of the key.

Not sure you would ever want to use this over Scripting.Dictionary but adding here for the sake of completeness. You can review the methods in case there are some of interest e.g. Clone, CopyTo

Example:

Option Explicit

Public Sub UsingHashTable()

    Dim h As Object
    Set h = CreateObject("System.Collections.HashTable")
   
    h.Add "A", 1
    ' h.Add "A", 1  ''<< Will throw duplicate key error
    h.Add "B", 2
    h("B") = 2
      
    Dim keys As mscorlib.IEnumerable 'Need to cast in order to enumerate  'https://stackoverflow.com/a/56705428/6241235
    
    Set keys = h.keys
    
    Dim k As Variant
    
    For Each k In keys
        Debug.Print k, h(k)                      'outputs the key and its associated value
    Next
    
End Sub

This answer by @MathieuGuindon gives plenty of detail about HashTable and also why it is necessary to use mscorlib.IEnumerable (early bound reference to mscorlib) in order to enumerate the key:value pairs.


Bootstrap 3 navbar active li not changing background-color

in my case just removing background-image from nav-bar item solved the problem

.navbar-default .navbar-nav > .active > a:focus {
    .
    .
    .


    background-image: none;
}

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

To call a sub inside another sub you only need to do:

Call Subname()

So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)

As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work

Hope it helps, Bruno

PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."

Global Variable in app.js accessible in routes?

As others have already shared, app.set('config', config) is great for this. I just wanted to add something that I didn't see in existing answers that is quite important. A Node.js instance is shared across all requests, so while it may be very practical to share some config or router object globally, storing runtime data globally will be available across requests and users. Consider this very simple example:

var express = require('express');
var app = express();

app.get('/foo', function(req, res) {
    app.set('message', "Welcome to foo!");
    res.send(app.get('message'));
});

app.get('/bar', function(req, res) {
    app.set('message', "Welcome to bar!");

    // some long running async function
    var foo = function() {
        res.send(app.get('message'));
    };
    setTimeout(foo, 1000);
});

app.listen(3000);

If you visit /bar and another request hits /foo, your message will be "Welcome to foo!". This is a silly example, but it gets the point across.

There are some interesting points about this at Why do different node.js sessions share variables?.

Find the max of 3 numbers in Java with different data types

if you want to do a simple, it will be like this

// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;

public class MaximumFinder
{
  // obtain three floating-point values and locate the maximum value
  public static void main(String[] args)
  {
    // create Scanner for input from command window
    Scanner input = new Scanner(System.in);

    // prompt for and input three floating-point values
    System.out.print(
      "Enter three floating-point values separated by spaces: ");
    double number1 = input.nextDouble(); // read first double
    double number2 = input.nextDouble(); // read second double
    double number3 = input.nextDouble(); // read third double

    // determine the maximum value
    double result = maximum(number1, number2, number3);

    // display maximum value
    System.out.println("Maximum is: " + result);
  }

  // returns the maximum of its three double parameters          
  public static double maximum(double x, double y, double z)     
  {                                                              
    double maximumValue = x; // assume x is the largest to start

    // determine whether y is greater than maximumValue         
    if (y > maximumValue)                                       
      maximumValue = y;                                        

    // determine whether z is greater than maximumValue         
    if (z > maximumValue)                                       
      maximumValue = z;                                        

    return maximumValue;                                        
  }                                                              
} // end class MaximumFinder

and the output will be something like this

Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

References Java™ How To Program (Early Objects), Tenth Edition

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

find index of an int in a list

List<string> accountList = new List<string> {"123872", "987653" , "7625019", "028401"};

int i = accountList.FindIndex(x => x.StartsWith("762"));
//This will give you index of 7625019 in list that is 2. value of i will become 2.
//delegate(string ac)
//{
//    return ac.StartsWith(a.AccountNumber);
//}
//);

grant remote access of MySQL database from any IP address

For anyone who fumbled with this, here is how I got to grant the privileges, hope it helps someone

GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY
'yourRootPassword';

As noted % is a wildcard and this will allow any IP address to connect to your database. The assumption I make here is when you connect you'll have a user named root (which is the default though). Feed in the root password and you are good to go. Note that I have no single quotes (') around the user root.

Two submit buttons in one form

Since you didn't specify what server-side scripting method you're using, I'll give you an example that works for Python, using CherryPy (although it may be useful for other contexts, too):

<button type="submit" name="register">Create a new account</button>
<button type="submit" name="login">Log into your account</button>

Rather than using the value to determine which button was pressed, you can use the name (with the <button> tag instead of <input>). That way, if your buttons happen to have the same text, it won't cause problems. The names of all form items, including buttons, are sent as part of the URL. In CherryPy, each of those is an argument for a method that does the server-side code. So, if your method just has **kwargs for its parameter list (instead of tediously typing out every single name of each form item) then you can check to see which button was pressed like this:

if "register" in kwargs:
    pass #Do the register code
elif "login" in kwargs:
    pass #Do the login code

Uses of Action delegate in C#

MSDN says:

This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.

Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.

What is the C# equivalent of NaN or IsNumeric?

This doesn't have the regex overhead

double myNum = 0;
String testVar = "Not A Number";

if (Double.TryParse(testVar, out myNum)) {
  // it is a number
} else {
  // it is not a number
}

Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.

update
secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.

example 1:

public Boolean IsNumber(String s) {
  Boolean value = true;
  foreach(Char c in s.ToCharArray()) {
    value = value && Char.IsDigit(c);
  }

  return value;
}

or if you want to be a little more fancy

public Boolean IsNumber(String value) {
  return value.All(Char.IsDigit);
}

update 2 ( from @stackonfire to deal with null or empty strings)

public Boolean IsNumber(String s) { 
    Boolean value = true; 
    if (s == String.Empty || s == null) { 
        value=false; 
    } else { 
        foreach(Char c in s.ToCharArray()) { 
            value = value && Char.IsDigit(c); 
        } 
    } return value; 
}

less than 10 add 0 to number

A single regular expression replace should do it:

var stringWithSmallIntegers = "4° 7' 34"W, 168° 1' 23"N";

var paddedString = stringWithSmallIntegers.replace(
    /\d+/g,
    function pad(digits) {
        return digits.length === 1 ? '0' + digits : digits;
    });

alert(paddedString);

shows the expected output.

.prop('checked',false) or .removeAttr('checked')?

use checked : true, false property of the checkbox.

jQuery:

if($('input[type=checkbox]').is(':checked')) {
    $(this).prop('checked',true);
} else {
    $(this).prop('checked',false);
}

Check if Key Exists in NameValueCollection

If the collection size is small you could go with the solution provided by rich.okelly. However, a large collection means that the generation of the dictionary may be noticeably slower than just searching the keys collection.

Also, if your usage scenario is searching for keys in different points in time, where the NameValueCollection may have been modified, generating the dictionary each time may, again, be slower than just searching the keys collection.

How do you update a DateTime field in T-SQL?

That should work, I'd put brackets around [Date] as it's a reserved keyword.

How to determine if a type implements an interface with C# reflection

Use Type.IsAssignableFrom:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType));

How to deal with page breaks when printing a large HTML table

The accepted answer did not work for me in all browsers, but following css did work for me:

tr    
{ 
  display: table-row-group;
  page-break-inside:avoid; 
  page-break-after:auto;
}

The html structure was:

<table>
  <thead>
    <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
    <tr></tr>
    ...
  </tbody>
</table>

In my case, there were some additional issues with the thead tr, but this resolved the original issue of keeping the table rows from breaking.

Because of the header issues, I ultimately ended up with:

#theTable td *
{
  page-break-inside:avoid;
}

This didn't prevent rows from breaking; just each cell's content.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{
    Layout = "~/Views/Shared/_PublicLayout.cshtml";
}

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

How to read and write into file using JavaScript?

You'll have to turn to Flash, Java or Silverlight. In the case of Silverlight, you'll be looking at Isolated Storage. That will get you write to files in your own playground on the users disk. It won't let you write outside of your playground though.

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

How can I remove the last character of a string in python?

The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]

Difference Between One-to-Many, Many-to-One and Many-to-Many?

Looks like everyone is answering One-to-many vs. Many-to-many:

The difference between One-to-many, Many-to-one and Many-to-Many is:

One-to-many vs Many-to-one is a matter of perspective. Unidirectional vs Bidirectional will not affect the mapping but will make difference on how you can access your data.

  • In Many-to-one the many side will keep reference of the one side. A good example is "A State has Cities". In this case State is the one side and City is the many side. There will be a column state_id in the table cities.

In unidirectional, Person class will have List<Skill> skills but Skill will not have Person person. In bidirectional, both properties are added and it allows you to access a Person given a skill( i.e. skill.person).

  • In One-to-Many the one side will be our point of reference. For example, "A User has Addresses". In this case we might have three columns address_1_id, address_2_id and address_3_id or a look up table with multi column unique constraint on user_id on address_id.

In unidirectional, a User will have Address address. Bidirectional will have an additional List<User> users in the Address class.

  • In Many-to-Many members of each party can hold reference to arbitrary number of members of the other party. To achieve this a look up table is used. Example for this is the relationship between doctors and patients. A doctor can have many patients and vice versa.

Why does the JFrame setSize() method not set the size correctly?

JFrame SetSize() contains the the Area + Border.

I think you have to set the size of ContentPane of that

jFrame.getContentPane().setSize(800,400);

So I would advise you to use JPanel embedded in a JFrame and you draw on that JPanel. This would minimize your problem.

JFrame jf = new JFrame();
JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(400,800));// changed it to preferredSize, Thanks!
jf.getContentPane().add( jp );// adding to content pane will work here. Please read the comment bellow.
jf.pack();

I am reading this from Javadoc

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

frame.add(child);

However using JFrame you need to add the child to the JFrame's content pane instead:

frame.getContentPane().add(child);

How to assign a select result to a variable?

DECLARE @tmp_key int
DECLARE @get_invckey cursor 

SET @get_invckey = CURSOR FOR 
    SELECT invckey FROM tarinvoice WHERE confirmtocntctkey IS NULL AND tranno LIKE '%115876'

OPEN @get_invckey 

FETCH NEXT FROM @get_invckey INTO @tmp_key

DECLARE @PrimaryContactKey int --or whatever datatype it is

WHILE (@@FETCH_STATUS = 0) 
BEGIN 
    SELECT @PrimaryContactKey=c.PrimaryCntctKey
    FROM tarcustomer c, tarinvoice i
    WHERE i.custkey = c.custkey AND i.invckey = @tmp_key

    UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey WHERE invckey = @tmp_key
    FETCH NEXT FROM @get_invckey INTO @tmp_key
END 

CLOSE @get_invckey
DEALLOCATE @get_invckey

EDIT:
This question has gotten a lot more traction than I would have anticipated. Do note that I'm not advocating the use of the cursor in my answer, but rather showing how to assign the value based on the question.

JUnit Testing private variables?

First of all, you are in a bad position now - having the task of writing tests for the code you did not originally create and without any changes - nightmare! Talk to your boss and explain, it is not possible to test the code without making it "testable". To make code testable you usually do some important changes;

Regarding private variables. You actually never should do that. Aiming to test private variables is the first sign that something wrong with the current design. Private variables are part of the implementation, tests should focus on behavior rather of implementation details.

Sometimes, private field are exposed to public access with some getter. I do that, but try to avoid as much as possible (mark in comments, like 'used for testing').

Since you have no possibility to change the code, I don't see possibility (I mean real possibility, not like Reflection hacks etc.) to check private variable.

Arguments to main in C

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

Load a bitmap image into Windows Forms using open file dialog

Works Fine. Try this,

private void addImageButton_Click(object sender, EventArgs e)
{
    OpenFileDialog of = new OpenFileDialog();
    //For any other formats
    of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG"; 
    if (of.ShowDialog() == DialogResult.OK)
    {
        pictureBox1.ImageLocation = of.FileName;

    }
}

Clear form fields with jQuery

For jQuery 1.6+:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);

For jQuery < 1.6:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Please see this post: Resetting a multi-stage form with jQuery

Or

$('#myform')[0].reset();

As jQuery suggests:

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

how to count the total number of lines in a text file using python

this one also gives the no.of lines in a file.

a=open('filename.txt','r')
l=a.read()
count=l.splitlines()
print(len(count))

SQL Server Regular expressions in T-SQL

In case anyone else is still looking at this question, http://www.sqlsharp.com/ is a free, easy way to add regular expression CLR functions into your database.

How does Git handle symbolic links?

You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?

To find out, first, make a symbolic link:

$ ln -s /path/referenced/by/symlink symlink

Git doesn't know about this file yet. git ls-files lets you inspect your index (-s prints stat-like output):

$ git ls-files -s ./symlink
[nothing]

Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.

$ git add ./symlink

So, what was added?

$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0       symlink

The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file:

$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink

(Note 120000 is the mode listed in ls-files output. It would be something like 100644 for a regular file.)

But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks config. From man git-config:

core.symlinks

If false, symbolic links are checked out as small plain files that contain the link text.

So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks config.

Either way, the data referenced by the symlink is not stored in the repository.

MySQL LEFT JOIN 3 tables

Select Persons.Name, Persons.SS, Fears.Fear
From Persons
LEFT JOIN Persons_Fear
ON Persons.PersonID = Person_Fear.PersonID
LEFT JOIN Fears
ON Person_Fear.FearID = Fears.FearID;

How to find the 'sizeof' (a pointer pointing to an array)?

There is a clean solution with C++ templates, without using sizeof(). The following getSize() function returns the size of any static array:

#include <cstddef>

template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
    return SIZE;
}

Here is an example with a foo_t structure:

#include <cstddef>

template<typename T, size_t SIZE>
size_t getSize(T (&)[SIZE]) {
    return SIZE;
}

struct foo_t {
    int ball;
};

int main()
{
    foo_t foos3[] = {{1},{2},{3}};
    foo_t foos5[] = {{1},{2},{3},{4},{5}};
    printf("%u\n", getSize(foos3));
    printf("%u\n", getSize(foos5));

    return 0;
}

Output:

3
5

c# open a new form then close the current form?

Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main, form2 can simply be created using Application.Run just like form1 before. Here's an example scenario:

I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I'm using two forms: LogingForm and MainForm. The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here's the code for this:

class LoginForm : Form
{
    public bool UserSuccessfullyAuthenticated { get; private set; }

    void LoginButton_Click(object s, EventArgs e)
    {
        if(AuthenticateUser(/* ... */))
        {
            UserSuccessfullyAuthenticated = true;
            Close();
        }
    }
}

static class Program
{
    [STAThread]
    static void Main()
    {
        LoginForm loginForm = new LoginForm();
        Application.Run(loginForm);

        if(loginForm.UserSuccessfullyAuthenticated)
        {
            // MainForm is defined elsewhere
            Application.Run(new MainForm());
        }
    }
}

Python pandas Filtering out nan from a data selection of a column of strings

Simplest of all solutions:

filtered_df = df[df['name'].notnull()]

Thus, it filters out only rows that doesn't have NaN values in 'name' column.

For multiple columns:

filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]

count number of rows in a data frame in R based on group

Here is another way of using aggregate to count rows by group:

my.data <- read.table(text = '
    month.year    my.cov
      Jan.2000     apple
      Jan.2000      pear
      Jan.2000     peach
      Jan.2001     apple
      Jan.2001     peach
      Feb.2002      pear
', header = TRUE, stringsAsFactors = FALSE, na.strings = NA)

rows.per.group  <- aggregate(rep(1, length(my.data$month.year)),
                             by=list(my.data$month.year), sum)
rows.per.group

#    Group.1 x
# 1 Feb.2002 1
# 2 Jan.2000 3
# 3 Jan.2001 2

Adding an .env file to React Project

Today there is a simpler way to do that.

Just create the .env.local file in your root directory and set the variables there. In your case:

REACT_APP_API_KEY = 'my-secret-api-key'

Then you call it en your js file in that way:

process.env.REACT_APP_API_KEY

React supports environment variables since [email protected] .You don't need external package to do that.

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables#adding-development-environment-variables-in-env

*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.

Files priority:

npm start: .env.development.local, .env.development, .env.local, .env

npm run build: .env.production.local, .env.production, .env.local, .env

npm test: .env.test.local, .env.test, .env (note .env.local is missing)

More info: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

How to multiply duration by integer?

int32 and time.Duration are different types. You need to convert the int32 to a time.Duration, such as time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond).

How to remove all options from a dropdown using jQuery / JavaScript

Try this

function removeElements(){
    $('#models').html("");
}

android get all contacts

This is the Method to get contact list Name and Number

 private void getAllContacts() {
    ContentResolver contentResolver = getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if (hasPhoneNumber > 0) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                Cursor phoneCursor = contentResolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
                        null);
                if (phoneCursor != null) {
                    if (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

   //At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
                        phoneCursor.close();
                    }


                }
            }
        }
    }
}

In Powershell what is the idiomatic way of converting a string to an int?

For me $numberAsString -as [int] of @Shay Levy is the best practice, I also use [type]::Parse(...) or [type]::TryParse(...)

But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an Int32:

PS > $b = "10"
PS > $a = 0 + $b
PS > $a.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType

You can use Exception (try/parse) to behave in case of Problem

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Convert data file to blob

async function FileToString (file) {
    try {
        let res = await file.raw.text();
        console.log(res);
    } catch (err) {
        throw err;
    }
}

select unique rows based on single distinct column

I'm assuming you mean that you don't care which row is used to obtain the title, id, and commentname values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:

select
    id,
    title,
    email,
    commentname

from
(
select 
    *, 
    row_number() over (partition by email order by id) as RowNbr 

from YourTable
) source

where RowNbr = 1

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

How to select rows in a DataFrame between two values, in Python Pandas?

there is a nicer alternative - use query() method:

In [58]: df = pd.DataFrame({'closing_price': np.random.randint(95, 105, 10)})

In [59]: df
Out[59]:
   closing_price
0            104
1             99
2             98
3             95
4            103
5            101
6            101
7             99
8             95
9             96

In [60]: df.query('99 <= closing_price <= 101')
Out[60]:
   closing_price
1             99
5            101
6            101
7             99

UPDATE: answering the comment:

I like the syntax here but fell down when trying to combine with expresison; df.query('(mean + 2 *sd) <= closing_price <=(mean + 2 *sd)')

In [161]: qry = "(closing_price.mean() - 2*closing_price.std())" +\
     ...:       " <= closing_price <= " + \
     ...:       "(closing_price.mean() + 2*closing_price.std())"
     ...:

In [162]: df.query(qry)
Out[162]:
   closing_price
0             97
1            101
2             97
3             95
4            100
5             99
6            100
7            101
8             99
9             95

set the iframe height automatically

If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.

How do I convert a calendar week into a date in Excel?

If A1 has the week number and year as a 3 or 4 digit integer in the format wwYY then the formula would be:

=INT(A1/100)*7+DATE(MOD([A1,100),1,1)-WEEKDAY(DATE(MOD(A1,100),1,1))-5

the subtraction of the weekday ensures you return a consistent start day of the week. Use the final subtraction to adjust the start day.

Swift Alamofire: How to get the HTTP response status code

you may check the following code for status code handler by alamofire

    let request = URLRequest(url: URL(string:"url string")!)    
    Alamofire.request(request).validate(statusCode: 200..<300).responseJSON { (response) in
        switch response.result {
        case .success(let data as [String:Any]):
            completion(true,data)
        case .failure(let err):
            print(err.localizedDescription)
            completion(false,err)
        default:
            completion(false,nil)
        }
    }

if status code is not validate it will be enter the failure in switch case

Copying one structure to another

You can use the following solution to accomplish your goal:

struct student 
{
    char name[20];
    char country[20];
};
void main()
{
    struct student S={"Wolverine","America"};
    struct student X;
    X=S;
    printf("%s%s",X.name,X.country);
}

React eslint error missing in props validation

You need to define propTypes as a static getter if you want it inside the class declaration:

static get propTypes() { 
    return { 
        children: PropTypes.any, 
        onClickOut: PropTypes.func 
    }; 
}

If you want to define it as an object, you need to define it outside the class, like this:

IxClickOut.propTypes = {
    children: PropTypes.any,
    onClickOut: PropTypes.func,
};

Also it's better if you import prop types from prop-types, not react, otherwise you'll see warnings in console (as preparation for React 16):

import PropTypes from 'prop-types';

How to start and stop android service from a adb shell?

For anyone still confused about how to define the service name parameter, the forward slash goes immediately after the application package name in the fully qualified class name.

So given an application package name of: app.package.name

And a full path to the service of: app.package.name.example.package.path.MyServiceClass

Then the command would look like this:

adb shell am startservice app.package.name/.example.package.path.MyServiceClass

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

How can I set the color of a selected row in DataGrid

Got it. Add the following within the DataGrid.Resources section:

  <DataGrid.Resources>
     <Style TargetType="{x:Type dg:DataGridCell}">
        <Style.Triggers>
            <Trigger Property="dg:DataGridCell.IsSelected" Value="True">
                <Setter Property="Background" Value="#CCDAFF" />
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

Sorted collection in Java

The most efficient way to implement a sorted list like you want would be to implement an indexable skiplist as in here: Wikipedia: Indexable skiplist. It would allow to have inserts/removals in O(log(n)) and would allow to have indexed access at the same time. And it would also allow duplicates.

Skiplist is a pretty interesting and, I would say, underrated data structure. Unfortunately there is no indexed skiplist implementation in Java base library, but you can use one of open source implementations or implement it yourself. There are regular Skiplist implementations like ConcurrentSkipListSet and ConcurrentSkipListMap

Ansible: get current target host's IP address

Another way to find public IP would be to use uri module:

    - name: Find my public ip
      uri: 
        url: http://ifconfig.me/ip
        return_content: yes
      register: ip_response

Your IP will be in ip_response.content

How to import existing Git repository into another?

Adding another answer as I think this is a bit simpler. A pull of repo_dest is done into repo_to_import and then a push --set-upstream url:repo_dest master is done.

This method has worked for me importing several smaller repos into a bigger one.

How to import: repo1_to_import to repo_dest

# checkout your repo1_to_import if you don't have it already 
git clone url:repo1_to_import repo1_to_import
cd repo1_to_import

# now. pull all of repo_dest
git pull url:repo_dest
ls 
git status # shows Your branch is ahead of 'origin/master' by xx commits.
# now push to repo_dest
git push --set-upstream url:repo_dest master

# repeat for other repositories you want to import

Rename or move files and dirs into desired position in original repo before you do the import. e.g.

cd repo1_to_import
mkdir topDir
git add topDir
git mv this that and the other topDir/
git commit -m"move things into topDir in preparation for exporting into new repo"
# now do the pull and push to import

The method described at the following link inspired this answer. I liked it as it seemed more simple. BUT Beware! There be dragons! https://help.github.com/articles/importing-an-external-git-repository git push --mirror url:repo_dest pushes your local repo history and state to remote (url:repo_dest). BUT it deletes the old history and state of the remote. Fun ensues! :-E

Is there a combination of "LIKE" and "IN" in SQL?

With PostgreSQL there is the ANY or ALL form:

WHERE col LIKE ANY( subselect )

or

WHERE col LIKE ALL( subselect )

where the subselect returns exactly one column of data.

How to set the size of a column in a Bootstrap responsive table

you can use the following Bootstrap class with

<tr class="w-25">

</tr>

for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/

How to create string with multiple spaces in JavaScript

In 2021 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.

let a = `something       something`;

Template Literals are fast, powerful and produce cleaner code.


If you need IE11 support and you don't have transpiler, stay strong and use \xa0 - it is a NO-BREAK SPACE char.

Reference from UTF-8 encoding table and Unicode characters, you can write as below:

var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';

How can I use a carriage return in a HTML tooltip?

As of Firefox 12 they now support line breaks using the line feed HTML entity: &#10;

<span title="First line&#10;Second line">Test</span>

This works in IE and is the correct according to the HTML5 spec for the title attribute.

How do I remove background-image in css?

div#a {
  background-image: url('../images/spacer.png');
  background-image: none !important;
}

I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none even though it is marked !important.

LINQ to Entities how to update a record

They both track your changes to the collection, just call the SaveChanges() method that should update the DB.

Is there any way to configure multiple registries in a single npmrc file

As of 13 April 2020 there is no such functionality unless you are able to use different scopes, but you may use the postinstall script as a workaround. It is always executed, well, after each npm install:

Say you have your .npmrc configured to install @foo-org/foo-pack-private from your private github repo, but the @foo-org/foo-pack-public public package is on npm (under the same scope: foo-org).

Your postinstall might look like this:

"scripts": {
    ...
    "postinstall": "mv .npmrc .npmrcc && npm i @foo-org/foo-pack --dry-run && mv .npmrcc .npmrc".
}

Don't forget to remove @foo-pack/foo-org from the dependencies array to make sure npm install does not try and get it from github and to add the --dry-run flag that makes sure package.json and package-lock.json stay unchanged after npm install.

Create line after text with css

using flexbox:

h2 {
    display: flex;
    align-items: center;

}

h2 span {
    content:"";
    flex: 1 1 auto;
    border-top: 1px solid #000;
}

html:

<h2>Title <span></span></h2>

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

FYI, another way this exception can occur is if:

  • Your transaction isolation is READ_COMMITTED
  • Transaction #1 queries for an entity, then deletes that entity
  • A simultaneous transaction #2 does the same thing

Then this can happen: TX #1 successfully commits before TX #2, then when TX #2 tries to delete the entity (again) it's not there any more - even though it was found by a query earlier in that same transaction. Note this anomaly is allowed with READ_COMMITTED isolation.

In my case the resulting exception looked like this:

HHH000315: Exception executing batch [org.hibernate.StaleStateException:
  Batch update returned unexpected row count from update [0]; actual row
  count: 0; expected: 1; statement executed: delete from Foobar where id=?],
  SQL: delete from Foobar where id=?

CentOS 64 bit bad ELF interpreter

You can also install OpenJDK 32-bit (.i686) instead. According to my test, it will be installed and works without problems.

sudo yum install java-1.8.0-openjdk.i686

Note:

The java-1.8.0-openjdk package contains just the Java Runtime Environment. If you want to develop Java programs then install the java-1.8.0-openjdk-devel package.

See here for more details.

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

Component based game engine design

Update 2013-01-07: If you want to see a good mix of component-based game engine with the (in my opinion) superior approach of reactive programming take a look at the V-Play engine. It very well integrates QTs QML property binding functionality.

We did some research on CBSE in games at our university and I collected some material over the years:

CBSE in games literature:

  • Game Engine Architecture
  • Game Programming Gems 4: A System for Managin Game Entities Game
  • Game Programming Gems 5: Component Based Object Management
  • Game Programming Gems 5: A Generic Component Library
  • Game Programming Gems 6: Game Object Component System
  • Object-Oriented Game Development
  • Architektur des Kerns einer Game-Engine und Implementierung mit Java (german)

A very good and clean example of a component-based game-engine in C# is the Elephant game framework.

If you really want to know what components are read: Component-based Software Engineering! They define a component as:

A software component is a software element that conforms to a component model and can be independently deployed and composed without modification according to a composition standard.

A component model defines specific interaction and composition standards. A component model implementation is the dedicated set of executable software elements required to support the execution of components that conform to the model.

A software component infrastructure is a set of interacting software components designed to ensure that a software system or subsystem constructed using those components and interfaces will satisfy clearly defined performance specifications.

My opinions after 2 years of experience with CBSE in games thought are that object-oriented programming is simply a dead-end. Remember my warning as you watch your components become smaller and smaller, and more like functions packed in components with a lot of useless overhead. Use functional-reactive programming instead. Also take a look at my fresh blog post (which lead me to this question while writing it :)) about Why I switched from component-based game engine architecture to FRP.

CBSE in games papers:

CBSE in games web-links (sorted by relevancy):

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

How to get past the login page with Wget?

Based on the manual page:

# Log in to the server.  This only needs to be done once.
wget --save-cookies cookies.txt \
     --keep-session-cookies \
     --post-data 'user=foo&password=bar' \
     --delete-after \
     http://server.com/auth.php

# Now grab the page or pages we care about.
wget --load-cookies cookies.txt \
     http://server.com/interesting/article.php

Make sure the --post-data parameter is properly percent-encoded (especially ampersands!) or the request will probably fail. Also make sure that user and password are the correct keys; you can find out the correct keys by sleuthing the HTML of the login page (look into your browser’s “inspect element” feature and find the name attribute on the username and password fields).

UIView frame, bounds and center

I found this image most helpful for understanding frame, bounds, etc.

enter image description here

Also please note that frame.size != bounds.size when the image is rotated.

Output data from all columns in a dataframe in pandas

you can also use DataFrame.head(x) / .tail(x) to display the first / last x rows of the DataFrame.

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

How can I setup & run PhantomJS on Ubuntu?

For Ubuntu, download the suitable file from http://phantomjs.org/download.html. CD to the downloaded folder. Then:

sudo tar xvf phantomjs-1.9.0-linux-x86_64.tar.bz2
sudo mv phantomjs-1.9.0-linux-x86_64 /usr/local/share/phantomjs
sudo ln -s /usr/local/share/phantomjs/bin/phantomjs /usr/bin/phantomjs

Make sure to replace the file name in these commands with the file you have downloaded.

Downloading MySQL dump from command line

If downloading from remote server, here is a simple example:

mysqldump -h my.address.amazonaws.com -u my_username -p db_name > /home/username/db_backup_name.sql

The -p indicates you will enter a password, it does not relate to the db_name. After entering the command you will be prompted for the password. Type it in and press enter.

Converting int to string in C

Use snprintf, it is more portable than itoa.

itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.

Example of sprintf

char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

Example of snprintf

char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);

Both functions are similar to fprintf, but output is written into an array rather than to a stream. The difference between sprintf and snprintf is that snprintf guarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer.

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

Styling JQuery UI Autocomplete

Bootstrap styling for jQuery UI Autocomplete

    .ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;   
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
}

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
}

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
}

How to set default value to all keys of a dict object in python?

You can replace your old dictionary with a defaultdict:

>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1

The "trick" here is that a defaultdict can be initialized with another dict. This means that you preserve the existing values in your normal dict:

>>> d['foo']
123

How to find a whole word in a String in java

Looking back at the original question, we need to find some given keywords in a given sentence, count the number of occurrences and know something about where. I don't quite understand what "where" means (is it an index in the sentence?), so I'll pass that one... I'm still learning java, one step at a time, so I'll see to that one in due time :-)

It must be noticed that common sentences (as the one in the original question) can have repeated keywords, therefore the search cannot just ask if a given keyword "exists or not" and count it as 1 if it does exist. There can be more then one of the same. For example:

// Base sentence (added punctuation, to make it more interesting):
String sentence = "Say that 123 of us will come by and meet you, "
                + "say, at the woods of 123woods.";

// Split it (punctuation taken in consideration, as well):
java.util.List<String> strings = 
                       java.util.Arrays.asList(sentence.split(" |,|\\."));

// My keywords:
java.util.ArrayList<String> keywords = new java.util.ArrayList<>();
keywords.add("123woods");
keywords.add("come");
keywords.add("you");
keywords.add("say");

By looking at it, the expected result would be 5 for "Say" + "come" + "you" + "say" + "123woods", counting "say" twice if we go lowercase. If we don't, then the count should be 4, "Say" being excluded and "say" included. Fine. My suggestion is:

// Set... ready...?
int counter = 0;

// Go!
for(String s : strings)
{
    // Asking if the sentence exists in the keywords, not the other
    // around, to find repeated keywords in the sentence.
    Boolean found = keywords.contains(s.toLowerCase());
    if(found)
    {
        counter ++;
        System.out.println("Found: " + s);
    }
}

// Statistics:
if (counter > 0)
{
    System.out.println("In sentence: " + sentence + "\n"
                     + "Count: " + counter);
}

And the results are:

Found: Say
Found: come
Found: you
Found: say
Found: 123woods
In sentence: Say that 123 of us will come by and meet you, say, at the woods of 123woods.
Count: 5

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

How to convert a String to JsonObject using gson library

To do it in a simpler way, consider below:

JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();

Convert dd-mm-yyyy string to date

You can just:

var f = new Date(from.split('-').reverse().join('/'));

getting the X/Y coordinates of a mouse click on an image with jQuery

Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset();
            var x = ev.clientX - offset.left;
            var y = ev.clientY - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.

In this case, you should also use $div.outerWidth(true) - $div.width() and $div.outerHeight(true) - $div.height() to calculate the amount of margin / border / etc.

Your new code might look more like:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset(); // Offset from the corner of the page.
            var xMargin = ($img.outerWidth() - $img.width()) / 2;
            var yMargin = ($img.outerHeight() - $img.height()) / 2;
            // Note that the above calculations assume your left margin is 
            // equal to your right margin, top to bottom, etc. and the same 
            // for borders.

            var x = (ev.clientX + xMargin) - offset.left;
            var y = (ev.clientY + yMargin) - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

How can one change the timestamp of an old commit in Git?

To change both the author date and the commit date:

GIT_COMMITTER_DATE="Wed Sep 23 9:40 2015 +0200" git commit --amend --date "Wed Sep 23 9:40 2015 +0200"

How to check a Long for null in java

As mentioned already primitives can not be set to the Object type null.

What I do in such cases is just to use -1 or Long.MIN_VALUE.

Equivalent of Math.Min & Math.Max for Dates?

How about a DateTime extension method?

public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
    return instance > dateTime ? instance : dateTime;
}

Usage:

var maxDate = date1.MaxOf(date2);

Getting the first index of an object

My solution:

Object.prototype.__index = function(index)
{
    var i = -1;
    for (var key in this)
    {
        if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
            ++i;
        if (i >= index)
            return this[key];
    }
    return null;
}
aObj = {'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));

Angularjs ng-model doesn't work inside ng-if

You can do it like this and you mod function will work perfect let me know if you want a code pen

  <div ng-repeat="icon in icons">                   
                <div class="row" ng-if="$index % 3 == 0 ">
                    <i class="col col-33 {{icons[$index + n].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 1].icon}} custom-icon"></i>
                    <i class="col col-33 {{icons[$index + n + 2].icon}} custom-icon"></i>
                </div>
         </div>

Easiest way to convert a List to a Set in Java

With Java 10, you could now use Set#copyOf to easily convert a List<E> to an unmodifiable Set<E>:

Example:

var set = Set.copyOf(list);

Keep in mind that this is an unordered operation, and null elements are not permitted, as it will throw a NullPointerException.

If you wish for it to be modifiable, then simply pass it into the constructor a Set implementation.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.

UPDATE table_mame SET field_name= 0;

After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.

ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;

I think it will help you.

Updating state on props change in React Form

From react documentation : https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

Erasing state when props change is an Anti Pattern

Since React 16, componentWillReceiveProps is deprecated. From react documentation, the recommended approach in this case is use

  1. Fully controlled component: the ParentComponent of the ModalBody will own the start_time state. This is not my prefer approach in this case since i think the modal should own this state.
  2. Fully uncontrolled component with a key: this is my prefer approach. An example from react documentation : https://codesandbox.io/s/6v1znlxyxn . You would fully own the start_time state from your ModalBody and use getInitialState just like you have already done. To reset the start_time state, you simply change the key from the ParentComponent

JavaScript window resize event

The already mentioned solutions above will work if all you want to do is resize the window and window only. However, if you want to have the resize propagated to child elements, you will need to propagate the event yourself. Here's some example code to do it:

window.addEventListener("resize", function () {
  var recResizeElement = function (root) {
    Array.prototype.forEach.call(root.childNodes, function (el) {

      var resizeEvent = document.createEvent("HTMLEvents");
      resizeEvent.initEvent("resize", false, true);
      var propagate = el.dispatchEvent(resizeEvent);

      if (propagate)
        recResizeElement(el);
    });
  };
  recResizeElement(document.body);
});

Note that a child element can call

 event.preventDefault();

on the event object that is passed in as the first Arg of the resize event. For example:

var child1 = document.getElementById("child1");
child1.addEventListener("resize", function (event) {
  ...
  event.preventDefault();
});

Set Value of Input Using Javascript Function

Depending on the usecase it makes a difference whether you use javascript (element.value = x) or jQuery $(element).val(x);

When x is undefined jQuery results in an empty String whereas javascript results in "undefined" as a String.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

In MS Windows the temporary directory is set by the environment variable TEMP. In XP, the temporary directory was set per-user as Local Settings\Temp.

If you change your TEMP environment variable to C:\temp, then you get the same when you run :

System.out.println(System.getProperty("java.io.tmpdir"));

Python executable not finding libpython shared library

just install python-lib. (python27-lib). It will install libpython2.7.so1.0. We don't require to manually set anything.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

Android Studio Emulator and "Process finished with exit code 0"

This can be solved by the following step:

Please ensure "Windows Hypervisor Platform" is installed. If it's not installed, install it, restart your computer and you will be good to go.

enter image description here

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

php date validation

We can use simple "date" input type, like below:

Birth date: <input type="date" name="userBirthDate" /><br />

Then we can link DateTime interface with built-in function 'explode':

public function validateDate()
    {
        $validateFlag = true;
        $convertBirthDate = DateTime::createFromFormat('Y-m-d', $this->birthDate);
        $birthDateErrors = DateTime::getLastErrors();

        if ($birthDateErrors['warning_count'] + $birthDateErrors['error_count'] > 0)
        {
            $_SESSION['wrongDateFormat'] = "The date format is wrong.";
        }

        else
        {
            $testBirthDate = explode('-', $this->birthDate);
            if ($testBirthDate[0] < 1900)
            {
                $validateFlag = false;
                $_SESSION['wrongDateYear'] = "We suspect that you did not born before XX century.";
            }
        }

        return $validateFlag;
    }

I tested it on Google Chrome and IE, everything works correctly. Furthemore, Chrome display simple additional interface. If you don't write anything in input or write it in bad format (correctly is following: '1919-12-23'), you will get the first statement. If you write everything in good format, but you type wrong date (I assumed that nobody could born before XX century), your controller will send the second statement.

How to create a .gitignore file

windows: in the commandline:

.>.gitignore

this will show an error but will work

npm install doesn't create node_modules directory

npm init

It is all you need. It will create the package.json file on the fly for you.

Tool to generate JSON schema from JSON data

json-schema-generator is a neat Ruby based JSON schema generator. It supports both draft 3 and 4 of the JSON schema. It can be run as a standalone executable, or it can be embedded inside of a Ruby script.

Then you can use json-schema to validate JSON samples against your newly generated schema if you want.

Programmatic equivalent of default(Type)

Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:

    public object GetDefault(Type t)
    {
        return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
    }

    public T GetDefaultGeneric<T>()
    {
        return default(T);
    }

Django template how to look up a dictionary value with a variable

Fetch both the key and the value from the dictionary in the loop:

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.

How to record phone calls in android?

Below code is working for me to record a outgoing phone call

//Call Recording varibales
private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";

private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
        MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
        AUDIO_RECORDER_FILE_EXT_3GP };

AudioManager audioManager;

//put this methods to outside of oncreate() method

private String getFilename() {
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath, AUDIO_RECORDER_FOLDER);

    if (!file.exists()) {
        file.mkdirs();
    }

    return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        Toast.makeText(CallActivity.this,
                "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        Toast.makeText(CallActivity.this,
                "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
                .show();
    }
};

//below part of code to make your device on speaker

    audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE); 
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    audioManager.setSpeakerphoneOn(true);

//below part of code to start recording

recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(output_formats[currentFormat]);
    //recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(getFilename());
    recorder.setOnErrorListener(errorListener);
    recorder.setOnInfoListener(infoListener);

    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException e) {
         Log.e("REDORDING :: ",e.getMessage());
            e.printStackTrace();
    } catch (IOException e) {
        Log.e("REDORDING :: ",e.getMessage());
        e.printStackTrace();
    }

//For stop recording and keep in mind to set speaker off while call end or stop

audioManager.setSpeakerphoneOn(false);

    try{
        if (null != recorder) {
            recorder.stop();
            recorder.reset();
            recorder.release();

            recorder = null;
        }
    }catch(RuntimeException stopException){

    }

And give permission to manifest file,

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Python unexpected EOF while parsing

Indent it! first. That would take care of your SyntaxError.

Apart from that there are couple of other problems in your program.

  • Use raw_input when you want accept string as an input. input takes only Python expressions and it does an eval on them.

  • You are using certain 8bit characters in your script like . You might need to define the encoding at the top of your script using # -*- coding:latin-1 -*- line commonly called as coding-cookie.

  • Also, while doing str comparison, normalize the strings and compare. (people using lower() it) This helps in giving little flexibility with user input.

  • I also think that reading Python tutorial might helpful to you. :)

Sample Code

#-*- coding: latin1 -*-

while 1:
    date=raw_input("Example: March 21 | What is the date? ")
    if date.lower() == "march 21":

    ....

How can I get the current date and time in UTC or GMT in Java?

Here is another way to get GMT time in String format

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());

How do I install and use curl on Windows?

Follow download wizard

Follow the screens one by one to select type of package (curl executable), OS (Win64), flavor (Generic), CPU (x86_64) and the download link.

unzip download and find curl.exe (I found it in src folder, one may find it in bin folder for different OS/flavor)

To make it available from the command line, add the executable path to the system path (Adding directory to PATH Environment Variable in Windows).

Enjoy curl.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I also had the same problem and I resolved the same by the following method

svn resolve --accept=working <FILE/FOLDER NAME>
svn cleanup
svn update <FILE/FOLDER NAME>
svn commit <FILE/FOLDER NAME> -m "Comment"

Hope this will help you :)

How to get current user in asp.net core

I know there area lot of correct answers here, with respect to all of them I introduce this hack :

In StartUp.cs

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

and then everywhere you need HttpContext you can use :

httpContext = new HttpContextAccessor().HttpContext;

Hope it helps ;)

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 make UIButton's text alignment center? Using IB

UIButton will not support setTextAlignment. So You need to go with setContentHorizontalAlignment for button text alignment

For your reference

[buttonName setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];

Disable button in jQuery

Use .prop instead (and clean up your selector string):

function disable(i){
    $("#rbutton_"+i).prop("disabled",true);
}

generated HTML:

<button id="rbutton_1" onclick="disable(1)">Click me</button>
<!-- wrap your onclick in quotes -->

But the "best practices" approach is to use JavaScript event binding and this instead:

_x000D_
_x000D_
$('.rbutton').on('click',function() {_x000D_
    $(this).prop("disabled",true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<button class="rbutton">Click me</button>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/mblase75/2Nfu4/

How to read the content of a file to a string in C?

easy and neat(assuming contents in the file are less than 10000):

void read_whole_file(char fileName[1000], char buffer[10000])
{
    FILE * file = fopen(fileName, "r");
    if(file == NULL)
    {
        puts("File not found");
        exit(1);
    }
    char  c;
    int idx=0;
    while (fscanf(file , "%c" ,&c) == 1)
    {
        buffer[idx] = c;
        idx++;
    }
    buffer[idx] = 0;
}

How to use an array list in Java?

object get(int index) is used to return the object stored at the specified index within the invoking collection.

Code Snippet :

import java.util.*;


class main
{
    public static void main(String [] args)
    {
        ArrayList<String> arr = new ArrayList<String>();
        arr.add("Hello!");
        arr.add("Ishe");
        arr.add("Watson?");

        System.out.printf("%s\n",arr.get(2)); 

        for (String s : arr) 
        {
            System.out.printf("%s\n",s);
        } 
    }
}

Remove a HTML tag but keep the innerHtml

$('b').contents().unwrap();

This selects all <b> elements, then uses .contents() to target the text content of the <b>, then .unwrap() to remove its parent <b> element.


For the greatest performance, always go native:

var b = document.getElementsByTagName('b');

while(b.length) {
    var parent = b[ 0 ].parentNode;
    while( b[ 0 ].firstChild ) {
        parent.insertBefore(  b[ 0 ].firstChild, b[ 0 ] );
    }
     parent.removeChild( b[ 0 ] );
}

This will be much faster than any jQuery solution provided here.

What Scala web-frameworks are available?

It must be noted that there is also a considerable interest in Wicket and Scala. Wicket fits Scala suprisingly well. If you want to take advantage of the very mature Wicket project and its ecosystem (extensions) plus the concise syntax and productivity advantage of Scala, this one may be for you!

See also:

  1. Some prosa

  2. Presentation

  3. Some experience with Wicket and Scala

  4. Announcments with reference to the project for the glue code to bind Scala closures to models

Measuring execution time of a function in C++

I recommend using steady_clock which is guarunteed to be monotonic, unlike high_resolution_clock.

#include <iostream>
#include <chrono>

using namespace std;

unsigned int stopwatch()
{
    static auto start_time = chrono::steady_clock::now();

    auto end_time = chrono::steady_clock::now();
    auto delta    = chrono::duration_cast<chrono::microseconds>(end_time - start_time);

    start_time = end_time;

    return delta.count();
}

int main() {
  stopwatch(); //Start stopwatch
  std::cout << "Hello World!\n";
  cout << stopwatch() << endl; //Time to execute last line
  for (int i=0; i<1000000; i++)
      string s = "ASDFAD";
  cout << stopwatch() << endl; //Time to execute for loop
}

Output:

Hello World!
62
163514

How do I center content in a div using CSS?

Update 2020:

There are several options available*:

*Disclaimer: This list may not be complete.

Using Flexbox
Nowadays, we can use flexbox. It is quite a handy alternative to the css-transform option. I would use this solution almost always. If it is just one element maybe not, but for example if I had to support an array of data e.g. rows and columns and I want them to be relatively centered in the very middle.

_x000D_
_x000D_
.flexbox {
  display: flex;
  height: 100px;
  flex-flow: row wrap;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  /* default => flex: 0 1 auto */
  background-color: #fff;
  border: 1px dotted #333;
  box-sizing: border-box;
}
_x000D_
<div class="flexbox">
  <div class="item">I am centered in the middle.</div>
  <div class="item">I am centered in the middle, too.</div>
</div>
_x000D_
_x000D_
_x000D_


Using CSS 2D-Transform
This is still a good option, was also the accepted solution back in 2015. It is very slim and simple to apply and does not mess with the layouting of other elements.

_x000D_
_x000D_
.boxes {
  position: relative;
}

.box {
  position: relative;
  display: inline-block;
  float: left;
  width: 200px;
  height: 200px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  margin-bottom: 10px;
  background-color: #eaeaea;
}

.h-center {
  text-align: center;
}

.v-center span {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
}
_x000D_
<div class="boxes">
  <div class="box h-center">horizontally centered lorem ipsun dolor sit amet</div>
  <div class="box v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
  <div class="box h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>
_x000D_
_x000D_
_x000D_

Note: This does also work with :after and :before pseudo-elements.


Using Grid
This might just be an overkill, but it depends on your DOM. If you want to use grid anyway, then why not. It is very powerful alternative and you are really maximum flexible with the design.

Note: To align the items vertically we use flexbox in combination with grid. But we could also use display: grid on the items.

_x000D_
_x000D_
.grid {
  display: grid;
  width: 400px;
  grid-template-rows: 100px;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 3px;
  align-items: center;
  justify-content: center;
  background-color: #eaeaea;
  border: 1px dotted #333;
}

.item {
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dotted #333;
  box-sizing: border-box;
}

.item-large {
  height: 80px;
}
_x000D_
<div class="grid">
  <div class="item">Item 1</div>
  <div class="item item-large">Item 2</div>
  <div class="item">Item 3</div>
</div>
_x000D_
_x000D_
_x000D_


Further reading:

CSS article about grid
CSS article about flexbox
CSS article about centering without flexbox or grid

Array to String PHP?

Use implode

implode("|",$type);

tsconfig.json: Build:No inputs were found in config file

Ok, in 2021, with a <project>/src/index.ts file, the following worked for me:

If VS Code complains with No inputs were found in config file... then change the include to…

"include": ["./src/**/*.ts"]

Found the above as a comment of How to Write Node.js Applications in Typescript

How to get the size of the current screen in WPF?

If you use any full screen window (having its WindowState = WindowState.Maximized, WindowStyle = WindowStyle.None), you can wrap its contents in System.Windows.Controls.Canvas like this:

<Canvas Name="MyCanvas" Width="auto" Height="auto">
...
</Canvas>

Then you can use MyCanvas.ActualWidth and MyCanvas.ActualHeight to get the resolution of the current screen, with DPI settings taken into account and in device independent units. It doesn't add any margins as the maximized window itself does.

(Canvas accepts UIElements as children, so you should be able to use it with any content.)

How to add jQuery code into HTML Page

  1. Create a file for the jquery eg uploadfuntion.js.
  2. Save that file in the same folder as website or in subfolder.
  3. In head section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

and then the reference to your script eg: <script src="uploadfuntion.js"> </script>

4.Lastly you should ensure there are elements that match the selectors in the code.

Difference between UTF-8 and UTF-16?

I believe there are a lot of good articles about this around the Web, but here is a short summary.

Both UTF-8 and UTF-16 are variable length encodings. However, in UTF-8 a character may occupy a minimum of 8 bits, while in UTF-16 character length starts with 16 bits.

Main UTF-8 pros:

  • Basic ASCII characters like digits, Latin characters with no accents, etc. occupy one byte which is identical to US-ASCII representation. This way all US-ASCII strings become valid UTF-8, which provides decent backwards compatibility in many cases.
  • No null bytes, which allows to use null-terminated strings, this introduces a great deal of backwards compatibility too.
  • UTF-8 is independent of byte order, so you don't have to worry about Big Endian / Little Endian issue.

Main UTF-8 cons:

  • Many common characters have different length, which slows indexing by codepoint and calculating a codepoint count terribly.
  • Even though byte order doesn't matter, sometimes UTF-8 still has BOM (byte order mark) which serves to notify that the text is encoded in UTF-8, and also breaks compatibility with ASCII software even if the text only contains ASCII characters. Microsoft software (like Notepad) especially likes to add BOM to UTF-8.

Main UTF-16 pros:

  • BMP (basic multilingual plane) characters, including Latin, Cyrillic, most Chinese (the PRC made support for some codepoints outside BMP mandatory), most Japanese can be represented with 2 bytes. This speeds up indexing and calculating codepoint count in case the text does not contain supplementary characters.
  • Even if the text has supplementary characters, they are still represented by pairs of 16-bit values, which means that the total length is still divisible by two and allows to use 16-bit char as the primitive component of the string.

Main UTF-16 cons:

  • Lots of null bytes in US-ASCII strings, which means no null-terminated strings and a lot of wasted memory.
  • Using it as a fixed-length encoding “mostly works” in many common scenarios (especially in US / EU / countries with Cyrillic alphabets / Israel / Arab countries / Iran and many others), often leading to broken support where it doesn't. This means the programmers have to be aware of surrogate pairs and handle them properly in cases where it matters!
  • It's variable length, so counting or indexing codepoints is costly, though less than UTF-8.

In general, UTF-16 is usually better for in-memory representation because BE/LE is irrelevant there (just use native order) and indexing is faster (just don't forget to handle surrogate pairs properly). UTF-8, on the other hand, is extremely good for text files and network protocols because there is no BE/LE issue and null-termination often comes in handy, as well as ASCII-compatibility.

How to have the cp command create any necessary folders for copying a file to a destination

cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory

It will create no existing paths in destination, if path have a source file inside. This dont create empty directories.

A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. without error message.

with ditto:

ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device

once freed space cp -Rvn /source/path/* /destination/path/ works as expected

Getting a directory name from a filename

Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.

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

Actually you need two div's for vertical centering. The div containing the content must have a width and height.

_x000D_
_x000D_
#container {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  margin-top: -200px;_x000D_
  /* half of #content height*/_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#content {_x000D_
  width: 624px;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  height: 395px;_x000D_
  border: 1px solid #000000;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="content">_x000D_
    <h1>Centered div</h1>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is the result

HTML5 Dynamically create Canvas

Via Jquery:

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/

Regular Expressions: Search in list

To do so without compiling the Regex first, use a lambda function - for example:

from re import match

values = ['123', '234', 'foobar']
filtered_values = list(filter(lambda v: match('^\d+$', v), values))

print(filtered_values)

Returns:

['123', '234']

filter() just takes a callable as it's first argument, and returns a list where that callable returned a 'truthy' value.

Editable 'Select' element

Another sort of workaround might be...

Use the HTML:

<input type="text" id="myselect"/>
<datalist id="myselect">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
<option>option 4</option>
</datalist>

In Firefox at least a focus followed by a click drops down the list of known valid values as the <datalist> elements IFF the field happens to be empty. Otherwise, one must clear the field to see valid choices as one types in data. A new value is accepted as typed. One must handle new values in JS or other to persist them.

This is not perfect, but it suffices for my minimalist needs, so I thought I would share.

extract part of a string using bash/cut/split

Define a function like this:

getUserName() {
    echo $1 | cut -d : -f 1 | xargs basename
}

And pass the string as a parameter:

userName=$(getUserName "/var/cpanel/users/joebloggs:DNS9=domain.com")
echo $userName

How do I disable fail_on_empty_beans in Jackson?

You can also probably annotate the class with @JsonIgnoreProperties(ignoreUnknown=true) to ignore the fields undefined in the class

How to change the application launcher icon on Flutter?

I use few methods for chaging flutter app lancher icon but only the manuall method is a bit easy and good. Because you will know how it work.

So to change flutter ios icon. First get copy of your icon 1024×1024 pixel and generate set of icons for android and ios using appicon.co generator. When you get zip file it work contact two folder ios and android open ios folder and copy folder and replace the one in your ios/runner directory.

For android copy all folder present in android folder and replace the ones present in the android/app/src/main/res/drawable here.

After replacing folder on both ios and android stop the app and re run and your icons will be changed.

How to print all information from an HTTP request to the screen, in PHP

A simple way would be:

<?php
print_r($_SERVER);
print_r($_POST);
print_r($_GET);
print_r($_FILES);
?>

A bit of massaging would be required to get everything in the order you want, and to exclude the variables you are not interested in, but should give you a start.

How to efficiently concatenate strings in go

Expanding on cd1's answer: You might use append() instead of copy(). append() makes ever bigger advance provisions, costing a little more memory, but saving time. I added two more benchmarks at the top of yours. Run locally with

go test -bench=. -benchtime=100ms

On my thinkpad T400s it yields:

BenchmarkAppendEmpty    50000000         5.0 ns/op
BenchmarkAppendPrealloc 50000000         3.5 ns/op
BenchmarkCopy           20000000        10.2 ns/op

How to target only IE (any version) within a stylesheet?

Internet Explorer 9 and lower : You could use conditional comments to load an IE-specific stylesheet for any version (or combination of versions) that you wanted to specifically target.like below using external stylesheet.

<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->

However, beginning in version 10, conditional comments are no longer supported in IE.

Internet Explorer 10 & 11 : Create a media query using -ms-high-contrast, in which you place your IE 10 and 11-specific CSS styles. Because -ms-high-contrast is Microsoft-specific (and only available in IE 10+), it will only be parsed in Internet Explorer 10 and greater.

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
     /* IE10+ CSS styles go here */
}

Microsoft Edge 12 : Can use the @supports rule Here is a link with all the info about this rule

@supports (-ms-accelerator:true) {
  /* IE Edge 12+ CSS styles go here */ 
}

Inline rule IE8 detection

I have 1 more option but it is only detect IE8 and below version.

  /* For IE css hack */
  margin-top: 10px\9 /* apply to all ie from 8 and below */
  *margin-top:10px;  /* apply to ie 7 and below */
  _margin-top:10px; /* apply to ie 6 and below */

As you specefied for embeded stylesheet. I think you need to use media query and condition comment for below version.

How to filter Android logcat by application?

Use fully qualified class names for your log tags:

public class MyActivity extends Activity {
  private static final String TAG = MyActivity.class.getName();
}

Then

Log.i(TAG, "hi");

Then use grep

adb logcat | grep com.myapp

PHP FPM - check if running

PHP-FPM is a service that spawns new PHP processes when needed, usually through a fast-cgi module like nginx. You can tell (with a margin of error) by just checking the init.d script e.g. "sudo /etc/init.d/php-fpm status"

What port or unix file socket is being used is up to the configuration, but often is just TCP port 9000. i.e. 127.0.0.1:9000

The best way to tell if it is running correctly is to have nginx running, and setup a virtual host that will fast-cgi pass to PHP-FPM, and just check it with wget or a browser.

How to copy a java.util.List into another java.util.List

You should use the addAll method. It appends all of the elements in the specified collection to the end of the copy list. It will be a copy of your list.

List<String> myList = new ArrayList<>();
myList.add("a");
myList.add("b");
List<String> copyList = new ArrayList<>();
copyList.addAll(myList);

How to make a simple rounded button in Storyboard?

Short Answer: YES

You can absolutely make a simple rounded button without the need of an additional background image or writing any code for the same. Just follow the screenshot given below, to set the runtime attributes for the button, to get the desired result.

It won't show in the Storyboard but it will work fine when you run the project.

enter image description here

Note:
The 'Key Path' layer.cornerRadius and value is 5. The value needs to be changed according to the height and width of the button. The formula for it is the height of button * 0.50. So play around the value to see the expected rounded button in the simulator or on the physical device. This procedure will look tedious when you have more than one button to be rounded in the storyboard.

asp.net mvc3 return raw html to view

What was working for me (ASP.NET Core), was to set return type ContentResult, then wrap the HMTL into it and set the ContentType to "text/html; charset=UTF-8". That is important, because, otherwise it will not be interpreted as HTML and the HTML language would be displayed as text.

Here's the example, part of a Controller class:

/// <summary>
/// Startup message displayed in browser.
/// </summary>
/// <returns>HTML result</returns>
[HttpGet]
public ContentResult Get()
{
    var result = Content("<html><title>DEMO</title><head><h2>Demo started successfully."
      + "<br/>Use <b><a href=\"http://localhost:5000/swagger\">Swagger</a></b>"
      + " to view API.</h2></head><body/></html>");
    result.ContentType = "text/html; charset=UTF-8";
    return result;
}

How can I define colors as variables in CSS?

You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

Getting String value from enum in Java

I believe enum have a .name() in its API, pretty simple to use like this example:

private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }

    private enum Security {
            low,
            high
    }

With this you can simply call

yourObject.security() 

and it returns high/low as String, in this example

Trim Cells using VBA in Excel

The infinite loop is a result of an On Error Resume Next statement somewhere higher up in your code. Get rid of it now. If your code only runs with On Error Resume Next in effect, it needs instant and complete overhaul.

And while you are at it, place an Option Explicit on top of yor module. It forces you to declare all variables, a safeguard against annoying bugs that are the result of mis-typed variable names. (You can modify the VBA editor preferences to have that option set automatically the next time, which is highly recommended.)

The immediate problem with your code is that a cell is an object, and objects cannot be trimmed. You want to trim the text of the cell, so you must do so:

cell.Text = Trim(cell.Text)

How to cast int to enum in C++?

Your code

enum Test
{
    A, B
}

int a = 1;

Solution

Test castEnum = static_cast<Test>(a);

Best practice when adding whitespace in JSX

You can use the css property white-space and set it to pre-wrap to the enclosing div element.

div {
     white-space: pre-wrap;
}

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

Your problem looks like you are mixing DML & DDL operations. See this URL which explains this issue:

http://www.orafaq.com/forum/t/54714/2/

PHP cURL HTTP CODE return 0

I had same problem and in my case this was because curl_exec function is disabled in php.ini. Check for logs:

PHP Warning:  curl_exec() has been disabled for security reasons in /var/www/***/html/test.php on line 18

Solution is remove curl_exec from disabled functions in php.ini on server configuration file.

Scanner only reads first word instead of line

Replace next() with nextLine():

String productDescription = input.nextLine();

Best way to store password in database

The best security practice is not to store the password at all (not even encrypted), but to store the salted hash (with a unique salt per password) of the encrypted password.

That way it is (practically) impossible to retrieve a plaintext password.

How to use Sublime over SSH

I know this is way old, but I have a really cool way of doing this that is worth sharing.

What is required in Conemu and WinSCP. These are simple instructions

  1. Open WinSCP.exe and login to my desired remote server (I have
    found that it's important to login before attaching ... ).

  2. In the preferences for WinSCP - two settings to change. Choose Explorer type interface and rather than Commander - so you don't see local files. Unless you want to (but that seems like it would suck here). Set up Sublime as your default editor.

  3. With ConEmu open, right click the tab bar and select the option Attach to.... A dialog box will open with your running applications. Choose, WinSCP and select OK. ConEmu will now have an open tab with WinSCP displaying your remote files.

  4. Right click on the WinSCP tab and choose New console.... When the dialog box opens, enter the path to the Sublime executable on your system. Before you press Start, In the box that says New console split select the radio button to right and set the percentage. I usually choose 75%, but you can customize this to your liking, and it can be changed later.

    1. Now you will see Sublime in the same window running to the right of WinSCP. In Sublime, from the View menu, choose Sidebar->Hide Sidebar, and bam, you now have remote files in exactly the same manner as you would locally - with a few caveats of course that comes with editing anything remotely. WinSCP is lightening fast though.

I have two monitors - left monitor display's Chrome browser, right monitor displays code editor. Also in ConEmu, I create another tab and ssh into the site I'm working on, so I can do things like run gulp or grunt remotely and also manipulate files from the command line. Seriously sped up development.

Here's a screenshot:

Setup Screenshot

Can I use DIV class and ID together in CSS?

Yes, why not? Then CSS that applies to class "x" AND CSS that applies to ID "y" applies to the div.

Swift - How to hide back button in navigation item?

That worked for me in Swift 5 like a charm, just add it to your viewDidLoad()

self.navigationItem.setHidesBackButton(true, animated: true)

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

How can I convert my Java program to an .exe file?

You can use Janel. This last works as an application launcher or service launcher (available from 4.x).

How do I request and receive user input in a .bat and use it to run a certain program?

I don't know the platform you're doing this on but I assume Windows due to the .bat extension.

Also I don't have a way to check this but this seems like the batch processor skips the If lines due to some errors and then executes the one with -dev.

You could try this by chaning the two jump targets (:yes and :no) along with the code. If then the line without -dev is executed you know your If lines are erroneous.

If so, please check if == is really the right way to do a comparison in .bat files.

Also, judging from the way bash does this stuff, %foo=="y" might evaluate to true only if %foo includes the quotes. So maybe "%foo"=="y" is the way to go.

Strip double quotes from a string in .NET

This worked for me

//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);

//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;

React Native: Getting the position of an element

I had a similar problem and solved it by combining the answers above

class FeedPost extends React.Component {
  constructor(props) {
    ...
    this.handleLayoutChange = this.handleLayoutChange.bind(this);
  }


handleLayoutChange() {
    this.feedPost.measure( (fx, fy, width, height, px, py) => {
      console.log('Component width is: ' + width)
      console.log('Component height is: ' + height)
      console.log('X offset to page: ' + px)
      console.log('Y offset to page: ' + py)
    })
  }

  render {
    return(
      <View onLayout={(event) => {this.handleLayoutChange(event) }} 
      ref={view => { this.feedPost = view; }} >
...

Now I can see the position of my feedPost element in the logs:

08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component width is: 156
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Component height is: 206
08-24 11:15:36.838  3727 27838 I ReactNativeJS: X offset to page: 188
08-24 11:15:36.838  3727 27838 I ReactNativeJS: Y offset to page: 870

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

How to hide reference counts in VS2013?

Workaround....

In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

How to know what the 'errno' means?

You can use strerror() to get a human-readable string for the error number. This is the same string printed by perror() but it's useful if you're formatting the error message for something other than standard error output.

For example:

#include <errno.h>
#include <string.h>

/* ... */

if(read(fd, buf, 1)==-1) {
    printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
}

Linux also supports the explicitly-threadsafe variant strerror_r().

In Python, how do I read the exif data for an image?

I usually use pyexiv2 to set exif information in JPG files, but when I import the library in a script QGIS script crash.

I found a solution using the library exif:

https://pypi.org/project/exif/

It's so easy to use, and with Qgis I don,'t have any problem.

In this code I insert GPS coordinates to a snapshot of screen:

from exif import Image
with open(file_name, 'rb') as image_file:
    my_image = Image(image_file)

my_image.make = "Python"
my_image.gps_latitude_ref=exif_lat_ref
my_image.gps_latitude=exif_lat
my_image.gps_longitude_ref= exif_lon_ref
my_image.gps_longitude= exif_lon

with open(file_name, 'wb') as new_image_file:
    new_image_file.write(my_image.get_file())

android adb turn on wifi via adb

You can turn on wifi : - connect usb on pc; - will show alert dialog "connect UMS mode or KIES" - do not click, do not cancel - pull notification bar and turn on wifi.

How to customize message box

Here is the code needed to create your own message box:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}   

What is the difference between Sublime text and Github's Atom

In addition to the points from prior answers, it's worth clarifying the differences between these two products from the perspective of choices made in their development.

Sublime is binary compiled for the platform. Its core is written in C/C++ and a number of its features are implemented in Python, which is also the language used for extending it. Atom is written in Node.js/Coffeescript and runs under webkit, with Coffeescript being the extension language. Though similar in UI and UX, Sublime performs significantly better than Atom especially in "heavy lifting" like working with large files, complex SnR or plugins that do heavy processing on files/buffers. Though I expect improvements in Atom as it matures, design & platform choices limit performance.

The "closed" part of Sublime includes the API and UI. Apart from skins/themes and colourisers, the API currently makes it difficult to modify other aspects of the UI. For example, Sublime plugins can't interact with the sidebar, control or draw on the editing area (except in some limited ways eg. in the gutter) or manipulate the statusbar beyond basic text. Atom's "closed" part is unknown at the moment, but I get the sense it's smaller. Atom has a richer API (though poorly documented at present) with the design goal of allowing greater control of its UI. Being closely coupled with webkit offers numerous capabilities for UI feature enhancements not presently possible with Sublime. However, Sublime's extensions perform closer to native, so those that perform compute-intensive, highly repetitive or complex text manipulations in large buffers are feasible in Sublime.

Since more of Atom will be open, Github open-sourced Atom on May 6th. As a result it's likely that support and pace of development will be rapid. By contrast, Sublime's development has slowed significantly of late - but it's not dead. In particular there are a number of bugs, many quite trivial, that haven't been fixed by the developer. None are showstopping imo, but if you want something in rapid development with regular bugfixing and enhancements, Sublime will frustrate. That said, installable Atom packages for Windows and Linux are yet to be released and activity on the codebase seems to have cooled in the weeks before and since the announcement, according to Github's stats.

In terms of IDE functions, from a webdev perspective Atom will allow extensions to the point of approaching products like Webstorm, though none have appeared yet. It remains to be seen how Atom will perform with such "heavy" extensions, since the editor natively feels sluggish. Due to restrictions in the API and lack of underlying webkit, Sublime won't allow this level of UI customisation although the developer may extend the API to support such features in future. Again, Sublime's underlying performance allows for things that involve computational grunt; ST3's symbol indexing being an example that performs well even with big projects. And though Atom's UI is certainly modelled upon Sublime, some refinements are noticeably missing, such as Sublime's learning panels and tab-complete popups which weight the defaults in accordance with those you most use.

I see these products as complementary. The fact that they share similar visuals and keystrokes just adds to the fact. There will be situations where the use of either has advantages. Presently, Sublime is a mature product with feature parity across all three platforms, and a rich set of plugins. Atom is the new kid whose features will rapidly grow; it doesn't feel production ready just yet and there are concerns in the area of performance.

[Update/Edit: May 18, 2015]

A note about improvements to these two editors since the time of writing the above.

In addition to bugfixes and improvements to its core, Atom has experienced a rapid growth in third-party extensions, with autocomplete-plus becoming part of the standard Atom distribution. Extension quality varies widely and a particular irritation is the frequency by which unstable third party packages can crash the editor. Within the last year, Atom has moved to using React by way of shifting reflow/repaint activity to the GPU for performance reasons, significantly improving the responsiveness of the UI for typical editing actions (scrolling, cursor movement etc.). While this has markedly improved the feel of the editor, it still feels cumbersome for CPU intensive tasks as described above, and is still slow in startup. Apart from performance improvements, Atom feels significantly more stable across the board.

Development of Sublime has picked up again since Jan 2015, with bugfixes, some minor new features (tooltip API, build system improvements) and a major development in the form of a new yaml-based .sublime-syntax definition (to eventually replace the old xml .tmLanguage). Together with a custom regex engine which replaces Onigurama, the new system offers more potential for precise regex matching, is significantly faster (up to 4x) and can perform multiple matches in parallel. Apart from colouring syntax, Sublime uses these components for symbol indexing (goto definition etc.) and other language-aware features. In addition to further speeding up Sublime, particularly for large files, this feature should open up the potential for performant language-specific features such as code-refactoring etc.. Further 'big developments' are promised, though the author remains, as ever, tight lipped about them.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I had the same issue, so I've disabled one setting on my WHM root login, which is as follows :

WHM > Home > Server Configuration > Tweak Settings > Restrict outgoing SMTP to root, exim, and mailman (FKA SMTP Tweak) [?]

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

Encode URL in JavaScript?

You should not use encodeURIComponent() directly.

Take a look at RFC3986: Uniform Resource Identifier (URI): Generic Syntax

sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI.

These reserved characters from the URI definition in RFC3986 ARE NOT escaped by encodeURIComponent().

MDN Web Docs: encodeURIComponent()

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

Use the MDN Web Docs function...

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

Load Image from javascript

You can try this:

<img id="id1" src="url/to/file.png" onload="showImage()">

function showImage() {
 $('#id1').attr('src', 'new/file/link.png');
}

Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

This way, you can change the attribute for the image.

Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

How to create a GUID/UUID in Python

I use GUIDs as random keys for database type operations.

The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..

Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).

import base64
import uuid

# get a UUID - URL safe, Base64
def get_a_uuid():
    r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes)
    return r_uuid.replace('=', '')

How do I make a MySQL database run completely in memory?

Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:

MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename for each table.

What is a Subclass

Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).

A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.

You declare that one class is subclass of another via the "extends" keyword in Java.

public class B extends A
{
...
}

B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.

This is the main concept of inheritance in Object-Oriented programming.

Video format or MIME type is not supported

In my case, this error:

Video format or MIME type is not supported.

Was due to the CSP in my .htaccess that did not allow the content to be loaded. You can check this by opening the browser's console and refreshing the page.

Once I added the domain that was hosting the video in the media-src part of that CSP, the console was clean and the video was loaded properly. Example:

Content-Security-Policy: default-src 'none'; media-src https://myvideohost.domain; script-src 'self'; style-src 'unsafe-inline' 'self'

How to open up a form from another form in VB.NET?

You may like to first create a dialogue by right clicking the project in solution explorer and in the code file type

dialogue1.show()

that's all !!!

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?

Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.

Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModules basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandlers can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.

Mocking member variables of a class using Mockito

You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).

If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).

Why do I need to configure the SQL dialect of a data source?

Dialect property is used by hibernate in following ways

  1. To generate Optimized SQL queries.
  2. If you have more than one DB then to talk with particular DB you want.
  3. To set default values for hibernate configuration file properties based on the DB software we use even though they are not specifed in configuration file.

Pass arguments to Constructor in VBA

Using the trick

Attribute VB_PredeclaredId = True

I found another more compact way:

Option Explicit
Option Base 0
Option Compare Binary

Private v_cBox As ComboBox

'
' Class creaor
Public Function New_(ByRef cBox As ComboBox) As ComboBoxExt_c
  If Me Is ComboBoxExt_c Then
    Set New_ = New ComboBoxExt_c
    Call New_.New_(cBox)
  Else
    Set v_cBox = cBox
  End If
End Function

As you can see the New_ constructor is called to both create and set the private members of the class (like init) only problem is, if called on the non-static instance it will re-initialize the private member. but that can be avoided by setting a flag.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

I changed my web.config file to use HTTPMODULE in two forms:

IIS: 6

<httpModules>
    <add name="Module" type="app.Module,app"/>
</httpModules>

IIS: 7.5

<system.webServer>
    <modules>
       <add name="Module" type="app.Module,app"/>
    </modules>
</system.webServer>

How do you select the entire excel sheet with Range using VBA?

I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet. If so - simply use... Range("A1").CurrentRegion

Java get last element of a collection

Or you can use a for-each loop:

Collection<X> items = ...;
X last = null;
for (X x : items) last = x;

SELECT INTO Variable in MySQL DECLARE causes syntax error?

I ran into this same issue, but I think I know what's causing the confusion. If you use MySql Query Analyzer, you can do this just fine:

SELECT myvalue 
INTO @myvar 
FROM mytable 
WHERE anothervalue = 1;

However, if you put that same query in MySql Workbench, it will throw a syntax error. I don't know why they would be different, but they are. To work around the problem in MySql Workbench, you can rewrite the query like this:

SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;

Tips for using Vim as a Java IDE?

I have just uploaded this Vim plugin for the development of Java Maven projects.

And don't forget to set the highlighting if you haven't already:

enter image description here https://github.com/sentientmachine/erics_vim_syntax_and_color_highlighting

How do I convert a Swift Array to a String?

Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator() instead of join():

var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

joinWithSeparator is defined as an extension on SequenceType

extension SequenceType where Generator.Element == String {
    /// Interpose the `separator` between elements of `self`, then concatenate
    /// the result.  For example:
    ///
    ///     ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
    @warn_unused_result
    public func joinWithSeparator(separator: String) -> String
}