Programs & Examples On #Element

In metadata, the term data element is an atomic unit of data that has precise meaning or precise semantics.

GetElementByID - Multiple IDs

document.getElementById() only takes one argument. You can give them a class name and use getElementsByClassName() .

Get the string representation of a DOM node

Under FF you can use the XMLSerializer object to serialize XML into a string. IE gives you an xml property of a node. So you can do the following:

function xml2string(node) {
   if (typeof(XMLSerializer) !== 'undefined') {
      var serializer = new XMLSerializer();
      return serializer.serializeToString(node);
   } else if (node.xml) {
      return node.xml;
   }
}

Deleting array elements in JavaScript - delete vs splice

Why not just filter? I think it is the most clear way to consider the arrays in js.

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});

Get element type with jQuery

also you can use:

$("#elementId").get(0).tagName

How to get elements with multiple classes

It's actually very similar to jQuery:

document.getElementsByClassName('class1 class2')

MDN Doc getElementsByClassName

How do I check in python if an element of a list is empty?

Try:

if l[i]:
    print 'Found element!'
else:
    print 'Empty element.'

Getting DOM element value using pure JavaScript

Pass the object:

doSomething(this)

You can get all data from object:

function(obj){
    var value = obj.value;
    var id = obj.id;
}

Or pass the id only:

doSomething(this.id)

Get the object and after that value:

function(id){
    var value = document.getElementById(id).value;  
}

How to get the focused element with jQuery?

How is it noone has mentioned..

document.activeElement.id

I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}

Deleting Elements in an Array if Element is a Certain value VBA

Sub DelEle(Ary, SameTypeTemp, Index As Integer) '<<<<<<<<< pass only not fixed sized array (i don't know how to declare same type temp array in proceder)
    Dim I As Integer, II As Integer
    II = -1
    If Index < LBound(Ary) And Index > UBound(Ary) Then MsgBox "Error.........."
    For I = 0 To UBound(Ary)
        If I <> Index Then
            II = II + 1
            ReDim Preserve SameTypeTemp(II)
            SameTypeTemp(II) = Ary(I)
        End If
    Next I
    ReDim Ary(UBound(SameTypeTemp))
    Ary = SameTypeTemp
    Erase SameTypeTemp
End Sub

Sub Test()
    Dim a() As Integer, b() As Integer
    ReDim a(3)
    Debug.Print "InputData:"
    For I = 0 To UBound(a)
        a(I) = I
        Debug.Print "    " & a(I)
    Next
    DelEle a, b, 1
    Debug.Print "Result:"
    For I = 0 To UBound(a)
        Debug.Print "    " & a(I)
    Next
End Sub

How to count items in JSON data

You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':

len(data['result'][0]['run'])

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

To put a sequence or another numpy array into a numpy array, Just change this line:

kOUT=np.zeros(N+1)

to:

kOUT=np.asarray([None]*(N+1))

Or:

kOUT=np.zeros((N+1), object)

Access multiple elements of list knowing their index

Another solution could be via pandas Series:

import pandas as pd

a = pd.Series([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
c = a[b]

You can then convert c back to a list if you want:

c = list(c)

How can I check if an element exists in the visible DOM?

Try the following. It is the most reliable solution:

window.getComputedStyle(x).display == ""

For example,

var x = document.createElement("html")
var y = document.createElement("body")
var z = document.createElement("div")
x.appendChild(y);
y.appendChild(z);

z.style.display = "block";

console.log(z.closest("html") == null); // 'false'
console.log(z.style.display); // 'block'
console.log(window.getComputedStyle(z).display == ""); // 'true'

How may I reference the script tag that loaded the currently-executing script?

Here's a bit of a polyfill that leverages document.CurrentScript if it exists and falls back to finding the script by ID.

<script id="uniqueScriptId">
    (function () {
        var thisScript = document.CurrentScript || document.getElementByID('uniqueScriptId');

        // your code referencing thisScript here
    ());
</script>

If you include this at the top of every script tag I believe you'll be able to consistently know which script tag is being fired, and you'll also be able to reference the script tag in the context of an asynchronous callback.

Untested, so leave feedback for others if you try it.

jquery, find next element by class

You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:


// Won't work in your case
$(obj).next().filter('.class');

But since it's not, I don't see a point to use next(). You can instead code:

$(obj).parents('table').find('.class')

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Counting the occurrences / frequency of array elements

_x000D_
_x000D_
const data = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]_x000D_
_x000D_
function count(arr) {_x000D_
  return arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {})_x000D_
}_x000D_
_x000D_
console.log(count(data))
_x000D_
_x000D_
_x000D_

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

You have to add

<script>jQuery.noConflict();</script>

after

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Add onclick event to newly added element in JavaScript

I don't think you can do that this way. You should use :

void addEventListener( 
  in DOMString type, 
  in EventListener listener, 
  in boolean useCapture 
); 

Documentation right here.

Check if one list contains element from the other

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

Its like

boolean b = list1.retainAll(list2);

Accessing elements by type in javascript

In plain-old JavaScript you can do this:

var inputs = document.getElementsByTagName('input');

for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type.toLowerCase() == 'text') {
        alert(inputs[i].value);
    }
}

In jQuery, you would just do:

// select all inputs of type 'text' on the page
$("input:text")

// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How to get child element by ID in JavaScript?

(Dwell in atom)

<div id="note">

   <textarea id="textid" class="textclass">Text</textarea>

</div>

<script type="text/javascript">

   var note = document.getElementById('textid').value;

   alert(note);

</script>

How to remove all the null elements inside a generic list in one go?

There is another simple and elegant option:

parameters.OfType<EmailParameterClass>();

This will remove all elements that are not of type EmailParameterClass which will obviously filter out any elements of type null.

Here's a test:

class Test { }
class Program
{
    static void Main(string[] args)
    {
        var list = new List<Test>();
        list.Add(null);
        Console.WriteLine(list.OfType<Test>().Count());// 0
        list.Add(new Test());
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Test test = null;
        list.Add(test);
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Console.ReadKey();
    }
}

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

How do you make an element "flash" in jQuery

Here's a solution that uses a mix of jQuery and CSS3 animations.

http://jsfiddle.net/padfv0u9/2/

Essentially you start by changing the color to your "flash" color, and then use a CSS3 animation to let the color fade out. You need to change the transition duration in order for the initial "flash" to be faster than the fade.

$(element).removeClass("transition-duration-medium");
$(element).addClass("transition-duration-instant");
$(element).addClass("ko-flash");
setTimeout(function () {
    $(element).removeClass("transition-duration-instant");
    $(element).addClass("transition-duration-medium");
    $(element).removeClass("ko-flash");
}, 500);

Where the CSS classes are as follows.

.ko-flash {
    background-color: yellow;
}
.transition-duration-instant {
    -webkit-transition-duration: 0s;
    -moz-transition-duration: 0s;
    -o-transition-duration: 0s;
    transition-duration: 0s;
}
.transition-duration-medium {
    -webkit-transition-duration: 1s;
    -moz-transition-duration: 1s;
    -o-transition-duration: 1s;
    transition-duration: 1s;
}

jQuery counting elements by class - what is the best way to implement this?

HTML:

<div>
    <img src='' class='class' />
    <img src='' class='class' />
    <img src='' class='class' />
</div>

    

JavaScript:

var numItems = $('.class').length; 
        
alert(numItems);

Fiddle demo for inside only div

Common elements in two lists

public static <T> List<T> getCommonElements(
            java.util.Collection<T> a,
            java.util.Collection<T> b
            ) {
        if(a==null && b==null) return new ArrayList<>();
        if(a!=null && a.size()==0) return new ArrayList<>(b);           
        if(b!=null && b.size()==0) return new ArrayList<>(a);
        
        Set<T> set= a instanceof HashSet?(HashSet<T>)a:new HashSet<>(a);
        return b.stream().filter(set::contains).collect(Collectors.toList());
    }

For better time performance, please use HashSet (O(1) look up) instead of List(O(n) look ups)

Time complexity- O(b) Space Complexity- O(a)

Select N random elements from a List<T> in C#

I just ran into this problem, and some more google searching brought me to the problem of randomly shuffling a list: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

To completely randomly shuffle your list (in place) you do this:

To shuffle an array a of n elements (indices 0..n-1):

  for i from n - 1 downto 1 do
       j ? random integer with 0 = j = i
       exchange a[j] and a[i]

If you only need the first 5 elements, then instead of running i all the way from n-1 to 1, you only need to run it to n-5 (ie: n-5)

Lets say you need k items,

This becomes:

  for (i = n - 1; i >= n-k; i--)
  {
       j = random integer with 0 = j = i
       exchange a[j] and a[i]
  }

Each item that is selected is swapped toward the end of the array, so the k elements selected are the last k elements of the array.

This takes time O(k), where k is the number of randomly selected elements you need.

Further, if you don't want to modify your initial list, you can write down all your swaps in a temporary list, reverse that list, and apply them again, thus performing the inverse set of swaps and returning you your initial list without changing the O(k) running time.

Finally, for the real stickler, if (n == k), you should stop at 1, not n-k, as the randomly chosen integer will always be 0.

Getting Index of an item in an arraylist;

Basically you need to look up ArrayList element based on name getName. Two approaches to this problem:

1- Don't use ArrayList, Use HashMap<String,AutionItem> where String would be name

2- Use getName to generate index and use index based addition into array list list.add(int index, E element). One way to generate index from name would be to use its hashCode and modulo by ArrayList current size (something similar what is used inside HashMap)

add item in array list of android

This will definitely work for you...

ArrayList<String> list = new ArrayList<String>();

list.add(textview.getText().toString());
list.add("B");
list.add("C");

Reference an Element in a List of Tuples

So you have "a list of tuples", let me assume that you are manipulating some 2-dimension matrix, and, in this case, one convenient interface to accomplish what you need is the one numpy provides.

Say you have an array arr = numpy.array([[1, 2], [3, 4], [5, 6]]), you can use arr[:, 0] to get a new array of all the first elements in each "tuple".

Removing an element from an Array (Java)

You can not change the length of an array, but you can change the values the index holds by copying new values and store them to a existing index number. 1=mike , 2=jeff // 10 = george 11 goes to 1 overwriting mike .

Object[] array = new Object[10];
int count = -1;

public void myFunction(String string) {
    count++;
    if(count == array.length) { 
        count = 0;  // overwrite first
    }
    array[count] = string;    
}

Using Java generics for JPA findAll() query with WHERE clause

Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

 @PersistenceContext
 EntityManager em;

 public List<ConfigurationEntry> allEntries() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
        Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
        CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
        TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
        return allQuery.getResultList();
 }

http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

AngularJS Directive Restrict A vs E

restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment) , let's assume that the name of the directive is Doc :

Type : Usage

A = <div Doc></div>

C = <div class="Doc"></div>

E = <Doc data="book_data"></Doc>

M = <!--directive:Doc -->

Fetch API with Cookie

If you are reading this in 2019, credentials: "same-origin" is the default value.

fetch(url).then

Telling Python to save a .txt file to a certain directory on Windows and Mac

Just give your desired path if file does not exist earlier;

        from os.path import abspath
        with open ('C:\\Users\\Admin\\Desktop\\results.txt', mode = 'w') as final1:
            print(final1.write('This is my new file.'))

        print(f'Text has been processed and saved at {abspath(final1.name)}')

Output will be:

Text has been processed and saved at C:\Users\Admin\Desktop\results.txt

The property 'value' does not exist on value of type 'HTMLElement'

We could assert

const inputElement: HTMLInputElement = document.getElementById('greet')

Or with as-syntax

const inputElement = document.getElementById('greet') as HTMLInputElement

Giving

const inputValue = inputElement.value // now inferred to be string

Failed to execute 'atob' on 'Window'

here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.

http://jsfiddle.net/tZPg4/9397/

stack overflow requires I include some code with a jsFiddle link so please ignore snippet:

localStorage.setItem(...)

Foreach loop, determine which is the last iteration of the loop

To do something additional to each element except for the last one, function based approach can be used.

delegate void DInner ();

....
    Dinner inner=delegate 
    { 
        inner=delegate 
        { 
            // do something additional
        } 
    }
    foreach (DataGridViewRow dgr in product_list.Rows)
    {
        inner()
        //do something
    }
}

This approach has apparent drawbacks: less code clarity for more complex cases. Calling delegates might be not very effective. Troubleshooting might be not quite easy. The bright side - coding is fun!

Having said that, I would suggest using plain for loops in trivial cases, if you know that your collection's count is not terribly slow.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

  1. To closed ideas,
  2. To remove all folder and file C:/Users/UserName/.m2/org/*,
  3. Open ideas and update Maven project,(right click on project -> maven->update maven project)
  4. After that update the project.

MVC 4 Razor adding input type date

The input date value format needs the date specified as per http://tools.ietf.org/html/rfc3339#section-5.6 full-date.

So I've ended up doing:

<input type="date" id="last-start-date" value="@string.Format("{0:yyyy-MM-dd}", Model.LastStartDate)" />

I did try doing it "properly" using:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime LastStartDate
{
    get { return lastStartDate; }
    set { lastStartDate = value; }
}

with

@Html.TextBoxFor(model => model.LastStartDate, 
    new { type = "date" })

Unfortunately that always seemed to set the value attribute of the input to a standard date time so I've ended up applying the formatting directly as above.

Edit:

According to Jorn if you use

@Html.EditorFor(model => model.LastStartDate)

instead of TextBoxFor it all works fine.

Forward host port to docker container

As stated in one of the comments, this works for Mac (probably for Windows/Linux too):

I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST

The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.

You can also reach the gateway using gateway.docker.internal.

Quoted from https://docs.docker.com/docker-for-mac/networking/

This worked for me without using --net=host.

How do you run a SQL Server query from PowerShell?

You can use the Invoke-Sqlcmd cmdlet

Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance"

http://technet.microsoft.com/en-us/library/cc281720.aspx

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute's standard behavior only happens for form elements. Try unbinding the event:

$("span").unbind("click");

Shell script not running, command not found

Make sure you are not using "PATH" as a variable, which will override the existing PATH for environment variables.

Vertical Alignment of text in a table cell

CSS {vertical-align: top;} or html Attribute {valign="top"}

_x000D_
_x000D_
.table td, 
.table th {
    border: 1px solid #161b21;
    text-align: left;
    padding: 8px;
    width: 250px;
    height: 100px;
    
    /* style for table */
}

.table-body-text {
  vertical-align: top;
}
_x000D_
<table class="table">
    <tr>
      <th valign="top">Title 1</th>
      <th valign="top">Title 2</th>
    </tr>
    <tr>
      <td class="table-body-text">text</td>
      <td class="table-body-text">text</td>
    </tr>
   </table>
_x000D_
_x000D_
_x000D_

For table vertical-align we have 2 options.

  1. is to use css {vertical-align: top;}
  1. another way is to user attribute "valign" and the property should be "top" {valign="top"}

How to add elements to an empty array in PHP?

When one wants elements to be added with zero-based element indexing, I guess this will work as well:

// adding elements to an array with zero-based index
$matrix= array();
$matrix[count($matrix)]= 'element 1';
$matrix[count($matrix)]= 'element 2';
...
$matrix[count($matrix)]= 'element N';

Kill process by name?

If you have killall:

os.system("killall -9 iChat");

Or:

os.system("ps -C iChat -o pid=|xargs kill -9")

python mpl_toolkits installation issue

It is not on PyPI and you should not be installing it via pip. If you have matplotlib installed, you should be able to import mpl_toolkits directly:

$ pip install --upgrade matplotlib
...

$ python
>>> import mpl_toolkits
>>> 

PHPExcel - creating multiple sheets by iteration

Complementing the coment of @Mark Baker.
Do as follow:

$titles = array('title 1', 'title 2');
$sheet = 0;
foreach($array as $value){
    if($sheet > 0){
        $objPHPExcel->createSheet();
        $sheet = $objPHPExcel->setActiveSheetIndex($sheet);
        $sheet->setTitle("$value");
        //Do you want something more here
    }else{
        $objPHPExcel->setActiveSheetIndex(0)->setTitle("$value");
    }
    $sheet++;
}  

This worked for me. And hope it works for those who need! :)

Using CMake to generate Visual Studio C++ project files

As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.

But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.

Ignore .classpath and .project from Git

If the .project and .classpath are already committed, then they need to be removed from the index (but not the disk)

git rm --cached .project
git rm --cached .classpath

Then the .gitignore would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse file will then work, which does include:

# Eclipse Core      
.project

# JDT-specific (Eclipse Java Development Tools)     
.classpath

Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR set to a shared folder accessible by all).
That template folder can contain an info/exclude file, with ignore rules that you want enforced for all repos, including the new ones (git init) that any user would use.


As commented by Abdollah

When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files .classpath and .project from the repo.

How can I generate a tsconfig.json file?

I recommend to uninstall typescript first with the command:

npm uninstall -g typescript

then use the chocolatey package in order to run:

choco install typescript

in PowerShell.

How to generate XML file dynamically using PHP?

An easily broken way to do this is :

<?php
// Send the headers
header('Content-type: text/xml');
header('Pragma: public');
header('Cache-control: private');
header('Expires: -1');
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

echo '<xml>';

// echo some dynamically generated content here
/*
<track>
    <path>song_path</path>
    <title>track_number - track_title</title>
</track>
*/

echo '</xml>';

?>

save it as .php

How to parse a JSON and turn its values into an Array?

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

How to run an awk commands in Windows?

You can download and run the setup file. This should install your AWK in "C:\Program Files (x86)\GnuWin32". You can run the awk or gawk command from the bin folder or add the folder ``C:\Program Files (x86)\GnuWin32\binto yourPATH`.

enter image description here

Google API for location, based on user IP address

It looks like Google actively frowns on using IP-to-location mapping:

https://developers.google.com/maps/articles/geolocation?hl=en

That article encourages using the W3C geolocation API. I was a little skeptical, but it looks like almost every major browser already supports the geolocation API:

http://caniuse.com/geolocation

Linux shell sort file according to the second column?

To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

sort -k 2,2 -s orig_file > sorted_file

VBA to copy a file from one directory to another

This method is even easier if you're ok with fewer options:

FileCopy source, destination

How do you perform a left outer join using linq extension methods

For a (left outer) join of a table Bar with a table Foo on Foo.Foo_Id = Bar.Foo_Id in lambda notation:

var qry = Foo.GroupJoin(
          Bar, 
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (x,y) => new { Foo = x, Bars = y })
       .SelectMany(
           x => x.Bars.DefaultIfEmpty(),
           (x,y) => new { Foo=x.Foo, Bar=y});

How to merge remote master to local branch

From your feature branch (e.g configUpdate) run:

git fetch
git rebase origin/master

Or the shorter form:

git pull --rebase

Why this works:

  • git merge branchname takes new commits from the branch branchname, and adds them to the current branch. If necessary, it automatically adds a "Merge" commit on top.

  • git rebase branchname takes new commits from the branch branchname, and inserts them "under" your changes. More precisely, it modifies the history of the current branch such that it is based on the tip of branchname, with any changes you made on top of that.

  • git pull is basically the same as git fetch; git merge origin/master.

  • git pull --rebase is basically the same as git fetch; git rebase origin/master.

So why would you want to use git pull --rebase rather than git pull? Here's a simple example:

  • You start working on a new feature.

  • By the time you're ready to push your changes, several commits have been pushed by other developers.

  • If you git pull (which uses merge), your changes will be buried by the new commits, in addition to an automatically-created merge commit.

  • If you git pull --rebase instead, git will fast forward your master to upstream's, then apply your changes on top.

Assert a function/method was not called using Mock

Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method.

Just upgrade yours;

pip install mock --upgrade

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Replace all latters from any language in 'A', and if you wish for example all digits to 0:

return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");

Link to add to Google calendar

For the next person Googling this topic, I've written a small NPM package to make it simple to generate Google Calendar URLs. It includes TypeScript type definitions, for those who need that. Hope it helps!

https://www.npmjs.com/package/google-calendar-url

How to assert two list contain the same elements in Python?

Converting your lists to sets will tell you that they contain the same elements. But this method cannot confirm that they contain the same number of all elements. For example, your method will fail in this case:

L1 = [1,2,2,3]
L2 = [1,2,3,3]

You are likely better off sorting the two lists and comparing them:

def checkEqual(L1, L2):
    if sorted(L1) == sorted(L2):
        print "the two lists are the same"
        return True
    else:
        print "the two lists are not the same"
        return False

Note that this does not alter the structure/contents of the two lists. Rather, the sorting creates two new lists

What is the difference between YAML and JSON?

I find YAML to be easier on the eyes: less parenthesis, "" etc. Although there is the annoyance of tabs in YAML... but one gets the hang of it.

In terms of performance/resources, I wouldn't expect big differences between the two.

Futhermore, we are talking about configuration files and so I wouldn't expect a high frequency of encode/decode activity, no?

How to convert a command-line argument to int?

Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments.

The C way; simplest, but will treat any invalid number as 0:

#include <cstdlib>

int x = atoi(argv[1]);

The C way with input checking:

#include <cstdlib>

errno = 0;
char *endptr;
long int x = strtol(argv[1], &endptr, 10);
if (endptr == argv[1]) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (*endptr) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
} else if (errno == ERANGE) {
  std::cerr << "Number out of range: " << argv[1] << '\n';
}

The C++ iostreams way with input checking:

#include <sstream>

std::istringstream ss(argv[1]);
int x;
if (!(ss >> x)) {
  std::cerr << "Invalid number: " << argv[1] << '\n';
} else if (!ss.eof()) {
  std::cerr << "Trailing characters after number: " << argv[1] << '\n';
}

Alternative C++ way since C++11:

#include <stdexcept>
#include <string>

std::string arg = argv[1];
try {
  std::size_t pos;
  int x = std::stoi(arg, &pos);
  if (pos < arg.size()) {
    std::cerr << "Trailing characters after number: " << arg << '\n';
  }
} catch (std::invalid_argument const &ex) {
  std::cerr << "Invalid number: " << arg << '\n';
} catch (std::out_of_range const &ex) {
  std::cerr << "Number out of range: " << arg << '\n';
}

All four variants assume that argc >= 2. All accept leading whitespace; check isspace(argv[1][0]) if you don't want that. All except atoi reject trailing whitespace.

How to get your Netbeans project into Eclipse

There's a very easy way if you were using a web application just follow this link.

just do in eclipse :

File > import > web > war file

Then select the war file of your app :)) very easy !!

Run php function on button click

<a href="home.php?click=1" class="btn">Click me</a>
<?php 
  if($_GET['click']){
    doSomething();
  }
?>

But is better to use JS and with ajax to call function!

Progress during large file copy (Copy-Item & Write-Progress?)

cmd /c copy /z src dest

not pure PowerShell, but executable in PowerShell and it displays progress in percents

PHP: Inserting Values from the Form into MySQL

<?php
    $username="root";
    $password="";
    $database="test";

    #get the data from form fields
    $Id=$_POST['Id'];
    $P_name=$_POST['P_name'];
    $address1=$_POST['address1'];
    $address2=$_POST['address2'];
    $email=$_POST['email'];

    mysql_connect(localhost,$username,$password);
    @mysql_select_db($database) or die("unable to select database");

    if($_POST['insertrecord']=="insert"){
        $query="insert into person values('$Id','$P_name','$address1','$address2','$email')";
        echo "inside";
        mysql_query($query);
        $query1="select * from person";
        $result=mysql_query($query1);
        $num= mysql_numrows($result);

        #echo"<b>output</b>";
        print"<table border size=1 > 
        <tr><th>Id</th>
        <th>P_name</th>
        <th>address1</th>
        <th>address2</th>
        <th>email</th>
        </tr>";
        $i=0;
        while($i<$num)
        {
            $Id=mysql_result($result,$i,"Id");
            $P_name=mysql_result($result,$i,"P_name");
            $address1=mysql_result($result,$i,"address1");
            $address2=mysql_result($result,$i,"address2");
            $email=mysql_result($result,$i,"email");
            echo"<tr><td>$Id</td>
            <td>$P_name</td>
            <td>$address1</td>
            <td>$address2</td>
            <td>$email</td>
            </tr>";
            $i++;
        }
        print"</table>";
    }

    if($_POST['searchdata']=="Search")
    {
        $P_name=$_POST['name'];
        $query="select * from person where P_name='$P_name'";
        $result=mysql_query($query);
        print"<table border size=1><tr><th>Id</th>
        <th>P_name</th>
        <th>address1</th>
        <th>address2</th>
        <th>email</th>
        </tr>";
        while($row=mysql_fetch_array($result))
        {
            $Id=$row[Id];
            $P_name=$row[P_name];
            $address1=$row[address1];
            $address2=$row[address2];
            $email=$row[email];
            echo"<tr><td>$Id</td>
            <td>$P_name</td>
            <td>$address1</td>
            <td>$address2</td>
            <td>$email</td>
            </tr>";
        }
        echo"</table>";
    }
    echo"<a href=lab2.html> Back </a>";
?>

How to write a file or data to an S3 object using boto3

In boto 3, the 'Key.set_contents_from_' methods were replaced by

For example:

import boto3

some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'

# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)

# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')

Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:

Storing Data

Storing data from a file, stream, or string is easy:

# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')

# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))

How to find list intersection?

Here's some Python 2 / Python 3 code that generates timing information for both list-based and set-based methods of finding the intersection of two lists.

The pure list comprehension algorithms are O(n^2), since in on a list is a linear search. The set-based algorithms are O(n), since set search is O(1), and set creation is O(n) (and converting a set to a list is also O(n)). So for sufficiently large n the set-based algorithms are faster, but for small n the overheads of creating the set(s) make them slower than the pure list comp algorithms.

#!/usr/bin/env python

''' Time list- vs set-based list intersection
    See http://stackoverflow.com/q/3697432/4014959
    Written by PM 2Ring 2015.10.16
'''

from __future__ import print_function, division
from timeit import Timer

setup = 'from __main__ import a, b'
cmd_lista = '[u for u in a if u in b]'
cmd_listb = '[u for u in b if u in a]'

cmd_lcsa = 'sa=set(a);[u for u in b if u in sa]'

cmd_seta = 'list(set(a).intersection(b))'
cmd_setb = 'list(set(b).intersection(a))'

reps = 3
loops = 50000

def do_timing(heading, cmd, setup):
    t = Timer(cmd, setup)
    r = t.repeat(reps, loops)
    r.sort()
    print(heading, r)
    return r[0]

m = 10
nums = list(range(6 * m))

for n in range(1, m + 1):
    a = nums[:6*n:2]
    b = nums[:6*n:3]
    print('\nn =', n, len(a), len(b))
    #print('\nn = %d\n%s %d\n%s %d' % (n, a, len(a), b, len(b)))
    la = do_timing('lista', cmd_lista, setup) 
    lb = do_timing('listb', cmd_listb, setup) 
    lc = do_timing('lcsa ', cmd_lcsa, setup)
    sa = do_timing('seta ', cmd_seta, setup)
    sb = do_timing('setb ', cmd_setb, setup)
    print(la/sa, lb/sa, lc/sa, la/sb, lb/sb, lc/sb)

output

n = 1 3 2
lista [0.082171916961669922, 0.082588911056518555, 0.0898590087890625]
listb [0.069530963897705078, 0.070394992828369141, 0.075379848480224609]
lcsa  [0.11858987808227539, 0.1188349723815918, 0.12825107574462891]
seta  [0.26900982856750488, 0.26902294158935547, 0.27298116683959961]
setb  [0.27218389511108398, 0.27459001541137695, 0.34307217597961426]
0.305460649521 0.258469975867 0.440838458259 0.301898526833 0.255455833892 0.435697630214

n = 2 6 4
lista [0.15915989875793457, 0.16000485420227051, 0.16551494598388672]
listb [0.13000702857971191, 0.13060092926025391, 0.13543915748596191]
lcsa  [0.18650484085083008, 0.18742108345031738, 0.19513416290283203]
seta  [0.33592700958251953, 0.34001994132995605, 0.34146714210510254]
setb  [0.29436492919921875, 0.2953648567199707, 0.30039691925048828]
0.473793098554 0.387009751735 0.555194537893 0.540689066428 0.441652573672 0.633583767462

n = 3 9 6
lista [0.27657914161682129, 0.28098297119140625, 0.28311991691589355]
listb [0.21585917472839355, 0.21679902076721191, 0.22272896766662598]
lcsa  [0.22559309005737305, 0.2271728515625, 0.2323150634765625]
seta  [0.36382699012756348, 0.36453008651733398, 0.36750602722167969]
setb  [0.34979605674743652, 0.35533690452575684, 0.36164689064025879]
0.760194128313 0.59330170819 0.62005595016 0.790686848184 0.61710008036 0.644927481902

n = 4 12 8
lista [0.39616990089416504, 0.39746403694152832, 0.41129183769226074]
listb [0.33485794067382812, 0.33914685249328613, 0.37850618362426758]
lcsa  [0.27405810356140137, 0.2745978832244873, 0.28249192237854004]
seta  [0.39211201667785645, 0.39234519004821777, 0.39317893981933594]
setb  [0.36988520622253418, 0.37011313438415527, 0.37571001052856445]
1.01034878821 0.85398540833 0.698928091731 1.07106176249 0.905302334456 0.740927452493

n = 5 15 10
lista [0.56792402267456055, 0.57422614097595215, 0.57740211486816406]
listb [0.47309303283691406, 0.47619009017944336, 0.47628307342529297]
lcsa  [0.32805585861206055, 0.32813096046447754, 0.3349759578704834]
seta  [0.40036201477050781, 0.40322518348693848, 0.40548801422119141]
setb  [0.39103078842163086, 0.39722800254821777, 0.43811702728271484]
1.41852623806 1.18166313332 0.819398061028 1.45237674242 1.20986133789 0.838951479847

n = 6 18 12
lista [0.77897095680236816, 0.78187918663024902, 0.78467702865600586]
listb [0.629547119140625, 0.63210701942443848, 0.63321495056152344]
lcsa  [0.36563992500305176, 0.36638498306274414, 0.38175487518310547]
seta  [0.46695613861083984, 0.46992206573486328, 0.47583580017089844]
setb  [0.47616910934448242, 0.47661614418029785, 0.4850609302520752]
1.66818870637 1.34819326075 0.783028414812 1.63591241329 1.32210827369 0.767878297495

n = 7 21 14
lista [0.9703209400177002, 0.9734041690826416, 1.0182771682739258]
listb [0.82394003868103027, 0.82625699043273926, 0.82796716690063477]
lcsa  [0.40975093841552734, 0.41210508346557617, 0.42286920547485352]
seta  [0.5086359977722168, 0.50968098640441895, 0.51014018058776855]
setb  [0.48688101768493652, 0.4879908561706543, 0.49204087257385254]
1.90769222837 1.61990115188 0.805587768483 1.99293236904 1.69228211566 0.841583309951

n = 8 24 16
lista [1.204819917678833, 1.2206029891967773, 1.258256196975708]
listb [1.014998197555542, 1.0206191539764404, 1.0343101024627686]
lcsa  [0.50966787338256836, 0.51018595695495605, 0.51319599151611328]
seta  [0.50310111045837402, 0.50556015968322754, 0.51335406303405762]
setb  [0.51472997665405273, 0.51948785781860352, 0.52113485336303711]
2.39478683834 2.01748351664 1.01305257092 2.34068341135 1.97190418975 0.990165516871

n = 9 27 18
lista [1.511646032333374, 1.5133969783782959, 1.5639569759368896]
listb [1.2461750507354736, 1.254518985748291, 1.2613379955291748]
lcsa  [0.5565330982208252, 0.56119203567504883, 0.56451296806335449]
seta  [0.5966339111328125, 0.60275578498840332, 0.64791703224182129]
setb  [0.54694414138793945, 0.5508568286895752, 0.55375313758850098]
2.53362406013 2.08867620074 0.932788243907 2.76380331728 2.27843203069 1.01753187594

n = 10 30 20
lista [1.7777848243713379, 2.1453688144683838, 2.4085969924926758]
listb [1.5070111751556396, 1.5202279090881348, 1.5779800415039062]
lcsa  [0.5954139232635498, 0.59703707695007324, 0.60746097564697266]
seta  [0.61563014984130859, 0.62125110626220703, 0.62354087829589844]
setb  [0.56723213195800781, 0.57257509231567383, 0.57460403442382812]
2.88774814689 2.44791645689 0.967161734066 3.13413984189 2.6567803378 1.04968299523

Generated using a 2GHz single core machine with 2GB of RAM running Python 2.6.6 on a Debian flavour of Linux (with Firefox running in the background).

These figures are only a rough guide, since the actual speeds of the various algorithms are affected differently by the proportion of elements that are in both source lists.

How to check if a date is in a given range?

$start_date="17/02/2012";
$end_date="21/02/2012";
$date_from_user="19/02/2012";

function geraTimestamp($data)
{
    $partes = explode('/', $data); 
    return mktime(0, 0, 0, $partes[1], $partes[0], $partes[2]);
}


$startDatedt = geraTimestamp($start_date); 
$endDatedt = geraTimestamp($end_date);
$usrDatedt = geraTimestamp($date_from_user);

if (($usrDatedt >= $startDatedt) && ($usrDatedt <= $endDatedt))
{ 
    echo "Dentro";
}    
else
{
    echo "Fora";
}

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

How do I make an attributed string using Swift?

I created an online tool that is going to solve your problem! You can write your string and apply styles graphically and the tool gives you objective-c and swift code to generate that string.

Also is open source so feel free to extend it and send PRs.

Transformer Tool

Github

enter image description here

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

Angular: date filter adds timezone, how to output UTC?

The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.

Borrowing from this answer, you could do something like this without moment.js:

controller

var app1 = angular.module('app1',[]);

app1.controller('ctrl',['$scope',function($scope){

  var toUTCDate = function(date){
    var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
    return _utc;
  };

  var millisToUTCDate = function(millis){
    return toUTCDate(new Date(millis));
  };

    $scope.toUTCDate = toUTCDate;
    $scope.millisToUTCDate = millisToUTCDate;

  }]);

template

<html ng-app="app1">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="ctrl">
      <div>
      utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
      </div>
      <div>
      local {{1400167800 | date:'dd-M-yyyy H:mm'}}
      </div>
    </div>
  </body>

</html>

here's plunker to play with it

See also this and this.

Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.

Accessing an SQLite Database in Swift

Configure your Swift project to handle SQLite C calls:

Create bridging header file to the project. See the Importing Objective-C into Swift section of the Using Swift with Cocoa and Objective-C. This bridging header should import sqlite3.h:

Add the libsqlite3.0.dylib to your project. See Apple's documentation regarding adding library/framework to one's project.

and used following code

    func executeQuery(query: NSString ) -> Int
    {
        if  sqlite3_open(databasePath! as String, &database) != SQLITE_OK
        {
            println("Databse is not open")
            return 0
        }
        else
        {
            query.stringByReplacingOccurrencesOfString("null", withString: "")
            var cStatement:COpaquePointer = nil
            var executeSql = query as NSString
            var lastId : Int?
            var sqlStatement = executeSql.cStringUsingEncoding(NSUTF8StringEncoding)
            sqlite3_prepare_v2(database, sqlStatement, -1, &cStatement, nil)
            var execute = sqlite3_step(cStatement)
            println("\(execute)")
            if execute == SQLITE_DONE
            {
                lastId = Int(sqlite3_last_insert_rowid(database))
            }
            else
            {
                println("Error in Run Statement :- \(sqlite3_errmsg16(database))")
            }
            sqlite3_finalize(cStatement)
            return lastId!
        }
    }
    func ViewAllData(query: NSString, error: NSError) -> NSArray
    {
        var cStatement = COpaquePointer()
        var result : AnyObject = NSNull()
        var thisArray : NSMutableArray = NSMutableArray(capacity: 4)
        cStatement = prepare(query)
        if cStatement != nil
        {
            while sqlite3_step(cStatement) == SQLITE_ROW
            {
                result = NSNull()
                var thisDict : NSMutableDictionary = NSMutableDictionary(capacity: 4)
                for var i = 0 ; i < Int(sqlite3_column_count(cStatement)) ; i++
                {
                    if sqlite3_column_type(cStatement, Int32(i)) == 0
                    {
                        continue
                    }
                    if sqlite3_column_decltype(cStatement, Int32(i)) != nil && strcasecmp(sqlite3_column_decltype(cStatement, Int32(i)), "Boolean") == 0
                    {
                        var temp = sqlite3_column_int(cStatement, Int32(i))
                        if temp == 0
                        {
                            result = NSNumber(bool : false)
                        }
                        else
                        {
                            result = NSNumber(bool : true)
                        }
                    }
                    else if sqlite3_column_type(cStatement,Int32(i)) == SQLITE_INTEGER
                    {
                        var temp = sqlite3_column_int(cStatement,Int32(i))
                        result = NSNumber(int : temp)
                    }
                    else if sqlite3_column_type(cStatement,Int32(i)) == SQLITE_FLOAT
                    {
                        var temp = sqlite3_column_double(cStatement,Int32(i))
                        result = NSNumber(double: temp)
                    }
                    else
                    {
                        if sqlite3_column_text(cStatement, Int32(i)) != nil
                        {
                            var temp = sqlite3_column_text(cStatement,Int32(i))
                            result = String.fromCString(UnsafePointer<CChar>(temp))!
                            
                            var keyString = sqlite3_column_name(cStatement,Int32(i))
                            thisDict.setObject(result, forKey: String.fromCString(UnsafePointer<CChar>(keyString))!)
                        }
                        result = NSNull()

                    }
                    if result as! NSObject != NSNull()
                    {
                        var keyString = sqlite3_column_name(cStatement,Int32(i))
                        thisDict.setObject(result, forKey: String.fromCString(UnsafePointer<CChar>(keyString))!)
                    }
                }
                thisArray.addObject(NSMutableDictionary(dictionary: thisDict))
            }
            sqlite3_finalize(cStatement)
        }
        return thisArray
    }
    func prepare(sql : NSString) -> COpaquePointer
    {
        var cStatement:COpaquePointer = nil
        sqlite3_open(databasePath! as String, &database)
        var utfSql = sql.UTF8String
        if sqlite3_prepare(database, utfSql, -1, &cStatement, nil) == 0
        {
            sqlite3_close(database)
            return cStatement
        }
        else
        {
            sqlite3_close(database)
            return nil
        }
    }
}

How to "fadeOut" & "remove" a div in jQuery?

If you're using it in several different places, you should turn it into a plugin.

jQuery.fn.fadeOutAndRemove = function(speed){
    $(this).fadeOut(speed,function(){
        $(this).remove();
    })
}

And then:

// Somewhere in the program code.
$('div').fadeOutAndRemove('fast');

TextView - setting the text size programmatically doesn't seem to work

Currently, setTextSize(float size) method will work well so we don't need to use another method for change text size

android.widget.TextView.java source code

/**
 * Set the default text size to the given value, interpreted as "scaled
 * pixel" units.  This size is adjusted based on the current density and
 * user font size preference.
 *
 * <p>Note: if this TextView has the auto-size feature enabled than this function is no-op.
 *
 * @param size The scaled pixel size.
 *
 * @attr ref android.R.styleable#TextView_textSize
 */
@android.view.RemotableViewMethod
public void setTextSize(float size) {
    setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}

Example using

textView.setTextSize(20); // set your text size = 20sp

How to Sign an Already Compiled Apk

For those of you who don't want to create a bat file to edit for every project, or dont want to remember all the commands associated with the keytools and jarsigner programs and just want to get it done in one process use this program:

http://lukealderton.com/projects/programs/android-apk-signer-aligner.aspx

I built it because I was fed up with the lengthy process of having to type all the file locations every time.

This program can save your configuration so the next time you start it, you just need to hit Generate an it will handle it for you. That's it.

No install required, it's completely portable and saves its configurations in a CSV in the same folder.

SQL Server ORDER BY date and nulls last

According to Itzik Ben-Gan, author of T-SQL Fundamentals for MS SQL Server 2012, "By default, SQL Server sorts NULL marks before non-NULL values. To get NULL marks to sort last, you can use a CASE expression that returns 1 when the" Next_Contact_Date column is NULL, "and 0 when it is not NULL. Non-NULL marks get 0 back from the expression; therefore, they sort before NULL marks (which get 1). This CASE expression is used as the first sort column." The Next_Contact_Date column "should be specified as the second sort column. This way, non-NULL marks sort correctly among themselves." Here is the solution query for your example for MS SQL Server 2012 (and SQL Server 2014):

ORDER BY 
   CASE 
        WHEN Next_Contact_Date IS NULL THEN 1
        ELSE 0
   END, Next_Contact_Date;

Equivalent code using IIF syntax:

ORDER BY 
   IIF(Next_Contact_Date IS NULL, 1, 0),
   Next_Contact_Date;

Insert a line at specific line number with sed or awk

sed -i '8i8 This is Line 8' FILE

inserts at line 8

8 This is Line 8

into file FILE

-i does the modification directly to file FILE, no output to stdout, as mentioned in the comments by glenn jackman.

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

The server will automatically abort connections over which no message has been received for the duration equal to the receive timeout (default is 10 mins). This is a DoS mitigation to prevent clients from forcing the server to have connections open for an indefinite amount of time.

Since the server aborts the connection because it has gone idle, the client gets this exception.

You can control how long the server allows a connection to go idle before aborting it by configuring the receive timeout on the server's binding. Credit: T.R.Vishwanath - MSFT

Basic Apache commands for a local Windows machine

Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-

  1. Click the start button and type CMD (if on Windows Vista or later and Apache is installed as a service make sure this is an elevated command prompt)
  2. In the command window that appears type cd C:\xampp\apache\bin (the default installation path for Xampp)
  3. Then type httpd -k restart

I hope that this is of use to others just starting out with running a local Apache server.

Linq style "For Each"

There isn't anything built-in, but you can easily create your own extension method to do it:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}

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

In order to see images, plots and anything displayed on windows on your remote machine you need to connect to it like this:

ssh -X user@hostname

That way you enable the access to the X server. The X server is a program in the X Window System that runs on local machines (i.e., the computers used directly by users) and handles all access to the graphics cards, display screens and input devices (typically a keyboard and mouse) on those computers.

More info here.

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

Multi-character constant warnings

This warning is useful for programmers that would mistakenly write 'test' where they should have written "test".

This happen much more often than programmers that do actually want multi-char int constants.

How can I delete an item from an array in VB.NET?

One line using LINQ:

Dim arr() As String = {"uno", "dos", "tres", "cuatro", "cinco"}
Dim indx As Integer = 2
arr = arr.Where(Function(item, index) index <> indx).ToArray 'arr = {"uno", "dos", "cuatro", "cinco"}

Remove first element:

arr = arr.Skip(1).ToArray

Remove last element:

arr = arr.Take(arr.length - 1).ToArray

Selenium IDE - Command to wait for 5 seconds

Your best bet is probably waitForCondition and writing a javascript function that returns true when the map is loaded.

How do I stretch a background image to cover the entire HTML element?

<style>
    { margin: 0; padding: 0; }

    html { 
        background: url('images/yourimage.jpg') no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    }
</style>

Handlebars.js Else If

I usually use this form:

{{#if FriendStatus.IsFriend}}
  ...
{{else}} {{#if FriendStatus.FriendRequested}}
  ...
{{else}}
  ...
{{/if}}{{/if}}

Get the string representation of a DOM node

if using react:

const html = ReactDOM.findDOMNode(document.getElementsByTagName('html')[0]).outerHTML;

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

http://api.jquery.com/jQuery.post/

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

How to write a switch statement in Ruby

Lots of great answers but I thought I would add one factoid.. If you are attempting to compare objects (Classes) make sure you have a space ship method (not a joke) or understand how they are being compared

"Ruby Equality And Object Comparison" is a good discussion on the topic.

How do I define and use an ENUM in Objective-C?

Your typedef needs to be in the header file (or some other file that's #imported into your header), because otherwise the compiler won't know what size to make the PlayerState ivar. Other than that, it looks ok to me.

C compiler for Windows?

I personally have been looking into using MinGW (what Bloodshed uses) with the Code Blocks IDE.

I am also considering using the Digital Mars C/C++ compiler.

Both seem to be well regarded.

How do I ignore files in Subversion?

Use the command svn status on your working copy to show the status of files, files that are not yet under version control (and not ignored) will have a question mark next to them.

As for ignoring files you need to edit the svn:ignore property, read the chapter Ignoring Unversioned Items in the svnbook at http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.ignore.html. The book also describes more about using svn status.

Check if PHP-page is accessed from an iOS device

preg_match("/iPhone|Android|iPad|iPod|webOS/", $_SERVER['HTTP_USER_AGENT'], $matches);
$os = current($matches);

switch($os){
   case 'iPhone': /*do something...*/ break;
   case 'Android': /*do something...*/ break;
   case 'iPad': /*do something...*/ break;
   case 'iPod': /*do something...*/ break;
   case 'webOS': /*do something...*/ break;
}

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.

How to check if an integer is within a range of numbers in PHP?

if (($num >= $lower_boundary) && ($num <= $upper_boundary)) {

You may want to adjust the comparison operators if you want the boundary values not to be valid.

Loop through an array in JavaScript

Array loop:

for(var i = 0; i < things.length; i++){
    var thing = things[i];
    console.log(thing);
}

Object loop:

for(var prop in obj){
    var propValue = obj[prop];
    console.log(propValue);
}

`&mdash;` or `&#8212;` is there any difference in HTML output?

They are exactly the same character. See: http://en.wikipedia.org/wiki/Dash

Barring browser bugs they will display the same in all cases, so the only difference would be concerning code readability, which would point to &mdash;.

Or, if you are using UTF-8 as a charset in your HTML document, you could enter the character directly. That would also display exactly the same.

Is there a difference between using a dict literal and a dict constructor?

the dict() literal is nice when you are copy pasting values from something else (none python) For example a list of environment variables. if you had a bash file, say

FOO='bar'
CABBAGE='good'

you can easily paste then into a dict() literal and add comments. It also makes it easier to do the opposite, copy into something else. Whereas the {'FOO': 'bar'} syntax is pretty unique to python and json. So if you use json a lot, you might want to use {} literals with double quotes.

./xx.py: line 1: import: command not found

It's about Shebang

#!usr/bin/python

This will tell which interpreter to wake up to run the code written in file.

How do you subtract Dates in Java?

If you deal with dates it is a good idea to look at the joda time library for a more sane Date manipulation model.

http://joda-time.sourceforge.net/

Is PowerShell ready to replace my Cygwin shell on Windows?

As my recent experiments led me into depths of PowerShell and .NET calls, I must say that PowerShell can replace Cygwin and Unix shell.

I'm not sure about Perl, but since both PowerShell and Perl are Turing complete as programming languages, I give this as a yes to replacing Perl too.

One thing that PowerShell has above Cygwin and ordinary Bash under *nix, is its ability to perform sandboxed DLL calls, manipulating the operating system via direct API calls, WMI methods and even COM objects. How about launching Internet Explorer via code, then doing whatever you want with its displayed document, effectively emulating a back-end for a Web server?

How about gathering data from SQL servers and other data providers, parse them and export as CSV, mail messages, text and actually any kind of existing and non-existing file formats? (With proper skills of creating a valid file out of data received, of course, but CSV are readily available).

And there is an extra security available via signed cmdlets and scripts, group policies, and execution policies that help prevent malicious code from running on your system even if you run them as administrator.

About what commands are implemented - the answer by Richard lists them and PowerShell's capability of emulating their functionality already.

About whether PowerShell is strong to warrant switching over - this is more a matter of personal preference, although as more and more Windows services are providing PowerShell cmdlets to control them, not using PowerShell with these services present is considered a hindrance. (Hyper-V server is the primary such service, and it also provides the ability to do more with PowerShell cmdlets than with GUI!)

Probably this answer is five years late, but still, if someone performs administrative tasks or general scripting of various stuff on Windows, they should definitely try harnessing PowerShell for their purposes.

Easiest way to open a download window without navigating away from the page

I've been looking for a good way to use javascript to initiate the download of a file, just as this question suggests. However these answers not been helpful. I then did some xbrowser testing and have found that an iframe works best on all modern browsers IE>8.

downloadUrl = "http://example.com/download/file.zip";
var downloadFrame = document.createElement("iframe"); 
downloadFrame.setAttribute('src',downloadUrl);
downloadFrame.setAttribute('class',"screenReaderText"); 
document.body.appendChild(downloadFrame); 

class="screenReaderText" is my class to style content that is present but not viewable.

css:

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}

same as .visuallyHidden in html5boilerplate

I prefer this to the javascript window.open method because if the link is broken the iframe method simply doesn't do anything as opposed to redirecting to a blank page saying the file could not be opened.

window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
window.focus();

SQL Server 2008 - Help writing simple INSERT Trigger

cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.

You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.

Counting array elements in Python

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

Razor MVC Populating Javascript array with Model Array

I was working with a list of toasts (alert messages), List<Alert> from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml file). The JavaScript code below is what worked for me:

var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
    var command = entry.AlertStyle;
    var message = entry.Message;
    if (command === "danger") { command = "error"; }
    toastr[command](message);
});

Get the Year/Month/Day from a datetime in php?

Try below code if you want to use php loop to display

<span>
  <select name="birth_month">
    <?php for( $m=1; $m<=12; ++$m ) { 
      $month_label = date('F', mktime(0, 0, 0, $m, 1));
    ?>
      <option value="<?php echo $month_label; ?>"><?php echo $month_label; ?></option>
    <?php } ?>
  </select> 
</span>
<span>
  <select name="birth_day">
    <?php 
      $start_date = 1;
      $end_date   = 31;
      for( $j=$start_date; $j<=$end_date; $j++ ) {
        echo '<option value='.$j.'>'.$j.'</option>';
      }
    ?>
  </select>
</span>
<span>
  <select name="birth_year">
    <?php 
      $year = date('Y');
      $min = $year - 60;
      $max = $year;
      for( $i=$max; $i>=$min; $i-- ) {
        echo '<option value='.$i.'>'.$i.'</option>';
      }
    ?>
  </select>
</span>

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark - NSSecureCoding

The main purpose of "pragma" is for developer reference.enter image description here

You can easily find a method/Function in a vast thousands of coding lines.

Xcode 11+:

Marker Line in Top

// MARK: - Properties

Marker Line in Top and Bottom

// MARK: - Properties - 

Marker Line only in bottom

// MARK: Properties -

MySQL query finding values in a comma separated string

This will work for sure, and I actually tried it out:

lwdba@localhost (DB test) :: DROP TABLE IF EXISTS shirts;
Query OK, 0 rows affected (0.08 sec)

lwdba@localhost (DB test) :: CREATE TABLE shirts
    -> (<BR>
    -> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> ticketnumber INT,
    -> colors VARCHAR(30)
    -> );<BR>
Query OK, 0 rows affected (0.19 sec)

lwdba@localhost (DB test) :: INSERT INTO shirts (ticketnumber,colors) VALUES
    -> (32423,'1,2,5,12,15'),
    -> (32424,'1,5,12,15,30'),
    -> (32425,'2,5,11,15,28'),
    -> (32426,'1,2,7,12,15'),
    -> (32427,'2,4,8,12,15');
Query OK, 5 rows affected (0.06 sec)
Records: 5  Duplicates: 0  Warnings: 0

lwdba@localhost (DB test) :: SELECT * FROM shirts WHERE LOCATE(CONCAT(',', 1 ,','),CONCAT(',',colors,',')) > 0;
+----+--------------+--------------+
| id | ticketnumber | colors       |
+----+--------------+--------------+
|  1 |        32423 | 1,2,5,12,15  |
|  2 |        32424 | 1,5,12,15,30 |
|  4 |        32426 | 1,2,7,12,15  |
+----+--------------+--------------+
3 rows in set (0.00 sec)

Give it a Try !!!

How do you access a website running on localhost from iPhone browser

Find your system's IP address and on what port you are running the website.

Say your IP address is 121.300.00.250 and your port is 8080.

[Port number: see your web browser while running the page eg: localhost:8080/... then the port number is 8080]

Now in your mobile go to 121.300.00.250:8080/.. and you'll find your website.

IMPORTANT: You have to make sure that your server (e.g Apache Tomcat) is in started condition

Plugin with id 'com.google.gms.google-services' not found

In build.gradle(Module:app) add this code

dependencies {
    ……..
    compile 'com.google.android.gms:play-services:10.0.1’
    ……  
}

If you still have a problem after that, then add this code in build.gradle(Module:app)

defaultConfig {
    ….
    …...
    multiDexEnabled true
}


dependencies {
    …..
    compile 'com.google.android.gms:play-services:10.0.1'
    compile 'com.android.support:multidex:1.0.1'
}

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

Android Transparent TextView?

try to set the transparency with the android-studio designer in activity_main.xml. If you want it to be transparent, write it for example like this for white: White: #FFFFFF, with 50% transparency: #80FFFFFF This is for Kotlin tho, not sure if that will work the same way for basic android (java).

Python 3 ImportError: No module named 'ConfigParser'

You can instead use the mysqlclient package as a drop-in replacement for MySQL-python. It is a fork of MySQL-python with added support for Python 3.

I had luck with simply

pip install mysqlclient

in my python3.4 virtualenv after

sudo apt-get install python3-dev libmysqlclient-dev

which is obviously specific to ubuntu/debian, but I just wanted to share my success :)

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

Timeout for python requests.get entire response

I'm using requests 2.2.1 and eventlet didn't work for me. Instead I was able use gevent timeout instead since gevent is used in my service for gunicorn.

import gevent
import gevent.monkey
gevent.monkey.patch_all(subprocess=True)
try:
    with gevent.Timeout(5):
        ret = requests.get(url)
        print ret.status_code, ret.content
except gevent.timeout.Timeout as e:
    print "timeout: {}".format(e.message)

Please note that gevent.timeout.Timeout is not caught by general Exception handling. So either explicitly catch gevent.timeout.Timeout or pass in a different exception to be used like so: with gevent.Timeout(5, requests.exceptions.Timeout): although no message is passed when this exception is raised.

jQuery returning "parsererror" for ajax request

I have encountered such error but after modifying my response before sending it to the client it worked fine.

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

How can I mark a foreign key constraint using Hibernate annotations?

@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.

How to convert CSV to JSON in Node.js

Me and my buddy created a web service to handle this kind of thing.

Check out Modifly.co for instructions on how to transform CSV to JSON with a single RESTful call.

Read a local text file using Javascript

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
        <div>
            Select a text file: 
            <input type="file" id="fileInput">
        </div>
        <pre id="fileDisplayArea"><pre>

    </div>
<script>
window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);    
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        });
}

</script>

Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                fileDisplayArea.innerText = allText 
            }
        }
    }
    rawFile.send(null);
}

readTextFile("file:///C:/your/path/to/file.txt");
</script>

npx command not found

Updating node helped me, whether that be from the command line or just re-downloading it from the web

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

I got the same error after a Java version update. I just edited the line after "-vm" in the eclipse.ini file, which was pointing to the older and no more existing jre path, and everything worked fine.

Android ListView with Checkbox and all clickable

Below code will help you:

public class DeckListAdapter extends BaseAdapter{

      private LayoutInflater mInflater;
        ArrayList<String> teams=new ArrayList<String>();
        ArrayList<Integer> teamcolor=new ArrayList<Integer>();


        public DeckListAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            teams.add("Upload");
            teams.add("Download");
            teams.add("Device Browser");
            teams.add("FTP Browser");
            teams.add("Options");

            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);


        }



        public int getCount() {
            return teams.size();
        }


        public Object getItem(int position) {
            return position;
        }


        public long getItemId(int position) {
            return position;
        }

       @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;


            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.decklist, null);

                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
                holder.text = (TextView) convertView.findViewById(R.id.textname);

             .......here you can use holder.text.setonclicklistner(new View.onclick.

                        for each textview


                System.out.println(holder.text.getText().toString());

                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
            }



             holder.text.setText(teams.get(position));

             if(position<teamcolor.size())
             holder.text.setBackgroundColor(teamcolor.get(position));

             holder.icon.setImageResource(R.drawable.arraocha);







            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView text;



        }
}

Hope this helps.

How to iterate over a string in C?

An optimized approach:

for (char character = *string; character != '\0'; character = *++string)
{
    putchar(character); // Do something with character.
}

Most C strings are null-terminated, meaning that as soon as the character becomes a '\0' the loop should stop. The *++string is moving the pointer one byte, then dereferencing it, and the loop repeats.

The reason why this is more efficient than strlen() is because strlen already loops through the string to find the length, so you would effectively be looping twice (one more time than needed) with strlen().

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

How to remove Firefox's dotted outline on BUTTONS as well as links?

Yep don't miss !important

button::-moz-focus-inner {
 border: 0 !important;
}

Underline text in UIlabel

NSString *tem =self.detailCustomerCRMCaseLabel.text;
if (tem != nil && ![tem isEqualToString:@""]) {
    NSMutableAttributedString *temString=[[NSMutableAttributedString alloc]initWithString:tem];
    [temString addAttribute:NSUnderlineStyleAttributeName
                      value:[NSNumber numberWithInt:1]
                      range:(NSRange){0,[temString length]}];
    self.detailCustomerCRMCaseLabel.attributedText = temString;
}

Python script to convert from UTF-8 to ASCII

UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.

Transitions on the CSS display property

At the time of this post all major browsers disable CSS transitions if you try to change the display property, but CSS animations still work fine so we can use them as a workaround.

Example Code (you can apply it to your menu accordingly) Demo:

Add the following CSS to your stylesheet:

@-webkit-keyframes fadeIn {
    from { opacity: 0; }
      to { opacity: 1; }
}
@keyframes fadeIn {
    from { opacity: 0; }
      to { opacity: 1; }
}

Then apply the fadeIn animation to the child on parent hover (and of course set display: block):

.parent:hover .child {
    display: block;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

Update 2019 - Method that also supports fading out:

(Some JavaScript code is required)

_x000D_
_x000D_
// We need to keep track of faded in elements so we can apply fade out later in CSS_x000D_
document.addEventListener('animationstart', function (e) {_x000D_
  if (e.animationName === 'fade-in') {_x000D_
      e.target.classList.add('did-fade-in');_x000D_
  }_x000D_
});_x000D_
_x000D_
document.addEventListener('animationend', function (e) {_x000D_
  if (e.animationName === 'fade-out') {_x000D_
      e.target.classList.remove('did-fade-in');_x000D_
   }_x000D_
});
_x000D_
div {_x000D_
    border: 5px solid;_x000D_
    padding: 10px;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
    border-color: red;_x000D_
}_x000D_
_x000D_
.parent .child {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.parent:hover .child {_x000D_
  display: block;_x000D_
  animation: fade-in 1s;_x000D_
}_x000D_
_x000D_
.parent:not(:hover) .child.did-fade-in {_x000D_
  display: block;_x000D_
  animation: fade-out 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade-in {_x000D_
  from {_x000D_
    opacity: 0;_x000D_
  }_x000D_
  to {_x000D_
    opacity: 1;_x000D_
  }_x000D_
}_x000D_
_x000D_
@keyframes fade-out {_x000D_
  from {_x000D_
    opacity: 1;_x000D_
  }_x000D_
  to {_x000D_
    opacity: 0;_x000D_
  }_x000D_
}
_x000D_
<div class="parent">_x000D_
    Parent_x000D_
    <div class="child">_x000D_
        Child_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

Despite all the other great answers none helped me until I found a comment that pointed out this Updating images:

The default pull policy is IfNotPresent which causes the kubelet to skip pulling an image if it already exists.

That's exactly what I wanted, but didn't seem to work.

Reading further said the following:

If you would like to always force a pull, you can do one of the following:

  • omit the imagePullPolicy and use :latest as the tag for the image to use.

When I replaced latest with a version (that I had pushed to minikube's Docker daemon), it worked fine.

$ kubectl create deployment presto-coordinator \
    --image=warsaw-data-meetup/presto-coordinator:beta0
deployment.apps/presto-coordinator created

$ kubectl get deployments
NAME                 READY   UP-TO-DATE   AVAILABLE   AGE
presto-coordinator   1/1     1            1           3s

Find the pod of the deployment (using kubectl get pods) and use kubectl describe pod to find out more on the pod.

Can't load IA 32-bit .dll on a AMD 64-bit platform

I had a problem when run red5(tomcat) on Windows x64 that previous worked under Windows x32, got next error:

 INFO pool-15-thread-1 com.home.launcher.CommandLauncher - Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\....\lib\Data Samolet.dll: Can't find dependent libraries
INFO pool-15-thread-1 com.home.launcher.CommandLauncher - at java.lang.ClassLoader$NativeLibrary.load(Native Method)

Problem solved when I installed Java x32 version and set next

"Environment variables"

"User variables for Home"

JAVA_HOME => C:\Program Files (x86)\Java\jdk.1.6.0_45

"System variables"

Path[at the beginning] => C:\Program Files\Java\jdk.1.8.0_60;..

Getting current device language in iOS?

Solution for iOS 9:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

language = "en-US"

NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];

languageDic will have the needed components

NSString *countryCode = [languageDic objectForKey:@"kCFLocaleCountryCodeKey"];

countryCode = "US"

NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];

languageCode = "en"

Why should I use a container div in HTML?

Well,

The container div is very good to have, because if You want the site centered, You just can't do it just with body or html... But You can, with divs. Why container? Its usually used, just because the code itselve has to be clean and readable. So that is container... It contains all website, in case You want to mess with it around :)

Good luck

Generate an HTML Response in a Java Servlet

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

Kickoff example:

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "Hello World";
        request.setAttribute("message", message); // This will be available as ${message}
        request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
    }

}

And /WEB-INF/hello.jsp look like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>

When opening http://localhost:8080/contextpath/hello this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

Android custom dropdown/popup menu

I know this is an old question, but I've found another answer that worked better for me and it doesn't seem to appear in any of the answers.

Create a layout xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:paddingStart="10dip"
    android:paddingEnd="10dip">

<ImageView
    android:id="@+id/shoe_select_icon"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="center_vertical"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/shoe_select_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="20sp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"/>

</LinearLayout>

Create a ListPopupWindow and a map with the content:

ListPopupWindow popupWindow;
List<HashMap<String, Object>> data = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
    map.put(TITLE, getString(R.string.left));
    map.put(ICON, R.drawable.left);
    data.add(map);
    map = new HashMap<>();
    map.put(TITLE, getString(R.string.right));
    map.put(ICON, R.drawable.right);
    data.add(map);

Then on click, display the menu using this function:

private void showListMenu(final View anchor) {
    popupWindow = new ListPopupWindow(this);

    ListAdapter adapter = new SimpleAdapter(
            this,
            data,
            R.layout.shoe_select,
            new String[] {TITLE, ICON}, // These are just the keys that the data uses (constant strings)
            new int[] {R.id.shoe_select_text, R.id.shoe_select_icon}); // The view ids to map the data to

    popupWindow.setAnchorView(anchor);
    popupWindow.setAdapter(adapter);
    popupWindow.setWidth(400);
    popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                    devicesAdapter.setSelectedLeftPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                case 1:
                    devicesAdapter.setSelectedRightPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                default:
                    break;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    devicesAdapter.notifyDataSetChanged();
                }
            });
            popupWindow.dismiss();
        }
    });
    popupWindow.show();
}

Simple excel find and replace for formulas

You can also click on the Formulas tab in Excel and select Show Formulas, then use the regular "Find" and "Replace" function. This should not affect the rest of your formula.

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

As c-smile mentioned: Just need to remove the apostrophes in the url():

<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>

Demo here

Unsetting array values in a foreach loop

One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.

For instance :

$arr = array(
    'a' => 123,
    'b' => 456,
    'c' => 789, 
);

foreach ($arr as $key => $item) {
    if ($item == 456) {
        unset($arr[$key]);
    }
}

var_dump($arr);

Will give you this array, in the end :

array
  'a' => int 123
  'c' => int 789


Which means that, in your case, something like this should do the trick :

foreach($images as $key => $image)
{
    if($image == 'http://i27.tinypic.com/29yk345.gif' ||
    $image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
    $image == 'http://i42.tinypic.com/9pp2456x.gif')
    {
        unset($images[$key]);
    }
}

How do I return a proper success/error message for JQuery .ajax() using PHP?

...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.

Typically, right mouse->inspect on your html page. Then look in the error console for errors like

Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Complex nesting of partials and templates

I too was struggling with nested views in Angular.

Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.

Here is an example application that uses multiple levels of views nesting

app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default
$urlRouterProvider.otherwise("/view1");

$stateProvider
    .state('view1', {
        url: '/view1',
        templateUrl: 'partials/view1.html',
        controller: 'view1.MainController'
    })
    .state('view1.nestedViews', {
        url: '/view1',
        views: {
            'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
            'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
            'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }
        }
    })

    .state('view2', {
        url: '/view2',
    })

    .state('view3', {
        url: '/view3',
    })

    .state('view4', {
        url: '/view4',
    });
});

As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.

How to convert .pem into .key?

I assume you want the DER encoded version of your PEM private key.

openssl rsa -outform der -in private.pem -out private.key

Problems when trying to load a package in R due to rJava

If you have this issue with macOS, there is no easy way here: ( Especially, when you want to use R3.4. I have been there already.

R 3.4, rJava, macOS and even more mess

For R3.3 it's a little bit easier (R3.3 was compiled using different compiler).

R, Java, rJava and macOS adventures

Receiving login prompt using integrated windows authentication

Windows authentication in IIS7.0 or IIS7.5 does not work with kerberos (provider=Negotiate) when the application pool identity is ApplicationPoolIdentity One has to use Network Service or another build-in account. Another possibility is to use NTLM to get Windows Authenticatio to work (in Windows Authentication, Providers, put NTLM on top or remove negotiate)

chris van de vijver

How to format column to number format in Excel sheet?

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

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

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

How can you make a custom keyboard in Android?

I came across this post recently when I was trying to decide what method to use to create my own custom keyboard. I found the Android system API to be very limited, so I decided to make my own in-app keyboard. Using Suragch's answer as the basis for my research, I went on to design my own keyboard component. It's posted on GitHub with an MIT license. Hopefully this will save somebody else a lot of time and headache.

The architecture is pretty flexible. There is one main view (CustomKeyboardView) that you can inject with whatever keyboard layout and controller you want.

You just have to declare the CustomKeyboardView in you activity xml (you can do it programmatically as well):

    <com.donbrody.customkeyboard.components.keyboard.CustomKeyboardView
    android:id="@+id/customKeyboardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />

Then register your EditText's with it and tell it what type of keyboard they should use:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val numberField: EditText = findViewById(R.id.testNumberField)
    val numberDecimalField: EditText = findViewById(R.id.testNumberDecimalField)
    val qwertyField: EditText = findViewById(R.id.testQwertyField)

    keyboard = findViewById(R.id.customKeyboardView)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER, numberField)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.NUMBER_DECIMAL, numberDecimalField)
    keyboard.registerEditText(CustomKeyboardView.KeyboardType.QWERTY, qwertyField)
}

The CustomKeyboardView handles the rest!

I've got the ball rolling with a Number, NumberDecimal, and QWERTY keyboard. Feel free to download it and create your own layouts and controllers. It looks like this:

android custom keyboard gif landscape

enter image description here

Even if this is not the architecture you decide to go with, hopefully it'll be helpful to see the source code for a working in-app keyboard.

Again, here's the link to the project: Custom In-App Keyboard

EDIT: I'm no longer an Android developer, and I no longer maintain this GitHub project. There are probably more modern approaches and architectures at this point, but please feel free to reference the GitHub project if you'd like and fork it.

How do I clear all variables in the middle of a Python script?

In Spyder one can configure the IPython console for each Python file to clear all variables before each execution in the Menu Run -> Configuration -> General settings -> Remove all variables before execution.

How do I make the scrollbar on a div only visible when necessary?

try

<div id="boxscroll2" style="overflow: auto; position: relative;" tabindex="5001">

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I'd just like to add that @JoinColumn does not always have to be related to the physical information location as this answer suggests. You can combine @JoinColumn with @OneToMany even if the parent table has no table data pointing to the child table.

How to define unidirectional OneToMany relationship in JPA

Unidirectional OneToMany, No Inverse ManyToOne, No Join Table

It seems to only be available in JPA 2.x+ though. It's useful for situations where you want the child class to just contain the ID of the parent, not a full on reference.

Left padding a String with Zeros

Here's my solution:

String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);

Output: 00000101

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

This did it for me.

https://gist.github.com/dideler/60c9ce184198666e5ab4

Short and to the point. I honestly don't aim to understand the guts of PostgreSQL, I want to get stuff done.

Calculate time difference in Windows batch file

Aacini's latest code showcases an awesome variable substitution method.
It's a shame it's not Regional format proof - it fails on so many levels.
Here's a short fix that keeps the substitution+math method intact:

@echo off
setlocal EnableDelayedExpansion

set "startTime=%time: =0%" & rem AveYo: fix single digit hour

set /P "=Any process here..."

set "endTime=%time: =0%" & rem AveYo: fix single digit hour

rem Aveyo: Regional format fix with just one aditional line
for /f "tokens=1-3 delims=0123456789" %%i in ("%endTime%") do set "COLON=%%i" & set "DOT=%%k" 

rem Get elapsed time:
set "end=!endTime:%DOT%=%%100)*100+1!" & set "start=!startTime:%DOT%=%%100)*100+1!"
set /A "elap=((((10!end:%COLON%=%%100)*60+1!%%100)-((((10!start:%COLON%=%%100)*60+1!%%100)"

rem Aveyo: Fix 24 hours 
set /A "elap=!elap:-=8640000-!"

rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"

echo Start:    %startTime%
echo End:      %endTime%
echo Elapsed:  %hh:~1%%COLON%%mm:~1%%COLON%%ss:~1%%DOT%%cc:~1% & rem AveYo: display as regional
pause

*

"Lean and Mean" TIMER with Regional format, 24h and mixed input support
Adapting Aacini's substitution method body, no IF's, just one FOR (my regional fix)

1: File timer.bat placed somewhere in %PATH% or the current dir

@echo off & rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

Usage:
timer & echo start_cmds & timeout /t 3 & echo end_cmds & timer
timer & timer "23:23:23,00"
timer "23:23:23,00" & timer
timer "13.23.23,00" & timer "03:03:03.00"
timer & timer "0:00:00.00" no & cmd /v:on /c echo until midnight=!timer_end!
Input can now be mixed, for those unlikely, but possible time format changes during execution

2: Function :timer bundled with the batch script (sample usage below):

@echo off
set "TIMER=call :timer" & rem short macro
echo.
echo EXAMPLE:
call :timer
timeout /t 3 >nul & rem Any process here..
call :timer
echo.
echo SHORT MACRO:
%TIMER% & timeout /t 1 & %TIMER% 
echo.
echo TEST INPUT:
set "start=22:04:04.58"
set "end=04.22.44,22"
echo %start% ~ start & echo %end% ~ end
call :timer "%start%"
call :timer "%end%"
echo.
%TIMER% & %TIMER% "00:00:00.00" no 
echo UNTIL MIDNIGHT: %timer_end%
echo.
pause 
exit /b

:: to test it, copy-paste both above and below code sections

rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support 
:timer Usage " call :timer [input - optional] [no - optional]" :i Result printed on second call, saved to timer_end 
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

Better naming in Tuple classes than "Item1", "Item2"

This is very annoying and I expect future versions of C# will address this need. I find the easiest work around to be either use a different data structure type or rename the "items" for your sanity and for the sanity of others reading your code.

Tuple<ApiResource, JSendResponseStatus> result = await SendApiRequest();
ApiResource apiResource = result.Item1;
JSendResponseStatus jSendStatus = result.Item2;

how to install python distutils

If you are unable to install with either of these:

sudo apt-get install python-distutils
sudo apt-get install python3-distutils

Try this instead:

sudo apt-get install python-distutils-extra

Ref: https://groups.google.com/forum/#!topic/beagleboard/RDlTq8sMxro

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Building on @SotiriosDelimanolis's comment, here is a method to deal with URLs (such as file:...) and non-URLs (such as C:...), using Spring's FileSystemResource:

public FileSystemResource get(String file) {
    try {
        // First try to resolve as URL (file:...)
        Path path = Paths.get(new URL(file).toURI());
        FileSystemResource resource = new FileSystemResource(path.toFile());
        return resource;
    } catch (URISyntaxException | MalformedURLException e) {
        // If given file string isn't an URL, fall back to using a normal file 
        return new FileSystemResource(file);
    }
}

Simple example of threading in C++

Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

Using boost::thread you'd get something like:

#include <boost/thread.hpp>

void task1() { 
    // do stuff
}

void task2() { 
    // do stuff
}

int main (int argc, char ** argv) {
    using namespace boost; 
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    return 0;
}

.NET Global exception handler in console application

If you have a single-threaded application, you can use a simple try/catch in the Main function, however, this does not cover exceptions that may be thrown outside of the Main function, on other threads, for example (as noted in other comments). This code demonstrates how an exception can cause the application to terminate even though you tried to handle it in Main (notice how the program exits gracefully if you press enter and allow the application to exit gracefully before the exception occurs, but if you let it run, it terminates quite unhappily):

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void DemoThread()
{
   for(int i = 5; i >= 0; i--)
   {
      Console.Write("24/{0} =", i);
      Console.Out.Flush();
      Console.WriteLine("{0}", 24 / i);
      System.Threading.Thread.Sleep(1000);
      if (exiting) return;
   }
}

You can receive notification of when another thread throws an exception to perform some clean up before the application exits, but as far as I can tell, you cannot, from a console application, force the application to continue running if you do not handle the exception on the thread from which it is thrown without using some obscure compatibility options to make the application behave like it would have with .NET 1.x. This code demonstrates how the main thread can be notified of exceptions coming from other threads, but will still terminate unhappily:

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
   Console.WriteLine("Notified of a thread exception... application is terminating.");
}

static void DemoThread()
{
   for(int i = 5; i >= 0; i--)
   {
      Console.Write("24/{0} =", i);
      Console.Out.Flush();
      Console.WriteLine("{0}", 24 / i);
      System.Threading.Thread.Sleep(1000);
      if (exiting) return;
   }
}

So in my opinion, the cleanest way to handle it in a console application is to ensure that every thread has an exception handler at the root level:

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void DemoThread()
{
   try
   {
      for (int i = 5; i >= 0; i--)
      {
         Console.Write("24/{0} =", i);
         Console.Out.Flush();
         Console.WriteLine("{0}", 24 / i);
         System.Threading.Thread.Sleep(1000);
         if (exiting) return;
      }
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception on the other thread");
   }
}

Read data from SqlDataReader

I have a helper function like:

  public static string GetString(object o)
    {
        if (o == DBNull.Value)
            return "";

        return o.ToString();
    }

then I use it to extract the string:

 tbUserName.Text = GetString(reader["UserName"]);

Cannot attach the file *.mdf as database

To fix this using SQL SERVER Management Studio

Your problem: You get an error such as 'Cannot attach the file 'YourDB.mdf' as database 'YourConnStringNamedContext';

Reason: happens because you deleted the backing files .mdf, ldf without actually deleting the database within the running instance of SqlLocalDb; re-running the code in VS won't help because you cannot re-create a DB with the same name (and that's why renaming works, but leaves the old phantom db name lying around).

The Fix: I am using VS2012, adopt similarly for a different version.

Navigate to below path and enter

c:\program files\microsoft sql server\110\Tools\Binn>sqllocaldb info

Above cmd shows the instance names, including 'v11.0'

If the instance is already running, enter at the prompt

sqllocaldb info v11.0

Note the following info Owner: YourPCName\Username , State: Running , Instance pipe name: np:\.\pipe\LOCALDB#12345678\tsql\query , where 123456789 is some random alphanumeric

If State is not running or stopped, start the instance with

sqllocaldb start v11.0

and extract same info as above.

In the SS Management Studio 'Connect' dialog box enter

server name: np:\.\pipe\LOCALDB#12345678\tsql\query

auth: Windows auth

user name: (same as Owner, it is grayed out for Win. auth.)

Once connected, find the phantom DB which you deleted (e.g. YourDB.mdf should have created a db named YourDB), and really delete it.

Done! Once it's gone, VS EF should have no problem re-creating it.

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

How to read data from a zip file without having to unzip the entire file

Here is how a UTF8 text file can be read from a zip archive into a string variable (.NET Framework 4.5 and up):

string zipFileFullPath = "{{TypeYourZipFileFullPathHere}}";
string targetFileName = "{{TypeYourTargetFileNameHere}}";
string text = new string(
            (new System.IO.StreamReader(
             System.IO.Compression.ZipFile.OpenRead(zipFileFullPath)
             .Entries.Where(x => x.Name.Equals(targetFileName,
                                          StringComparison.InvariantCulture))
             .FirstOrDefault()
             .Open(), Encoding.UTF8)
             .ReadToEnd())
             .ToArray());

Serializing enums with Jackson

@JsonFormat(shape= JsonFormat.Shape.OBJECT)
public enum SomeEnum

available since https://github.com/FasterXML/jackson-databind/issues/24

just tested it works with version 2.1.2

answer to TheZuck:

I tried your example, got Json:

{"events":[{"type":"ADMIN"}]}

My code:

@RequestMapping(value = "/getEvent") @ResponseBody
  public EventContainer getEvent() {
    EventContainer cont = new EventContainer();
    cont.setEvents(Event.values());
    return cont;
 }

class EventContainer implements Serializable {

  private Event[] events;

  public Event[] getEvents() {
    return events;
 }

 public void setEvents(Event[] events) {
   this.events = events;
 }
}

and dependencies are:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson.version}</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
  <exclusions>
    <exclusion>
      <artifactId>jackson-annotations</artifactId>
      <groupId>com.fasterxml.jackson.core</groupId>
    </exclusion>
    <exclusion>
      <artifactId>jackson-core</artifactId>
      <groupId>com.fasterxml.jackson.core</groupId>
    </exclusion>
  </exclusions>
</dependency>

<jackson.version>2.1.2</jackson.version>

How to push local changes to a remote git repository on bitbucket

This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.

To push all local branches to the remote repository, use --all:

git push REMOTENAME --all
git push --all

or specify all branches you want to push:

git push REMOTENAME master exp-branch-a anotherbranch bugfix

In addition, it's useful to add -u to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.

How to call a parent method from child class in javascript?

Here's a nice way for child objects to have access to parent properties and methods using JavaScript's prototype chain, and it's compatible with Internet Explorer. JavaScript searches the prototype chain for methods and we want the child’s prototype chain to looks like this:

Child instance -> Child’s prototype (with Child methods) -> Parent’s prototype (with Parent methods) -> Object prototype -> null

The child methods can also call shadowed parent methods, as shown at the three asterisks *** below.

Here’s how:

_x000D_
_x000D_
//Parent constructor_x000D_
function ParentConstructor(firstName){_x000D_
    //add parent properties:_x000D_
    this.parentProperty = firstName;_x000D_
}_x000D_
_x000D_
//add 2 Parent methods:_x000D_
ParentConstructor.prototype.parentMethod = function(argument){_x000D_
    console.log(_x000D_
            "Parent says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ParentConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Parent! argument=" + argument);_x000D_
};_x000D_
_x000D_
//Child constructor    _x000D_
function ChildConstructor(firstName, lastName){_x000D_
    //first add parent's properties_x000D_
    ParentConstructor.call(this, firstName);_x000D_
_x000D_
    //now add child's properties:_x000D_
    this.childProperty = lastName;_x000D_
}_x000D_
_x000D_
//insert Parent's methods into Child's prototype chain_x000D_
var rCopyParentProto = Object.create(ParentConstructor.prototype);_x000D_
rCopyParentProto.constructor = ChildConstructor;_x000D_
ChildConstructor.prototype = rCopyParentProto;_x000D_
_x000D_
//add 2 Child methods:_x000D_
ChildConstructor.prototype.childMethod = function(argument){_x000D_
    console.log(_x000D_
            "Child says: argument=" + argument +_x000D_
            ", parentProperty=" + this.parentProperty +_x000D_
            ", childProperty=" + this.childProperty_x000D_
    );_x000D_
};_x000D_
_x000D_
ChildConstructor.prototype.commonMethod = function(argument){_x000D_
    console.log("Hello from Child! argument=" + argument);_x000D_
_x000D_
    // *** call Parent's version of common method_x000D_
    ParentConstructor.prototype.commonMethod(argument);_x000D_
};_x000D_
_x000D_
//create an instance of Child_x000D_
var child_1 = new ChildConstructor('Albert', 'Einstein');_x000D_
_x000D_
//call Child method_x000D_
child_1.childMethod('do child method');_x000D_
_x000D_
//call Parent method_x000D_
child_1.parentMethod('do parent method');_x000D_
_x000D_
//call common method_x000D_
child_1.commonMethod('do common method');
_x000D_
_x000D_
_x000D_

How to use radio on change event?

document.addEventListener('DOMContentLoaded', () => {
  const els = document.querySelectorAll('[name="bedStatus"]');

  const capitalize = (str) =>
    `${str.charAt(0).toUpperCase()}${str.slice(1)}`;

  const handler = (e) => alert(
    `${capitalize(e.target.value)} Thai Gayo${e.target.value === 'allot' ? ' Bhai' : ''}`
  );

  els.forEach((el) => {
    el.addEventListener('change', handler);
  });
});

ImportError: No module named google.protobuf

To find where the name google clashes .... try this:

python3

then >>> help('google')

... I got info about google-auth:

NAME
    google

PACKAGE CONTENTS
    auth (package)
    oauth2 (package)

Also then try

pip show google-auth

Then

sudo pip3 uninstall google-auth

... and re-try >>> help('google')

I then see protobuf:

NAME
    google

PACKAGE CONTENTS
    protobuf (package)

Jenkins: Can comments be added to a Jenkinsfile?

Comments work fine in any of the usual Java/Groovy forms, but you can't currently use groovydoc to process your Jenkinsfile (s).

First, groovydoc chokes on files without extensions with the wonderful error

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
    at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at org.codehaus.groovy.tools.groovydoc.SimpleGroovyClassDocAssembler.<init>(SimpleGroovyClassDocAssembler.java:67)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.parseGroovy(GroovyRootDocBuilder.java:131)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.getClassDocsFromSingleSource(GroovyRootDocBuilder.java:83)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.processFile(GroovyRootDocBuilder.java:213)
    at org.codehaus.groovy.tools.groovydoc.GroovyRootDocBuilder.buildTree(GroovyRootDocBuilder.java:168)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool.add(GroovyDocTool.java:82)
    at org.codehaus.groovy.tools.groovydoc.GroovyDocTool$add.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at org.codehaus.groovy.tools.groovydoc.Main.execute(Main.groovy:214)
    at org.codehaus.groovy.tools.groovydoc.Main.main(Main.groovy:180)
    ... 6 more

... and second, as far as I can tell Javadoc-style commments at the start of a groovy script are ignored. So even if you copy/rename your Jenkinsfile to Jenkinsfile.groovy, you won't get much useful output.

I want to be able to use a

/**
 * Document my Jenkinsfile's overall purpose here
 */

comment at the start of my Jenkinsfile. No such luck (yet).

groovydoc will process classes and methods defined in your Jenkinsfile if you pass -private to the command, though.

How to save an activity state using save instance state?

Meanwhile I do in general no more use

Bundle savedInstanceState & Co

The life cycle is for most activities too complicated and not necessary.

And Google states itself, it is NOT even reliable.

My way is to save any changes immediately in the preferences:

 SharedPreferences p;
 p.edit().put(..).commit()

In some way SharedPreferences work similar like Bundles. And naturally and at first such values have to be read from preferences.

In the case of complex data you may use SQLite instead of using preferences.

When applying this concept, the activity just continues to use the last saved state, regardless of whether it was an initial open with reboots in between or a reopen due to the back stack.

jQuery selector for inputs with square brackets in the name attribute

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">

JQuery:

var value = $('input[name="myName[1][data]"]').val();

sscanf in Python

Python doesn't have an sscanf equivalent built-in, and most of the time it actually makes a whole lot more sense to parse the input by working with the string directly, using regexps, or using a parsing tool.

Probably mostly useful for translating C, people have implemented sscanf, such as in this module: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/

In this particular case if you just want to split the data based on multiple split characters, re.split is really the right tool.

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

The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:

Maven defines 4 items of a build process:

  1. Lifecycle

    Three built-in lifecycles (aka build lifecycles): default, clean, site. (Lifecycle Reference)

  2. Phase

    Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

  3. Plugin

    An artifact that provides one or more goals.

    Based on packaging type (jar, war, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)

  4. Goal

    The task (action) that is executed. A plugin can have one or more goals.

    One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

Maven can be invoked with:

  1. a phase (e.g clean, package)
  2. <plugin-prefix>:<goal> (e.g. dependency:copy-dependencies)
  3. <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> (e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile)

with one or more combinations of any or all, e.g.:

mvn clean dependency:copy-dependencies package

How do I get values from a SQL database into textboxes using C#?

Make a connection and open it.

con = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=<database_name>)));User Id =<userid>; Password =<password>");
con.Open();

Write the select query:

string sql = "select * from Pending_Tasks";

Create a command object:

OracleCommand cmd = new OracleCommand(sql, con);

Execute the command and put the result in a object to read it.

OracleDataReader r = cmd.ExecuteReader();

now start reading from it.

while (read.Read())
{
 CustID.Text = (read["Customer_ID"].ToString());
 CustName.Text = (read["Customer_Name"].ToString());
 Add1.Text = (read["Address_1"].ToString());
 Add2.Text = (read["Address_2"].ToString());
 PostBox.Text = (read["Postcode"].ToString());
 PassBox.Text = (read["Password"].ToString());
 DatBox.Text = (read["Data_Important"].ToString());
 LanNumb.Text = (read["Landline"].ToString());
 MobNumber.Text = (read["Mobile"].ToString());
 FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();

Add this too using Oracle.ManagedDataAccess.Client;

How do I read image data from a URL in Python?

In Python3 the StringIO and cStringIO modules are gone.

In Python3 you should use:

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

var https = require('https');
https.globalAgent.options.secureProtocol = 'SSLv3_method';

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

How can I format date by locale in Java?

Take a look at java.text.DateFormat. Easier to use (with a bit less power) is the derived class, java.text.SimpleDateFormat

And here is a good intro to Java internationalization: http://java.sun.com/docs/books/tutorial/i18n/index.html (the "Formatting" section addressing your problem, and more).

invalid conversion from 'const char*' to 'char*'

First of all this code snippet

char *addr=NULL;
strcpy(addr,retstring().c_str());

is invalid because you did not allocate memory where you are going to copy retstring().c_str().

As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.

How to resolve Value cannot be null. Parameter name: source in linq?

When you call a Linq statement like this:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.

logger configuration to log to file and print to stdout

Logging to stdout and rotating file with different levels and formats:

import logging
import logging.handlers
import sys

if __name__ == "__main__":

    # Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.
    logging.getLogger().setLevel(logging.NOTSET)

    # Add stdout handler, with level INFO
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formater = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')
    console.setFormatter(formater)
    logging.getLogger().addHandler(console)

    # Add file rotating handler, with level DEBUG
    rotatingHandler = logging.handlers.RotatingFileHandler(filename='rotating.log', maxBytes=1000, backupCount=5)
    rotatingHandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    rotatingHandler.setFormatter(formatter)
    logging.getLogger().addHandler(rotatingHandler)

    log = logging.getLogger("app." + __name__)

    log.debug('Debug message, should only appear in the file.')
    log.info('Info message, should appear in file and stdout.')
    log.warning('Warning message, should appear in file and stdout.')
    log.error('Error message, should appear in file and stdout.')

Convert Month Number to Month Name Function in SQL

in addition to original

SELECT DATENAME(m, str(2) + '/1/2011')

you can do this

SELECT DATENAME(m, str([column_name]) + '/1/2011')

this way you get names for all rows in a table. where [column_name] represents a integer column containing numeric value 1 through 12

2 represents any integer, by contact string i created a date where i can extract the month. '/1/2011' can be any date

if you want to do this with variable

DECLARE @integer int;

SET @integer = 6;

SELECT DATENAME(m, str(@integer) + '/1/2011')

Convert base class to derived class

No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.

Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.

List of all special characters that need to be escaped in a regex

To escape you could just use this from Java 1.5:

Pattern.quote("$test");

You will match exacty the word $test

How to upload file to server with HTTP POST multipart/form-data?

I know this is and old thread, but I was fighting with this and I would like to share my solution.

This solution works with HttpClient and MultipartFormDataContent, from System.Net.Http. You can release it with .NET Core 1.0 or higher, or .NET Framework 4.5 or higher.

As a quick summary, it's an asynchronous method that receives as parameters the URL in which you want to perform the POST, a key/value collection for sending strings, and a key/value collection for sending files.

private static async Task<HttpResponseMessage> Post(string url, NameValueCollection strings, NameValueCollection files)
{
    var formContent = new MultipartFormDataContent(/* If you need a boundary, you can define it here */);

    // Strings
    foreach (string key in strings.Keys)
    {
        string inputName = key;
        string content = strings[key];

        formContent.Add(new StringContent(content), inputName);
    }

    // Files
    foreach (string key in files.Keys)
    {
        string inputName = key;
        string fullPathToFile = files[key];

        FileStream fileStream = File.OpenRead(fullPathToFile);
        var streamContent = new StreamContent(fileStream);
        var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
        formContent.Add(fileContent, inputName, Path.GetFileName(fullPathToFile));
    }

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync(url, formContent);
    //string stringContent = await response.Content.ReadAsStringAsync(); // If you need to read the content

    return response;
}

You can prepare your POST like this (you can add so many strings and files as you need):

string url = @"http://yoursite.com/upload.php"

NameValueCollection strings = new NameValueCollection();
strings.Add("stringInputName1", "The content for input 1");
strings.Add("stringInputNameN", "The content for input N");

NameValueCollection files = new NameValueCollection();
files.Add("fileInputName1", @"FullPathToFile1"); // Path + filename
files.Add("fileInputNameN", @"FullPathToFileN");

And finally, call the method like this:

var result = Post(url, strings, files).GetAwaiter().GetResult();

If you want, you can check your status code, and show the reason as below:

if (result.StatusCode == HttpStatusCode.OK)
{
    // Logic if all was OK
}
else
{
    // You can show a message like this:
    Console.WriteLine(string.Format("Error. StatusCode: {0} | ReasonPhrase: {1}", result.StatusCode, result.ReasonPhrase));
}

And if someone need it, here I let a small example of how to receive store a file with PHP (at the other side of our .Net app):

<?php

if (isset($_FILES['fileInputName1']) && $_FILES['fileInputName1']['error'] === UPLOAD_ERR_OK)
{
  $fileTmpPath = $_FILES['fileInputName1']['tmp_name'];
  $fileName = $_FILES['fileInputName1']['name'];

  move_uploaded_file($fileTmpPath, '/the/final/path/you/want/' . $fileName);
}

I hope you find it useful, I am attentive to your questions.

Inverse of a matrix using numpy

What about inv?

e.g.: my_inverse_array = inv(my_array)

Setting Authorization Header of HttpClient

Use Basic Authorization And Json Parameters.

using (HttpClient client = new HttpClient())
{
    var request_json = "your json string";

    var content = new StringContent(request_json, Encoding.UTF8, "application/json");

    var authenticationBytes = Encoding.ASCII.GetBytes("YourUsername:YourPassword");

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(authenticationBytes));
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var result = await client.PostAsync("YourURL", content);

    var result_string = await result.Content.ReadAsStringAsync();
}

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

How to display pdf in php

easy if its pdf or img use

return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));

password for postgres

Set the default password in the .pgpass file. If the server does not save the password, it is because it is not set in the .pgpass file, or the permissions are open and the file is therefore ignored.

Read more about the password file here.

Also, be sure to check the permissions: on *nix systems the permissions on .pgpass must disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored.

Have you tried logging-in using PGAdmin? You can save the password there, and modify the pgpass file.

Can't create handler inside thread that has not called Looper.prepare()

Handler handler2;  
HandlerThread handlerThread=new HandlerThread("second_thread");
handlerThread.start();
handler2=new Handler(handlerThread.getLooper());

Now handler2 will use a different Thread to handle the messages than the main Thread.

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

Accessing nested JavaScript objects and arrays by string path

Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.

function get(obj, str) {
  return str.split(/\.|\[/g).map(function(crumb) {
    return crumb.replace(/\]$/, '').trim().replace(/^(["'])((?:(?!\1)[^\\]|\\.)*?)\1$/, (match, quote, str) => str.replace(/\\(\\)?/g, "$1"));
  }).reduce(function(obj, prop) {
    return obj ? obj[prop] : undefined;
  }, obj);
}

Log4Net configuring log level

you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters

in ur appender section add

<filter type="log4net.Filter.LevelMatchFilter">
    <levelToMatch value="Info" />
    <acceptOnMatch value="true" />
</filter>

the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters

Install numpy on python3.3 - Install pip for python3

On fedora/rhel/centos you need to

sudo yum install -y python3-devel

before

mkvirtualenv -p /usr/bin/python3.3 test-3.3
pip install numpy

otherwise you'll get

SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

What is the size limit of a post request?

As David pointed out, I would go with KB in most cases.

php_value post_max_size 2K

Note: my form is simple, just a few text boxes, not long text.

(PHP shorthand for KB is K, as outlined here.)

javac error: Class names are only accepted if annotation processing is explicitly requested

How you can reproduce this cryptic error on the Ubuntu terminal:

Put this in a file called Main.java:

public Main{
    public static void main(String[] args){
        System.out.println("ok");
    }
}

Then compile it like this:

user@defiant /home/user $ javac Main
error: Class names, 'Main', are only accepted if 
annotation processing is explicitly requested
1 error

It's because you didn't specify .java at the end of Main.

Do it like this, and it works:

user@defiant /home/user $ javac Main.java
user@defiant /home/user $

Slap your forehead now and grumble that the error message is so cryptic.

AppStore - App status is ready for sale, but not in app store

You may also need to provide your contact info, bank info, and tax info in this page so it will allow your last release on App Store:

https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/6.0

Fuzzy matching using T-SQL

Since the first release of Master Data Services, you've got access to more advanced fuzzy logic algorithms than what SOUNDEX implements. So provided that you've got MDS installed, you'll be able to find a function called Similarity() in the mdq schema (MDS database).

More info on how it works: http://blog.hoegaerden.be/2011/02/05/finding-similar-strings-with-fuzzy-logic-functions-built-into-mds/

Adding div element to body or document in JavaScript

Instead of replacing everything with innerHTML try:

document.body.appendChild(myExtraNode);

Class name does not name a type in C++

The solution to my problem today was slightly different that the other answers here.

In my case, the problem was caused by a missing close bracket (}) at the end of one of the header files in the include chain.

Essentially, what was happening was that A was including B. Because B was missing a } somewhere in the file, the definitions in B were not correctly found in A.

At first I thought I have circular dependency and added the forward declaration B. But then it started complaining about the fact that something in B was an incomplete type. That's how I thought of double checking the files for syntax errors.

Is it possible to get element from HashMap by its position?

HashMap - and the underlying data structure - hash tables, do not have a notion of position. Unlike a LinkedList or Vector, the input key is transformed to a 'bucket' where the value is stored. These buckets are not ordered in a way that makes sense outside the HashMap interface and as such, the items you put into the HashMap are not in order in the sense that you would expect with the other data structures

Java ArrayList of Doubles

You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:

new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));

If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:

new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));

How to create a custom string representation for a class object?

Ignacio Vazquez-Abrams' approved answer is quite right. It is, however, from the Python 2 generation. An update for the now-current Python 3 would be:

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object, metaclass=MC):
    pass

print(C)

If you want code that runs across both Python 2 and Python 3, the six module has you covered:

from __future__ import print_function
from six import with_metaclass

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(with_metaclass(MC)):
    pass

print(C)

Finally, if you have one class that you want to have a custom static repr, the class-based approach above works great. But if you have several, you'd have to generate a metaclass similar to MC for each, and that can get tiresome. In that case, taking your metaprogramming one step further and creating a metaclass factory makes things a bit cleaner:

from __future__ import print_function
from six import with_metaclass

def custom_class_repr(name):
    """
    Factory that returns custom metaclass with a class ``__repr__`` that
    returns ``name``.
    """
    return type('whatever', (type,), {'__repr__': lambda self: name})

class C(with_metaclass(custom_class_repr('Wahaha!'))): pass

class D(with_metaclass(custom_class_repr('Booyah!'))): pass

class E(with_metaclass(custom_class_repr('Gotcha!'))): pass

print(C, D, E)

prints:

Wahaha! Booyah! Gotcha!

Metaprogramming isn't something you generally need everyday—but when you need it, it really hits the spot!

git: How to ignore all present untracked files?

If you have a lot of untracked files, and don't want to "gitignore" all of them, note that, since git 1.8.3 (April, 22d 2013), git status will mention the --untracked-files=no even if you didn't add that option in the first place!

"git status" suggests users to look into using --untracked=no option when it takes too long.

Correct set of dependencies for using Jackson mapper

<properties>
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.4.4</jackson.version>
</properties>
<dependencies>
   <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
</dependencies>

you have a ObjectMapper (from Jackson Databind package) handy. if so, you can do:

JsonFactory factory = objectMapper.getFactory();

Source: https://github.com/FasterXML/jackson-core

So, the 3 "fasterxml" dependencies which you already have in u'r pom are enough for ObjectMapper as it includes jackson-databind.

File Upload ASP.NET MVC 3.0

How i do mine is pretty much as above ill show you my code and how to use it with a MYSSQL DB...

Document table in DB -

int Id ( PK ), string Url, string Description, CreatedBy, TenancyId DateUploaded

The above code ID, being the Primary key, URL being the name of the file ( with file type on the end ), file description to ouput on documents view, CreatedBy being who uploaded the file, tenancyId, dateUploaded

inside the view you must define the enctype or it will not work correctly.

@using (Html.BeginForm("Upload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="input-group">
    <label for="file">Upload a document:</label>
    <input type="file" name="file" id="file" />
</div>
}

The above code will give you the browse button, then inside my project I have a class basically called IsValidImage which just checks the filesize is under your specified max size, checks if its an IMG file, this is all in a class bool function. So if true returns true.

public static bool IsValidImage(HttpPostedFileBase file, double maxFileSize, ModelState ms )
{
    // make sur the file isnt null.
    if( file == null )
        return false;

// the param I normally set maxFileSize is 10MB  10 * 1024 * 1024 = 10485760 bytes converted is 10mb
var max = maxFileSize * 1024 * 1024;

// check if the filesize is above our defined MAX size.
if( file.ContentLength > max )
    return false;

try
{
    // define our allowed image formats
    var allowedFormats = new[] { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif, ImageFormat.Bmp };

    // Creates an Image from the specified data stream.      
    using (var img = Image.FromStream(file.InputStream))
    {
        // Return true if the image format is allowed
        return allowedFormats.Contains(img.RawFormat);
    }
}
catch( Exception ex )
{
    ms.AddModelError( "", ex.Message );                 
}
return false;   
}

So in the controller:

if (!Code.Picture.IsValidUpload(model.File, 10, true))
{                
    return View(model);
}

// Set the file name up... Being random guid, and then todays time in ticks. Then add the file extension
// to the end of the file name
var dbPath = Guid.NewGuid().ToString() + DateTime.UtcNow.Ticks + Path.GetExtension(model.File.FileName);

// Combine the two paths together being the location on the server to store it
// then the actual file name and extension.
var path = Path.Combine(Server.MapPath("~/Uploads/Documents/"), dbPath);

// set variable as Parent directory I do this to make sure the path exists if not
// I will create the directory.
var directoryInfo = new FileInfo(path).Directory;

if (directoryInfo != null)
    directoryInfo.Create();

// save the document in the combined path.
model.File.SaveAs(path);

// then add the data to the database
_db.Documents.Add(new Document
{
    TenancyId = model.SelectedTenancy,
    FileUrl = dbPath,
    FileDescription = model.Description,
    CreatedBy = loggedInAs,
    CreatedDate = DateTime.UtcNow,
    UpdatedDate = null,
    CanTenantView = true
});

_db.SaveChanges();
model.Successfull = true;

Homebrew: Could not symlink, /usr/local/bin is not writable

If you go to the folder in finder, right click and select "Get Info" you can go to the "Sharing and Permissions" section for the folder and allow "Read & Write" to "everyone"

This is what I do to make symlinks pass with this error. Also brew seems to reset the permissions on the folder also as if you hadn't altered anything

how to get the base url in javascript

Should you want what is exactly specified in the web page, just use:

document.querySelector('head base')['href']

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

Connect to SQL Server Database from PowerShell

I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

Android eclipse DDMS - Can't access data/data/ on phone to pull files

To set permission on the data folder and all it's subfolders and files:
Open command prompt from the ADB folder:

>> adb shell
>> su
>> find /data -type d -exec chmod 777 {} \;

How to get the value from the GET parameters?

you can do it by bellow function:

function getParameter(parameterName){
        let paramsIndex = document.URL.indexOf("?");
        let params="";
        if(paramsIndex>0)
            params=document.URL.substring(paramsIndex+1, document.URL.length).split("&");
        let result = [];
        for(let i=0;i<params.length;i++)
        {
            console.warn(params[i].split("=")[0].toString()+ "," + params[i].split("=")[1].toString());
            var obj = {"key":params[i].split("=")[0].toString(),"value":params[i].split("=")[1].toString()};
            result.push(obj);
        }
        return passedValue = result.find(x=>x.key==parameterName).value;
    }

now you can get parameter value with getParameter("parameterName")

glob exclude pattern

As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.

The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method):

import glob

data_files = glob.glob("path_to_files/*.fits")

light_files = np.setdiff1d( data_files, glob.glob("*BIAS*"))
light_files = np.setdiff1d(light_files, glob.glob("*FLAT*"))

(In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)

Where and why do I have to put the "template" and "typename" keywords?

Preface

This post is meant to be an easy-to-read alternative to litb's post.

The underlying purpose is the same; an explanation to "When?" and "Why?" typename and template must be applied.


What's the purpose of typename and template?

typename and template are usable in circumstances other than when declaring a template.

There are certain contexts in C++ where the compiler must explicitly be told how to treat a name, and all these contexts have one thing in common; they depend on at least one template-parameter.

We refer to such names, where there can be an ambiguity in interpretation, as; "dependent names".

This post will offer an explanation to the relationship between dependent-names, and the two keywords.


A snippet says more than 1000 words

Try to explain what is going on in the following function-template, either to yourself, a friend, or perhaps your cat; what is happening in the statement marked (A)?

template<class T> void f_tmpl () { T::foo * x; /* <-- (A) */ }


It might not be as easy as one thinks, more specifically the result of evaluating (A) heavily depends on the definition of the type passed as template-parameter T.

Different Ts can drastically change the semantics involved.

struct X { typedef int       foo;       }; /* (C) --> */ f_tmpl<X> ();
struct Y { static  int const foo = 123; }; /* (D) --> */ f_tmpl<Y> ();


The two different scenarios:

  • If we instantiate the function-template with type X, as in (C), we will have a declaration of a pointer-to int named x, but;

  • if we instantiate the template with type Y, as in (D), (A) would instead consist of an expression that calculates the product of 123 multiplied with some already declared variable x.



The Rationale

The C++ Standard cares about our safety and well-being, at least in this case.

To prevent an implementation from potentially suffering from nasty surprises, the Standard mandates that we sort out the ambiguity of a dependent-name by explicitly stating the intent anywhere we'd like to treat the name as either a type-name, or a template-id.

If nothing is stated, the dependent-name will be considered to be either a variable, or a function.



How to handle dependent names?

If this was a Hollywood film, dependent-names would be the disease that spreads through body contact, instantly affects its host to make it confused. Confusion that could, possibly, lead to an ill-formed perso-, erhm.. program.

A dependent-name is any name that directly, or indirectly, depends on a template-parameter.

template<class T> void g_tmpl () {
   SomeTrait<T>::type                   foo; // (E), ill-formed
   SomeTrait<T>::NestedTrait<int>::type bar; // (F), ill-formed
   foo.data<int> ();                         // (G), ill-formed    
}

We have four dependent names in the above snippet:

  • E)
    • "type" depends on the instantiation of SomeTrait<T>, which include T, and;
  • F)
    • "NestedTrait", which is a template-id, depends on SomeTrait<T>, and;
    • "type" at the end of (F) depends on NestedTrait, which depends on SomeTrait<T>, and;
  • G)
    • "data", which looks like a member-function template, is indirectly a dependent-name since the type of foo depends on the instantiation of SomeTrait<T>.

Neither of statement (E), (F) or (G) is valid if the compiler would interpret the dependent-names as variables/functions (which as stated earlier is what happens if we don't explicitly say otherwise).

The solution

To make g_tmpl have a valid definition we must explicitly tell the compiler that we expect a type in (E), a template-id and a type in (F), and a template-id in (G).

template<class T> void g_tmpl () {
   typename SomeTrait<T>::type foo;                            // (G), legal
   typename SomeTrait<T>::template NestedTrait<int>::type bar; // (H), legal
   foo.template data<int> ();                                  // (I), legal
}

Every time a name denotes a type, all names involved must be either type-names or namespaces, with this in mind it's quite easy to see that we apply typename at the beginning of our fully qualified name.

template however, is different in this regard, since there's no way of coming to a conclusion such as; "oh, this is a template, then this other thing must also be a template". This means that we apply template directly in front of any name that we'd like to treat as such.



Can I just stick the keywords in front of any name?

"Can I just stick typename and template in front of any name? I don't want to worry about the context in which they appear..." - Some C++ Developer

The rules in the Standard states that you may apply the keywords as long as you are dealing with a qualified-name (K), but if the name isn't qualified the application is ill-formed (L).

namespace N {
  template<class T>
  struct X { };
}

         N::         X<int> a; // ...  legal
typename N::template X<int> b; // (K), legal
typename template    X<int> c; // (L), ill-formed

Note: Applying typename or template in a context where it is not required is not considered good practice; just because you can do something, doesn't mean that you should.


Additionally there are contexts where typename and template are explicitly disallowed:

  • When specifying the bases of which a class inherits

    Every name written in a derived class's base-specifier-list is already treated as a type-name, explicitly specifying typename is both ill-formed, and redundant.

                        // .------- the base-specifier-list
      template<class T> // v
      struct Derived      : typename SomeTrait<T>::type /* <- ill-formed */ {
        ...
      };
    

  • When the template-id is the one being referred to in a derived class's using-directive

      struct Base {
        template<class T>
        struct type { };
      };
    
      struct Derived : Base {
        using Base::template type; // ill-formed
        using Base::type;          // legal
      };
    

Add column with number of days between dates in DataFrame pandas

How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

Remove everything after a certain character

It works for me very nicely:

var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result =  x.substring(0, remove_after);
alert(result);

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Without Gradle (Click here for the Gradle solution)

  1. Create a support library project.

  2. Import your library project to Intellij from Eclipse project (this step only applies if you created your library in Eclipse).

  3. Right click on module and choose Open Module Settings.

  4. Setup libraries of v7 jar file Setup libraries of v7 jar file

  5. Setup library module of v7 Setup library module of v7

  6. Setup app module dependency of v7 library module Setup app module dependency of v7 library module

AVD Manager - Cannot Create Android Virtual Device

you need to avoid spaces in the AVD name. & Select the "Skin" option.

Java Web Service client basic authentication

The easiest option to get this working is to include Username and Password under of request. See sample below.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:typ="http://xml.demo.com/types" xmlns:ser="http://xml.demo.com/location/services"
    xmlns:typ1="http://xml.demo.com/location/types">
    <soapenv:Header>
        <typ:requestHeader>
            <typ:timestamp>?</typ:timestamp>
            <typ:sourceSystemId>TEST</typ:sourceSystemId>
            <!--Optional: -->
            <typ:sourceSystemUserId>1</typ:sourceSystemUserId>
            <typ:sourceServerId>1</typ:sourceServerId>
            <typ:trackingId>HYD-12345</typ:trackingId>
        </typ:requestHeader>

        <wsse:Security soapenv:mustUnderstand="1"
            xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsse:UsernameToken wsu:Id="UsernameToken-emmprepaid"
                xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                <wsse:Username>your-username</wsse:Username>
                <wsse:Password
                    Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">your-password</wsse:Password>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body>
        <ser:getLocation>
            <!--Optional: -->
            <ser:GetLocation>
                <typ1:locationID>HYD-GoldenTulipsEstates</typ1:locationID>
            </ser:GetLocation>
        </ser:getLocation>
    </soapenv:Body>
</soapenv:Envelope>