Programs & Examples On #Thrust

Thrust is a template library of parallel algorithms with an interface resembling the C++ Standard Template Library (STL) for NVIDIA CUDA.

Converting dict to OrderedDict

You can create the ordered dict from old dict in one line:

from collections import OrderedDict
ordered_dict = OrderedDict(sorted(ship.items())

The default sorting key is by dictionary key, so the new ordered_dict is sorted by old dict's keys.

CUDA incompatible with my gcc version

To compile the CUDA 8.0 examples on Ubuntu 16.10, I did:

sudo apt-get install gcc-5 g++-5
cd /path/to/NVIDIA_CUDA-8.0_Samples
# Find the path to the library (this should be in NVIDIA's Makefiles)
LIBLOC=`find /usr/lib -name "libnvcuvid.so.*" | head -n1 | perl -pe 's[/usr/lib/(nvidia-\d+)/.*][$1]'`
# Substitute that path into the makefiles for the hard-coded, incorrect one
find . -name "*.mk" | xargs perl -pi -e "s/nvidia-\d+/$LIBLOC/g"
# Make using the supported compiler
HOST_COMPILER=g++-5 make

This has the advantage of not modifying the whole system or making symlinks to just the binaries (that could cause library linking problems.)

Reordering arrays

Here is an immutable version for those who are interested:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

How can one create an overlay in css?

http://jsfiddle.net/55LNG/1/

CSS:

#box{
    border:1px solid black;
    position:relative;
}
#overlay{
    position:absolute;
    top:0px;
    left:0px;
    bottom:0px;
    right:0px;
    background-color:rgba(255,255,0,0.5);
}

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

in C#:

new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)

How to properly assert that an exception gets raised in pytest?

pytest constantly evolves and with one of the nice changes in the recent past it is now possible to simultaneously test for

  • the exception type (strict test)
  • the error message (strict or loose check using a regular expression)

Two examples from the documentation:

with pytest.raises(ValueError, match='must be 0 or None'):
    raise ValueError('value must be 0 or None')
with pytest.raises(ValueError, match=r'must be \d+$'):
    raise ValueError('value must be 42')

I have been using that approach in a number of projects and like it very much.

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Directory-tree listing in Python

FYI Add a filter of extension or ext file import os

path = '.'
for dirname, dirnames, filenames in os.walk(path):
    # print path to all filenames with extension py.
    for filename in filenames:
        fname_path = os.path.join(dirname, filename)
        fext = os.path.splitext(fname_path)[1]
        if fext == '.py':
            print fname_path
        else:
            continue

How to efficiently count the number of keys/properties of an object in JavaScript?

I don't think this is possible (at least not without using some internals). And I don't think you would gain much by optimizing this.

How to send a model in jQuery $.ajax() post request to MVC controller method

This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

I am achieving this either by a double click event on a grid row or click event on a button of some sort.

@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value, 
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")', 
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

How to get the first element of the List or Set?

Let's assume that you have a List<String> strings that you want the first item from.

There are several ways to do that:

Java (pre-8):

String firstElement = null;
if (!strings.isEmpty() && strings.size() > 0) {
    firstElement = strings.get(0);
}

Java 8:

Optional<String> firstElement = strings.stream().findFirst();

Guava

String firstElement = Iterables.getFirst(strings, null);

Apache commons (4+)

String firstElement = (String) IteratorUtils.get(strings, 0);

Apache commons (before 4)

String firstElement = (String) CollectionUtils.get(strings, 0);

Followed by or encapsulated within the appropriate checks or try-catch blocks.

Kotlin:

In Kotlin both Arrays and most of the Collections (eg: List) have a first method call. So your code would look something like this

for a List:

val stringsList: List<String?> = listOf("a", "b", null)
val first: String? = stringsList.first()

for an Array:

val stringArray: Array<String?> = arrayOf("a", "b", null)
val first: String? = stringArray.first()

Followed by or encapsulated within the appropriate checks or try-catch blocks.

Kotlin also includes safer ways to do that for kotlin.collections, for example firstOrNull or getOrElse, or getOrDefault when using JRE8

Github Push Error: RPC failed; result=22, HTTP code = 413

I figured it out!!! Of course I would right after I hit post!

I had the repo set to use the HTTPS url, I changed it to the SSH address, and everything resumed working flawlessly.

When should I use double or single quotes in JavaScript?

It's mostly a matter of style and preference. There are some rather interesting and useful technical explorations in the other answers, so perhaps the only thing I might add is to offer a little worldly advice.

  • If you're coding in a company or team, then it's probably a good idea to follow the "house style".

  • If you're alone hacking a few side projects, then look at a few prominent leaders in the community. For example, let's say you getting into Node.js. Take a look at core modules, for example, Underscore.js or express and see what convention they use, and consider following that.

  • If both conventions are equally used, then defer to your personal preference.

  • If you don't have any personal preference, then flip a coin.

  • If you don't have a coin, then beer is on me ;)

java.lang.UnsupportedClassVersionError

Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

When publishing to IIS, by Web Deploy, I just checked the File Publish Options and executed. Now it works! After this deploy the checkboxes do not need to be checked. I don't think this can be a solutions for everybody, but it is the only thing I needed to do to solve my problem. Good luck.

Version of Apache installed on a Debian machine

For me this works on Debian 6 (Squeeze):

Linux www809 2.6.26-2-xen-686 #1 SMP Wed Sep 21 09:56:47 UTC 2011 i686 GNU/Linux

I had to go to the right path:

/usr/local/apache/bin** $ **./apachectl -v

./apachectl: line 71: ulimit: open files: cannot modify limit: Operation not permitted
Server version: Apache/2.2.21 (Unix)
Server built: Dec 17 2011 19:57:53

Getting number of elements in an iterator in Python

An iterator is just an object which has a pointer to the next object to be read by some kind of buffer or stream, it's like a LinkedList where you don't know how many things you have until you iterate through them. Iterators are meant to be efficient because all they do is tell you what is next by references instead of using indexing (but as you saw you lose the ability to see how many entries are next).

SQL count rows in a table

The index statistics likely need to be current, but this will return the number of rows for all tables that are not MS_SHIPPED.

select o.name, i.rowcnt 
from sys.objects o join sys.sysindexes i 
on o.object_id = i.id
where o.is_ms_shipped = 0
and i.rowcnt > 0
order by o.name

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

How to auto resize and adjust Form controls with change in resolution

sorry I saw the question late, Here is an easy programmatically solution that works well on me,

Create those global variables:

 float firstWidth;
 float firstHeight;

after on load, fill those variables;

 firstWidth = this.Size.Width;
 firstHeight = this.Size.Height;

then select your form and put these code to your form's SizeChange event;

 private void AnaMenu_SizeChanged(object sender, EventArgs e)
    {
        

        float size1 = this.Size.Width /  firstWidth;
        float size2 = this.Size.Height / firstHeight;

            SizeF scale = new SizeF(size1, size2);
        firstWidth = this.Size.Width;
        firstHeight = this.Size.Height;

        foreach (Control control in this.Controls)
        {
                
            control.Font = new Font(control.Font.FontFamily, control.Font.Size* ((size1+ size2)/2));
            
            control.Scale(scale);
                

        }


    }

I hope this helps, it works perfect on my projects.

Add image to left of text via css

.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px;  /* width of the image plus a little extra padding */
display: block;  /* may not need this, but I've found I do */
}

Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).

How to enable CORS on Firefox?

This Firefox add-on may work for you:

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

It can toggle CORS on and off for development purposes.

What generates the "text file busy" message in Unix?

If trying to build phpredis on a Linux box you might need to give it time to complete modifying the file permissions, with a sleep command, before running the file:

chmod a+x /usr/bin/php/scripts/phpize \
  && sleep 1 \
  && /usr/bin/php/scripts/phpize

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Use FireFox or any other browser instead of Chrome if you want to test it on your development environment, for production there is no way except using https.

For development environment just open http://localhost:8100/ on FireFox and alas no such error.

How to delete a file after checking whether it exists

Use System.IO.File.Delete like so:

System.IO.File.Delete(@"C:\test.txt")

From the documentation:

If the file to be deleted does not exist, no exception is thrown.

How to call shell commands from Ruby

The backticks (`) method is the easiest one to call shell commands from Ruby. It returns the result of the shell command:

     url_request = 'http://google.com'
     result_of_shell_command = `curl #{url_request}`

How to create PDFs in an Android app?

A trick to make a PDF with complex features is to make a dummy activity with the desired xml layout. You can then open this dummy activity, take a screenshot programmatically and convert that image to pdf using this library. Of course there are limitations such as not being able to scroll, not more than one page,but for a limited application this is quick and easy. Hope this helps someone!

how to add key value pair in the JSON object already declared

Object assign copies one or more source objects to the target object. So we could use Object.assign here.

Syntax: Object.assign(target, ...sources)

_x000D_
_x000D_
var obj  = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

How to find my realm file?

To get the DB path for iOS, the simplest way is to:

  1. Launch your app in a simulator
  2. Pause it at any time in the debugger
  3. Go to the console (where you have (lldb)) and type: po RLMRealm.defaultRealmPath

Tada...you have the path to your realm database

Excel - Button to go to a certain sheet

You have to add Button to excel sheet(say sheet1) from which you can go to another sheet(say sheet2).

Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.

GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.

To Add button :-

Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.

To give name for button :-

Right click on button -> edit text.

To add code for going to sheet2 :-

Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code

Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate

Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.

Javascript - sort array based on another array

Use intersection of two arrays.

Ex:

var sortArray = ['a', 'b', 'c',  'd', 'e'];

var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];

_.intersection(sortArray, arrayToBeSort) 

=> ['a', 'b', 'e']

if 'z and 's' are out of range of first array, append it at the end of result

What is the best/safest way to reinstall Homebrew?

Update 10/11/2020 to reflect the latest brew changes.

Brew already provide a command to uninstall itself (this will remove everything you installed with Homebrew):

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

If you failed to run this command due to permission (like run as second user), run again with sudo

Then you can install again:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Email and phone Number Validation in android

Use Pattern package in Android to match the input validation for email and phone

Do like

android.util.Patterns.EMAIL_ADDRESS.matcher(input).matches();
android.util.Patterns.PHONE.matcher(input).matches();

Get the data received in a Flask request

To get request.form as a normal dictionary , use request.form.to_dict(flat=False).

To return JSON data for an API, pass it to jsonify.

This example returns form data as JSON data.

@app.route('/form_to_json', methods=['POST'])
def form_to_json():
    data = request.form.to_dict(flat=False)
    return jsonify(data)

Here's an example of POST form data with curl, returning as JSON:

$ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer"
{
  "name": "ivanleoncz", 
  "role": "Software Developer"
}

Getting or changing CSS class property with Javascript using DOM style

Maybe better document.querySelectorAll(".col1") because getElementsByClassName doesn't works in IE 8 and querySelectorAll does (althought CSS2 selectors only).

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Get program execution time in the shell

Should you want more precision, use %N with date (and use bc for the diff, because $(()) only handles integers).

Here's how to do it:

start=$(date +%s.%N)
# do some stuff here
dur=$(echo "$(date +%s.%N) - $start" | bc)

printf "Execution time: %.6f seconds" $dur

Example:

start=$(date +%s.%N); \
  sleep 0.1s; \
  dur=$(echo "$(date +%s.%N) - $start" | bc); \
  printf "Execution time: %.6f seconds\n" $dur

Result:

Execution time: 0.104623 seconds

How can I set a DateTimePicker control to a specific date?

This oughta do it.

DateTimePicker1.Value = DateTime.Now.AddDays(-1).Date;

AngularJS : Clear $watch

scope.$watch returns a function that you can call and that will unregister the watch.

Something like:

var unbindWatch = $scope.$watch("myvariable", function() {
    //...
});

setTimeout(function() {
    unbindWatch();
}, 1000);

How to increase space between dotted border dots

So starting with the answer given and applying the fact that CSS3 allows multiple settings - the below code is useful for creating a complete box:

_x000D_
_x000D_
#border {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
  background: yellow;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
  background: linear-gradient(to right, orange 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(blue 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(to right, green 50%, rgba(255, 255, 255, 0) 0%), linear-gradient(red 50%, rgba(255, 255, 255, 0) 0%);_x000D_
  background-position: top, right, bottom, left;_x000D_
  background-repeat: repeat-x, repeat-y;_x000D_
  background-size: 10px 1px, 1px 10px;_x000D_
}
_x000D_
<div id="border">_x000D_
  bordered area_x000D_
</div>
_x000D_
_x000D_
_x000D_

Its worth noting that the 10px in the background size gives the area that the dash and gap will cover. The 50% of the background tag is how wide the dash actually is. It is therefore possible to have different length dashes on each border side.

What does the Ellipsis object do?

You can use Ellipsis yourself, in custom slicing situations like numpy has done, but it has no usage in any builtin class.

I don't know if it was added specifically for use in numpy, but I certainly haven't seen it used elsewhere.

See also: How do you use the ellipsis slicing syntax in Python?

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Find all controls in WPF Window by type

This is the easiest way:

IEnumerable<myType> collection = control.Children.OfType<myType>(); 

where control is the root element of the window.

Tri-state Check box in HTML?

Refering to @BoltClock answer, here is my solution for a more complex recursive method:

http://jsfiddle.net/gx7so2tq/2/

It might not be the most pretty solution but it works fine for me and is quite flexible.

I use two data objects defining the container:

data-select-all="chapter1"

and the elements itself:

data-select-some="chapter1"

Both having the same value. The combination of both data-objects within one checkbox allows sublevels, which are scanned recursively. Therefore two "helper" functions are needed to prevent the change-trigger.

Concatenation of strings in Lua

As other answers have said, the string concatenation operator in Lua is two dots.

Your simple example would be written like this:

filename = "checkbook"
filename = filename .. ".tmp"

However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.

The Lua idiom for this case is something like this:

function listvalues(s)
    local t = { }
    for k,v in ipairs(s) do
        t[#t+1] = tostring(v)
    end
    return table.concat(t,"\n")
end

By collecting the strings to be concatenated in an array t, the standard library routine table.concat can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.

Update: I just noticed that I originally wrote the code snippet above using pairs() instead of ipairs().

As originally written, the function listvalues() would indeed produce every value from the table passed in, but not in a stable or predictable order. On the other hand, it would include values who's keys were not positive integers in the span of 1 to #s. That is what pairs() does: it produces every single (key,value) pair stored in the table.

In most cases where you would be using something like listvaluas() you would be interested in preserving their order. So a call written as listvalues{13, 42, 17, 4} would produce a string containing those value in that order. However, pairs() won't do that, it will itemize them in some order that depends on the underlying implementation of the table data structure. It is known that the order not only depends on the keys, but also on the order in which the keys were inserted and other keys removed.

Of course ipairs() isn't a perfect answer either. It only enumerates those values of the table that form a "sequence". That is, those values who's keys form an unbroken block spanning from 1 to some upper bound, which is (usually) also the value returned by the # operator. (In many cases, the function ipairs() itself is better replaced by a simpler for loop that just counts from 1 to #s. This is the recommended practice in Lua 5.2 and in LuaJIT where the simpler for loop can be more efficiently implemented than the ipairs() iterator.)

If pairs() really is the right approach, then it is usually the case that you want to print both the key and the value. This reduces the concerns about order by making the data self-describing. Of course, since any Lua type (except nil and the floating point NaN) can be used as a key (and NaN can also be stored as a value) finding a string representation is left as an exercise for the student. And don't forget about trees and more complex structures of tables.

Getting Serial Port Information

EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...

Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)

Sample code (make sure to add reference to System.Management):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;        

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                var tList = (from n in portnames
                            join p in ports on n equals p["DeviceID"].ToString()
                            select n + " - " + p["Caption"]).ToList();

                tList.ForEach(Console.WriteLine);
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

More info here: http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx

Aliases in Windows command prompt

Expanding on roryhewitt answer.

An advantage to using .cmd files over DOSKEY is that these "aliases" are then available in other shells such as PowerShell or WSL (Windows subsystem for Linux).

The only gotcha with using these commands in bash is that it may take a bit more setup since you might need to do some path manipulation before calling your "alias".

eg I have vs.cmd which is my "alias" for editing a file in Visual Studio

@echo off
if [%1]==[] goto nofiles
start "" "c:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" /edit %1
goto end
:nofiles
start "" "C:\Program Files (x86)\Microsoft Visual Studio 
11.0\Common7\IDE\devenv.exe" "[PATH TO MY NORMAL SLN]"
:end

Which fires up VS (in this case VS2012 - but adjust to taste) using my "normal" project with no file given but when given a file will attempt to attach to a running VS opening that file "within that project" rather than starting a new instance of VS.

For using this from bash I then add an extra level of indirection since "vs Myfile" wouldn't always work

alias vs='/usr/bin/run_visual_studio.sh'

Which adjusts the paths before calling the vs.cmd

#!/bin/bash
cmd.exe /C 'c:\Windows\System32\vs.cmd' "`wslpath.sh -w -r $1`"

So this way I can just do

vs SomeFile.txt

In either a command prompt, Power Shell or bash and it opens in my running Visual Studio for editing (which just saves my poor brain from having to deal with VI commands or some such when I've just been editing in VS for hours).

Sorting a list with stream.sorted() in Java

Use list.sort instead:

list.sort((o1, o2) -> o1.getItem().getValue().compareTo(o2.getItem().getValue()));

and make it more succinct using Comparator.comparing:

list.sort(Comparator.comparing(o -> o.getItem().getValue()));

After either of these, list itself will be sorted.

Your issue is that list.stream.sorted returns the sorted data, it doesn't sort in place as you're expecting.

Run R script from command line

Yet another way to use Rscript for *Unix systems is Process Substitution.

Rscript <(zcat a.r)
# [1] "hello"

Which obviously does the same as the accepted answer, but this allows you to manipulate and run your file without saving it the power of the command line, e.g.:

Rscript <(sed s/hello/bye/ a.r)
# [1] "bye"

Similar to Rscript -e "Rcode" it also allows to run without saving into a file. So it could be used in conjunction with scripts that generate R-code, e.g.:

Rscript <(echo "head(iris,2)")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa

How to convert image to byte array

Sample code to change an image into a byte array

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
   using (var ms = new MemoryStream())
   {
      imageIn.Save(ms,imageIn.RawFormat);
      return  ms.ToArray();
   }
}

C# Image to Byte Array and Byte Array to Image Converter Class

git: undo all working dir changes including new files

You can do this in two steps:

  1. Revert modified files: git checkout -f
  2. Remove untracked files: git clean -fd

Android, landscape only orientation?

When you are in android studio 3 or above you need to add following lines AndroidManifest.xml file

<activity
            android:name=".MainActivity"
            android:configChanges="orientation"
            android:screenOrientation= "sensorLandscape"
            tools:ignore="LockedOrientationActivity">

One thing this is sensor Landscape, means it will work on both landscape sides

But if you only want to work the regular landscape side then, replace sensorLandscape to landscape

Disable F5 and browser refresh using JavaScript

This is the code I'm using to disable refresh on IE and firefox which works for the following key combinations:

F5   |   Ctrl + F5   |   Ctrl + R

//this code handles the F5/Ctrl+F5/Ctrl+R
document.onkeydown = checkKeycode
function checkKeycode(e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
                
    // Mozilla firefox
    if ($.browser.mozilla) {
        if (keycode == 116 ||(e.ctrlKey && keycode == 82)) {
            if (e.preventDefault)
            {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    } 
    // IE
    else if ($.browser.msie) {
        if (keycode == 116 || (window.event.ctrlKey && keycode == 82)) {
            window.event.returnValue = false;
            window.event.keyCode = 0;
            window.status = "Refresh is disabled";
        }
    }
}

If you don't want to use useragent to detect what type of browser it is ($.browser uses navigator.userAgent to determine the platform), you can use

if('MozBoxSizing' in document.documentElement.style) which returns true for firefox

Function names in C++: Capitalize or not?

As others said, there is no such thing in C++. Having said that, I tend to use the style in which the standard library is written - K & R.

Also, see the FAQ entry by Bjarne Stroustrup.

Altering user-defined table types in SQL Server

You should drop the old table type and create a new one. However if it has any dependencies (any stored procedures using it) you won't be able to drop it. I've posted another answer on how to automate the process of temporary dropping all stored procedures, modifying the table table and then restoring the stored procedures.

How to get a table creation script in MySQL Workbench?

1 use command

show create table test.location

enter image description here

  1. right click on selected row and choose Open Value In Viewer

  2. select tab Text enter image description here

How to write DataFrame to postgres table?

Pandas 0.24.0+ solution

In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method

import csv
from io import StringIO

from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    # gets a DBAPI connection that can provide a cursor
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)

        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name

        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
            table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)

In Matplotlib, what does the argument mean in fig.add_subplot(111)?

The answer from Constantin is spot on but for more background this behavior is inherited from Matlab.

The Matlab behavior is explained in the Figure Setup - Displaying Multiple Plots per Figure section of the Matlab documentation.

subplot(m,n,i) breaks the figure window into an m-by-n matrix of small subplots and selects the ithe subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth.

Error in Process.Start() -- The system cannot find the file specified

Try to replace your initialization code with:

ProcessStartInfo info 
    = new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");

Using non full filepath on Process.Start only works if the file is found in System32 folder.

Generating a SHA-256 hash from the Linux command line

echo will normally output a newline, which is suppressed with -n. Try this:

echo -n foobar | sha256sum

Easiest way to detect Internet connection on iOS?

Sorry for replying too late but I hope this answer can help somebody in future.

Following is a small native C code snippet that can check internet connectivity without any extra class.

Add the following headers:

#include<unistd.h>
#include<netdb.h>

Code:

-(BOOL)isNetworkAvailable
{
    char *hostname;
    struct hostent *hostinfo;
    hostname = "google.com";
    hostinfo = gethostbyname (hostname);
    if (hostinfo == NULL){
        NSLog(@"-> no connection!\n");
        return NO;
    }
    else{
        NSLog(@"-> connection established!\n");
        return YES;
    }
}

Swift 3

func isConnectedToInternet() -> Bool {
    let hostname = "google.com"
    //let hostinfo = gethostbyname(hostname)
    let hostinfo = gethostbyname2(hostname, AF_INET6)//AF_INET6
    if hostinfo != nil {
        return true // internet available
      }
     return false // no internet
    }

How to convert CSV file to multiline JSON?

I took @SingleNegationElimination's response and simplified it into a three-liner that can be used in a pipeline:

import csv
import json
import sys

for row in csv.DictReader(sys.stdin):
    json.dump(row, sys.stdout)
    sys.stdout.write('\n')

JAX-WS and BASIC authentication, when user names and passwords are in a database

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are matching HTTP Basic Authentication mechanism that enable authentication process at the HTTP level and not at the application nor servlet level.

Basically, only the HTTP server will know the username and the password (and eventually application according to HTTP/application server specification, such with Apache/PHP). With Tomcat/Java, add a login config BASIC in your web.xml and appropriate security-constraint/security-roles (roles that will be later associated to users/groups of real users).

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>YourRealm</realm-name>
</login-config>

Then, connect the realm at the HTTP server (or application server) level with the appropriate user repository. For tomcat you may look at JAASRealm, JDBCRealm or DataSourceRealm that may suit your needs.

http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html

Why use static_cast<int>(x) instead of (int)x?

It's about how much type-safety you want to impose.

When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.

When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.


EDIT 2014-02-26

I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

I had that problem too...turns out my credit card info on file needed updated to my new expiration date.

These instructions came from troubleshooting on my phone.

On a computer (not tablet or phone) sign into your Google Wallet, click Payment Methods then edit to edit info. Hope it works for you too!

powershell - list local users and their groups

Update as an alternative to the excellent answer from 2010:

You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups

Example:

PS C:\WINDOWS\system32> Get-LocalGroupMember -name users

ObjectClass Name                             PrincipalSource 
----------- ----                             --------------- 
User        DESKTOP-R05QDNL\someUser1        Local           
User        DESKTOP-R05QDNL\someUser2        MicrosoftAccount
Group       NT AUTHORITY\INTERACTIVE         Unknown  

You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.

In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:

$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"

New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description

What is the difference between float and double?

Floats have less precision than doubles. Although you already know, read What WE Should Know About Floating-Point Arithmetic for better understanding.

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

How do I split a string, breaking at a particular character?

With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

matplotlib savefig in jpeg format

Matplotlib can handle directly and transparently jpg if you have installed PIL. You don't need to call it, it will do it by itself. If Python cannot find PIL, it will raise an error.

How to convert seconds to HH:mm:ss in moment.js

You can use moment-duration-format plugin:

_x000D_
_x000D_
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
_x000D_
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
_x000D_
_x000D_
_x000D_

See also this Fiddle

Upd: To avoid trimming for values less than 60-sec use { trim: false }:

var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"

Alarm Manager Example

This is working code. It wakes CPU every 10 minutes until the phone turns off.

Add to Manifest.xml:

...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver android:process=":remote" android:name=".Alarm"></receiver>
...

Code in your class:

package yourPackage;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;

public class Alarm extends BroadcastReceiver 
{    
    @Override
    public void onReceive(Context context, Intent intent) 
    {   
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        // Put here YOUR code.
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

        wl.release();
    }

    public void setAlarm(Context context)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
    }

    public void cancelAlarm(Context context)
    {
        Intent intent = new Intent(context, Alarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}

Set Alarm from Service:

package yourPackage;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class YourService extends Service
{
    Alarm alarm = new Alarm();
    public void onCreate()
    {
        super.onCreate();       
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
        alarm.setAlarm(this);
        return START_STICKY;
    }

   @Override        
   public void onStart(Intent intent, int startId)
    {
        alarm.setAlarm(this);
    }

    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }
}

If you want to set alarm repeating at phone boot time:

Add permission and the service to Manifest.xml:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
...
<receiver android:name=".AutoStart">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>
...
<service
        android:name=".YourService"
        android:enabled="true"
        android:process=":your_service" >
</service>

And create a new class:

package yourPackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AutoStart extends BroadcastReceiver
{   
    Alarm alarm = new Alarm();
    @Override
    public void onReceive(Context context, Intent intent)
    {   
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
        {
            alarm.setAlarm(context);
        }
    }
}

Split Strings into words with multiple word boundary delimiters

try this:

import re

phrase = "Hey, you - what are you doing here!?"
matches = re.findall('\w+', phrase)
print matches

this will print ['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']

VB.NET: how to prevent user input in a ComboBox

Set the DropDownStyle property of the combobox to DropDownList. This will allow only items in the list to be selected and will not allow any free-form user input.

How do I get a file's directory using the File object?

File API File.getParent or File.getParentFile should return you Directory of file.

Your code should be like :

    File file = new File("c:\\temp\\java\\testfile");
    if(!file.exists()){
        file = file.getParentFile();
    }

You can additionally check your parent file is directory using File.isDirectory API

if(file.isDirectory()){
    System.out.println("file is directory ");
}

ViewPager PagerAdapter not updating the View

There are several ways to achieve this.

The first option is easier, but bit more inefficient.

Override getItemPosition in your PagerAdapter like this:

public int getItemPosition(Object object) {
    return POSITION_NONE;
}

This way, when you call notifyDataSetChanged(), the view pager will remove all views and reload them all. As so the reload effect is obtained.

The second option, suggested by Alvaro Luis Bustamante (previously alvarolb), is to setTag() method in instantiateItem() when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag() to find the view you want to update.

The second approach is very flexible and high performant. Kudos to alvarolb for the original research.

Pass a datetime from javascript to c# (Controller)

var Ihours = Math.floor(TotMin / 60);          

var Iminutes = TotMin % 60; var TotalTime = Ihours+":"+Iminutes+':00';

   $.ajax({
            url: ../..,
            cache: false,
            type: "POST",                
            data: JSON.stringify({objRoot: TotalTime}) ,
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {

            },
            error: function (er) {
                console.log(er);
            }
        });

How to getText on an input in protractor

I had this issue I tried Jmr's solution however it didn't work for me. As all input fields have ng-model attributes I could pull the the attribute and evaluate it and get the value.

HTML

<input ng-model="qty" type="number">

Protractor

var qty = element( by.model('qty') );
qty.sendKeys('10');
qty.evaluate(qty.getAttribute('ng-model')) //-> 10

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

Doctrine and LIKE query

you can also do it like that :

$ver = $em->getRepository('GedDocumentBundle:version')->search($val);

$tail = sizeof($ver);

What is the difference between And and AndAlso in VB.NET?

Just for all those people who say side effects are evil: a place where having two side effects in one condition is good would be reading two file objects in tandem.

While File1.Seek_Next_Row() And File2.Seek_Next_Row()
    Str1 = File1.GetRow()
    Str2 = File2.GetRow()
End While

Using the And ensures that a row is consumed every time the condition is checked. Whereas AndAlso might read the last line of File1 and leave File2 without a consumed line.

Of course the code above wouldn't work, but I use side effects like this all the time and wouldn't consider it "bad" or "evil" code as some would lead you to believe. It's easy to read and efficient.

CSS image overlay with color and transparency

Have you given a try to Webkit Filters?

You can manipulate not only opacity, but colour, brightness, luminosity and other properties:

How can I get the source directory of a Bash script from within the script itself?

$_ is worth mentioning as an alternative to $0. If you're running a script from Bash, the accepted answer can be shortened to:

DIR="$( dirname "$_" )"

Note that this has to be the first statement in your script.

How to send data with angularjs $http.delete() request?

$http.delete method doesn't accept request body. You can try this workaround :

$http( angular.merge({}, config || {}, {
    method  : 'delete',
    url     : _url,
    data    : _data
}));

where in config you can pass config data like headers etc.

Get the position of a spinner in Android

The way to get the selection of the spinner is:

  spinner1.getSelectedItemPosition();

Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()

However, in your code, the one place you are referencing it is within your setOnItemSelectedListener(). It is not necessary to poll the spinner, because the onItemSelected method gets passed the position as the "position" variable.

So you could change that line to:

TestProjectActivity.this.number = position + 1;

If that does not fix the problem, please post the error message generated when your app crashes.

Comparing chars in Java

pseudocode as I haven't got a java sdk on me:

Char candidates = new Char[] { 'A', 'B', ... 'G' };

foreach(Char c in candidates)
{
    if (symbol == c) { return true; }
}
return false;

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

Django - after login, redirect user to his custom page --> mysite.com/username

A simpler approach relies on redirection from the page LOGIN_REDIRECT_URL. The key thing to realize is that the user information is automatically included in the request.

Suppose:

LOGIN_REDIRECT_URL = '/profiles/home'

and you have configured a urlpattern:

(r'^profiles/home', home),

Then, all you need to write for the view home() is:

from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    return HttpResponseRedirect(
               reverse(NAME_OF_PROFILE_VIEW, 
                       args=[request.user.username]))

where NAME_OF_PROFILE_VIEW is the name of the callback that you are using. With django-profiles, NAME_OF_PROFILE_VIEW can be 'profiles_profile_detail'.

Compute a confidence interval from sample data

import numpy as np
import scipy.stats


def mean_confidence_interval(data, confidence=0.95):
    a = 1.0 * np.array(data)
    n = len(a)
    m, se = np.mean(a), scipy.stats.sem(a)
    h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
    return m, m-h, m+h

you can calculate like this way.

How to ignore user's time zone and force Date() use specific time zone

Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser). Then just add the needed number of milliseconds to it.

_x000D_
_x000D_
var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );_x000D_
_date.setUTCMilliseconds(1270544790922);_x000D_
_x000D_
alert(_date); //date shown shifted corresponding to local time settings_x000D_
alert(_date.getUTCFullYear());    //the UTC year value_x000D_
alert(_date.getUTCMonth());       //the UTC month value_x000D_
alert(_date.getUTCDate());        //the UTC day of month value_x000D_
alert(_date.getUTCHours());       //the UTC hour value_x000D_
alert(_date.getUTCMinutes());     //the UTC minutes value
_x000D_
_x000D_
_x000D_

Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings. Otherwise date values will be shifted corresponding to local time settings.

What are the advantages of Sublime Text over Notepad++ and vice-versa?

One thing that should be considered is licensing.

Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.

To quote the Sublime Text 2 website:

..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.

Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.

This licensing requirement is still correct as of Dec 2019.

How do I return the response from an asynchronous call?

While promises and callbacks work fine in many situations, it is a pain in the rear to express something like:

if (!name) {
  name = async1();
}
async2(name);

You'd end up going through async1; check if name is undefined or not and call the callback accordingly.

async1(name, callback) {
  if (name)
    callback(name)
  else {
    doSomething(callback)
  }
}

async1(name, async2)

While it is okay in small examples it gets annoying when you have a lot of similar cases and error handling involved.

Fibers helps in solving the issue.

var Fiber = require('fibers')

function async1(container) {
  var current = Fiber.current
  var result
  doSomething(function(name) {
    result = name
    fiber.run()
  })
  Fiber.yield()
  return result
}

Fiber(function() {
  var name
  if (!name) {
    name = async1()
  }
  async2(name)
  // Make any number of async calls from here
}

You can checkout the project here.

Resolving IP Address from hostname with PowerShell

Use Resolve-DnsName cmdlet.

Resolve-DnsName computername | FT Name, IPAddress -HideTableHeaders | Out-File -Append c:\filename.txt

PS C:\> Resolve-DnsName stackoverflow.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
stackoverflow.com                              A      130   Answer     151.101.65.69
stackoverflow.com                              A      130   Answer     151.101.129.69
stackoverflow.com                              A      130   Answer     151.101.193.69
stackoverflow.com                              A      130   Answer     151.101.1.69

PS C:\> Resolve-DnsName stackoverflow.com | Format-Table Name, IPAddress -HideTableHeaders

stackoverflow.com 151.101.65.69
stackoverflow.com 151.101.1.69
stackoverflow.com 151.101.193.69
stackoverflow.com 151.101.129.69

PS C:\> Resolve-DnsName -Type A google.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     A      16    Answer     216.58.193.78


PS C:\> Resolve-DnsName -Type AAAA google.com

Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     AAAA   223   Answer     2607:f8b0:400e:c04::64

Using Node.js require vs. ES6 import/export

There are several usage / capabilities you might want to consider:

Require:

  • You can have dynamic loading where the loaded module name isn't predefined /static, or where you conditionally load a module only if it's "truly required" (depending on certain code flow).
  • Loading is synchronous. That means if you have multiple requires, they are loaded and processed one by one.

ES6 Imports:

  • You can use named imports to selectively load only the pieces you need. That can save memory.
  • Import can be asynchronous (and in current ES6 Module Loader, it in fact is) and can perform a little better.

Also, the Require module system isn't standard based. It's is highly unlikely to become standard now that ES6 modules exist. In the future there will be native support for ES6 Modules in various implementations which will be advantageous in terms of performance.

Copy map values to vector in STL

You can't easily use a range here because the iterator you get from a map refers to a std::pair, where the iterators you would use to insert into a vector refers to an object of the type stored in the vector, which is (if you are discarding the key) not a pair.

I really don't think it gets much cleaner than the obvious:

#include <map>
#include <vector>
#include <string>
using namespace std;

int main() {
    typedef map <string, int> MapType;
    MapType m;  
    vector <int> v;

    // populate map somehow

    for( MapType::iterator it = m.begin(); it != m.end(); ++it ) {
        v.push_back( it->second );
    }
}

which I would probably re-write as a template function if I was going to use it more than once. Something like:

template <typename M, typename V> 
void MapToVec( const  M & m, V & v ) {
    for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) {
        v.push_back( it->second );
    }
}

PHP: Possible to automatically get all POSTed data?

As long as you don't want any special formatting: yes.

foreach ($_POST as $key => $value) 
    $body .= $key . ' -> ' . $value . '<br>';

Obviously, more formatting would be necessary, however that's the "easy" way. Unless I misunderstood the question.

You could also do something like this (and if you like the format, it's certainly easier):

$body = print_r($_POST, true);

JQuery Redirect to URL after specified time

This is improved @Vicky solution - it has clearInterval() added so it prevents a loop of reloading if the redirect takes too long:

                            $(document).ready(function () {
                                var myTimer = window.setInterval(function () {
                                    var timeLeft = $("#countdown").html();
                                    if (eval(timeLeft) == 0) {
                                        console.log('Now redirecting');
                                        clearInterval(myTimer);
                                        window.location = ("@Html.Raw(HttpUtility.HtmlDecode(redirectUrl))");
                                    } else {
                                        $("#countdown").html(eval(timeLeft) - eval(1));
                                    }
                                }, 1000);
                            });

Standard way to embed version into python package?

For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration has a make_svn_version_py() method that embeds the revision number inside package.__svn_version__ in the variable version .

Simple http post example in Objective-C?

From Apple's Official Website :

// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";

NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];

// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];

// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL

From : code with chris

    // Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];

// Specify that it will be a POST request
request.HTTPMethod = @"POST";

// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

// Convert your data and set your request's HTTPBody property
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

php refresh current page?

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

Auto Resize Image in CSS FlexBox Layout and keeping Aspect Ratio?

I am using jquery or vw to keep the ratio

jquery

function setSize() {
    var $h = $('.cell').width();
    $('.your-img-class').height($h);
}
$(setSize);
$( window ).resize(setSize); 

vw

 .cell{
    width:30vw;
    height:30vw;
}
.cell img{
    width:100%;
    height:100%;
}

Make <body> fill entire screen?

I tried all the solutions above and I'm not discrediting any of them, but in my case, they didn't work.

For me, the problem was caused because the <header> tag had a margin-top of 5em and the <footer> had a margin-bottom of 5em. I removed them and instead put some padding (top and bottom, respectively). I'm not sure if replacing the margin was an ideal fix to the problem, but the point is that, if the first and last elements in your <body> has some margins, you might want to look into it and remove them.

My html and body tags had the following styles

body {
  line-height: 1;
  min-height: 100%;
  position: relative; }

html {
  min-height: 100%;
  background-color: #3c3c3c; }

System.Net.WebException HTTP status code

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

How to find Control in TemplateField of GridView?

string textboxID;
string da;
textboxID = "ctl00$MainContent$grd$ctl" + (grd.Columns.Count + j).ToString() + "$txtDyna" + (k).ToString();
textboxID= ctl00$MainContent$grd$ctl12$ctl00;
da = Request.Form(textboxID);

Setting maxlength of textbox with JavaScript or jQuery

without jQuery you can use

document.getElementById('text_input').setAttribute('maxlength',200);

How to detect when facebook's FB.init is complete

Instead of using any setTimeout or setInterval I would stick to deferred objects (implementation by jQuery here). It's still tricky to resolve queue in proper moment, because init don't have callbacks but combining result with event subscription (as someone pointed before me), should do the trick and be close enough.

Pseudo-snippet would look as follows:

FB.Event.subscribe('auth.statusChange', function(response) {
   if (response.authResponse) {
       // user has auth'd your app and is logged into Facebook
   } else {
       // user has not auth'd your app, or is not logged into Facebook
   }
   DeferredObject.resolve();
});

How can I get the current array index in a foreach loop?

In your sample code, it would just be $key.

If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:

$i = -1;
foreach($arr as $val) {
  $i++;
  //$i is now the index.  if $i == 0, then this is the first element.
  ...
}

Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.

TypeError: $ is not a function when calling jQuery function

You can use

jQuery(document).ready(function(){ ...... });

or

(function ($) { ...... }(jQuery));

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Try changing Tools > Options > Database Tools > Data Connections > SQL Server Instance Name.

The default for VS2013 is (LocalDB)\v11.0.

Changing to (LocalDB)\MSSQLLocalDB, for example, seems to work - no more version 782 error.

Horizontal ListView in Android?

HorizontialListView can't work when the data in the adapter is involved in another thread. Everything runs 100% on UI thread.This is a big problem in multithread. I think using HorizontialListView is not the best solution for your problem.HorzListView is a better way.You just replace your previous Gallery with HorzListView.You neednot modify the code about the adapter.Then everything goes the way you hope.See https://stackoverflow.com/a/12339708/1525777 about HorzListView.

Which mime type should I use for mp3

The standard way is to use audio/mpeg which is something like this in your PHP header function ...

header('Content-Type: audio/mpeg');

How to print formatted BigDecimal values?

 BigDecimal pi = new BigDecimal(3.14);
 BigDecimal pi4 = new BigDecimal(12.56);

 System.out.printf("%.2f",pi);

// prints 3.14

System.out.printf("%.0f",pi4);

// prints 13

How can I use goto in Javascript?

goto begin and end of all parents closures

var foo=false;
var loop1=true;
LABEL1: do {var LABEL1GOTO=false;
    console.log("here be 2 times");
    if (foo==false){
        foo=true;
        LABEL1GOTO=true;continue LABEL1;// goto up
    }else{
        break LABEL1; //goto down
    }
    console.log("newer go here");
} while(LABEL1GOTO);

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

How to change Vagrant 'default' machine name?

If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:

Change the basebox name, when using "vagrant status"

 config.vm.define "tendo" do |tendo|
  end

Where "tendo" will be the name that will appear instead of default

How to upgrade Git to latest version on macOS?

the simplest way I found so far is from git official website. It just computed dependencies and downloaded all of the required libraries/tools

http://git-scm.com/book/en/Getting-Started-Installing-Git

The other major way is to install Git via MacPorts (http://www.macports.org). If you have MacPorts installed, install Git via

$ sudo port install git-core +svn +doc +bash_completion +gitweb

How do I watch a file for changes?

Well, since you are using Python, you can just open a file and keep reading lines from it.

f = open('file.log')

If the line read is not empty, you process it.

line = f.readline()
if line:
    // Do what you want with the line

You may be missing that it is ok to keep calling readline at the EOF. It will just keep returning an empty string in this case. And when something is appended to the log file, the reading will continue from where it stopped, as you need.

If you are looking for a solution that uses events, or a particular library, please specify this in your question. Otherwise, I think this solution is just fine.

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:

text.+(.*)$

Example

text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      ^
                                                      last character


To replace anything that starts with "text" until "123"

text.+(\ 123)

Example

text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

npm install gives error "can't find a package.json file"

I was facing the same issue as below.

npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'D:\SVenu\FullStackDevelopment\Angular\Angular2_Splitter_CodeSkeleton\CodeSke leton\run\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent

The problem I made was, I was running the command npm build run instead of running npm run build.

Just sharing to help someone who does small mistakes like me.

How do you set a JavaScript onclick event to a class with css

It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:

$(document).ready(function(){
  $("a").click(function(){
    alert("hohoho");
  });
});

C# Collection was modified; enumeration operation may not execute

As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:

foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....

    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

What may not be obvious from the code above is where the Enumerator comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach loop gets expanded to by the compiler. The generated code will look something like:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator() returns) you will see:

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

Integer ASCII value to character in BASH using printf

this prints all the "printable" characters of your basic bash setup:

printf '%b\n' $(printf '\\%03o' {30..127})

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

How to pass arguments and redirect stdin from a file to program run in gdb?

Pass the arguments to the run command from within gdb.

$ gdb ./a.out
(gdb) r < t
Starting program: /dir/a.out < t

What is the difference between a HashMap and a TreeMap?

You almost always use HashMap, you should only use TreeMap if you need your keys to be in a specific order.

Java: How to check if object is null?

Edited Java 8 Solution:

final Drawable drawable = 
    Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
        .orElseGet(() -> getRandomDrawable());

You can declare drawable final in this case.

As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.

JTable won't show column headers

As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:

JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);

Angular.js directive dynamic templateURL

You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.

<div ng-repeat="week in [1,2]">
  <div ng-repeat="day in ['monday', 'tuesday']">
    <ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
  </div>
</div>

How to Get True Size of MySQL Database?

if you want to find it in MB do this

SELECT table_schema                                        "DB Name", 
   Round(Sum(data_length + index_length) / 1024 / 1024, 1) "DB Size in MB" 
FROM   information_schema.tables 
GROUP  BY table_schema; 

Best way to resolve file path too long exception

If you are having an issue with your bin files due to a long path, In Visual Studio 2015 you can go to the offending project's property page and change the relative Output Directory to a shorter one.

E.g. bin\debug\ becomes C:\_bins\MyProject\

How to properly ignore exceptions

How to properly ignore Exceptions?

There are several ways of doing this.

However, the choice of example has a simple solution that does not cover the general case.

Specific to the example:

Instead of

try:
    shutil.rmtree(path)
except:
    pass

Do this:

shutil.rmtree(path, ignore_errors=True)

This is an argument specific to shutil.rmtree. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.

>>> import shutil
>>> help(shutil.rmtree)

Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

General approach

Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.

New in Python 3.4:

You can import the suppress context manager:

from contextlib import suppress

But only suppress the most specific exception:

with suppress(FileNotFoundError):
    shutil.rmtree(path)

You will silently ignore a FileNotFoundError:

>>> with suppress(FileNotFoundError):
...     shutil.rmtree('bajkjbkdlsjfljsf')
... 
>>> 

From the docs:

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

Note that suppress and FileNotFoundError are only available in Python 3.

If you want your code to work in Python 2 as well, see the next section:

Python 2 & 3:

When you just want to do a try/except without handling the exception, how do you do it in Python?

Is the following the right way to do it?

try :
    shutil.rmtree ( path )
except :
    pass

For Python 2 compatible code, pass is the correct way to have a statement that's a no-op. But when you do a bare except:, that's the same as doing except BaseException: which includes GeneratorExit, KeyboardInterrupt, and SystemExit, and in general, you don't want to catch those things.

In fact, you should be as specific in naming the exception as you can.

Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
... and so on

You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.

We can get that specific error number from the errno library, and reraise if we don't have that:

import errno

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno == errno.ENOENT: # no such file or directory
        pass
    else: # we had an OSError we didn't expect, so reraise it
        raise 

Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass with code in the exception handling:

try:
    shutil.rmtree(path)
except OSError as error:
    if error.errno != errno.ENOENT: # no such file or directory
        raise 

How do I find the current machine's full hostname in C (hostname and domain information)?

My solution:

#ifdef WIN32
    #include <Windows.h>
    #include <tchar.h>
#else
    #include <unistd.h>
#endif

void GetMachineName(char machineName[150])
{
    char Name[150];
    int i=0;

    #ifdef WIN32
        TCHAR infoBuf[150];
        DWORD bufCharCount = 150;
        memset(Name, 0, 150);
        if( GetComputerName( infoBuf, &bufCharCount ) )
        {
            for(i=0; i<150; i++)
            {
                Name[i] = infoBuf[i];
            }
        }
        else
        {
            strcpy(Name, "Unknown_Host_Name");
        }
    #else
        memset(Name, 0, 150);
        gethostname(Name, 150);
    #endif
    strncpy(machineName,Name, 150);
}

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

If you are using a certificate signed by a Certificate Authority that is not included in the Java cacerts file by default, you need to complete the following configuration for HTTPS connections. To import certificates into cacerts:

  1. Open Windows Explorer and navigate to the cacerts file, which is located in the jre\lib\security subfolder where AX Core Client is installed. The default location is C:\Program Files\ACL Software\AX Core Client\jre\lib\security
  2. Create a backup copy of the file before making any changes.
  3. Depending on the certificates you receive from the Certificate Authority you are using, you may need to import an intermediate certificate and/or root certificate into the cacerts file. Use the following syntax to import certificates: keytool -import -alias -keystore -trustcacerts -file
  4. If you are importing both certificates the alias specified for each certificate should be unique.
  5. Type the password for the keystore at the “Password” prompt and press Enter. The default Java password for the cacerts file is “changeit”. Type ‘y’ at the “Trust this certificate?” prompt and press Enter.

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

Pretty printing JSON from Jackson 2.2's ObjectMapper

if you are using spring and jackson combination you can do it as following. I'm following @gregwhitaker as suggested but implementing in spring style.

<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
    <property name="dateFormat">
        <bean class="java.text.SimpleDateFormat">
            <constructor-arg value="yyyy-MM-dd" />
            <property name="lenient" value="false" />
        </bean>
    </property>
    <property name="serializationInclusion">
        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
            NON_NULL
        </value>
    </property>
</bean>

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject">
        <ref bean="objectMapper" />
    </property>
    <property name="targetMethod">
        <value>enable</value>
    </property>
    <property name="arguments">
        <value type="com.fasterxml.jackson.databind.SerializationFeature">
            INDENT_OUTPUT
        </value>
    </property>
</bean>

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Prevent Caching in ASP.NET MVC for specific actions using an attribute

For MVC6 (DNX), there is no System.Web.OutputCacheAttribute

Note: when you set NoStore Duration parameter is not considered. It is possible to set an initial duration for first registration and override this with custom attributes.

But we have Microsoft.AspNet.Mvc.Filters.ResponseCacheFilter

 public void ConfigureServices(IServiceCollection services)
        ...
        services.AddMvc(config=>
        {
            config.Filters.Add(
                 new ResponseCacheFilter(
                    new CacheProfile() { 
                      NoStore=true
                     }));
        }
        ...
       )

It is possible to override initial filter with a custom attribute

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class NoCacheAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var filter=filterContext.Filters.Where(t => t.GetType() == typeof(ResponseCacheFilter)).FirstOrDefault();
            if (filter != null)
            {
                ResponseCacheFilter f = (ResponseCacheFilter)filter;
                f.NoStore = true;
                //f.Duration = 0;
            }

            base.OnResultExecuting(filterContext);
        }
    }

Here is a use case

    [NoCache]
    [HttpGet]
    public JsonResult Get()
    {            
        return Json(new DateTime());
    }

Replace forward slash "/ " character in JavaScript string?

Escape it: someString.replace(/\//g, "-");

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

mailto using javascript

Please find the code in jsFiddle. It uses jQuery to modify the href of the link. You can use any other library in its place. It should work.

HTML

<a id="emailLnk" href="#">
    <img src="http://ssl.gstatic.com/gb/images/j_e6a6aca6.png">
</a>

JS

$(document).ready(function() {
    $("#emailLnk").attr('href',"mailto:[email protected]");
});?

UPDATE

Another code sample, if the id is known only during the click event

$(document).ready(function() {
    $("#emailLnk").click(function()
     {
         window.location.href = "mailto:[email protected]";
     });
});?

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...

Using port number in Windows host file

I managed to achieve this by using Windows included Networking tool netsh.

As Mat points out : The hosts file is for host name resolution only, so a combination of the two did the trick for me.

Example


Overview

example.app:80
 |                           <--Link by Hosts File
 +--> 127.65.43.21:80
       |                     <--Link by netsh Utility
       +--> localhost:8081

Actions

  • Started my server on localhost:8081
  • Added my "local DNS" in the hosts file as a new line
    • 127.65.43.21 example.app
      • Any free address in the network 127.0.0.0/8 (127.x.x.x) can be used.
      • Note: I am assuming 127.65.43.21:80 is not occupied by another service.
      • You can check with netstat -a -n -p TCP | grep "LISTENING"
  • added the following network configuration with netsh command utility
    • netsh interface portproxy add v4tov4 listenport=80 listenaddress=127.65.43.21 connectport=8081 connectaddress=127.0.0.1
  • I can now access the server at http://example.app

Notes:
- These commands/file modifications need to be executed with Admin rights

- netsh portproxy needs ipv6 libraries even only to use v4tov4, typically they will also be included by default, otherwise install them using the following command: netsh interface ipv6 install


You can see the entry you have added with the command:

netsh interface portproxy show v4tov4

You can remove the entry with the following command:

netsh interface portproxy delete v4tov4 listenport=80 listenaddress=127.65.43.21


Links to Resources:

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

AngularJS + JQuery : How to get dynamic content working in angularjs

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

AngularJS : When to use service instead of factory

Even when they say that all services and factories are singleton, I don't agree 100 percent with that. I would say that factories are not singletons and this is the point of my answer. I would really think about the name that defines every component(Service/Factory), I mean:

A factory because is not a singleton, you can create as many as you want when you inject, so it works like a factory of objects. You can create a factory of an entity of your domain and work more comfortably with this objects which could be like an object of your model. When you retrieve several objects you can map them in this objects and it can act kind of another layer between the DDBB and the AngularJs model.You can add methods to the objects so you oriented to objects a little bit more your AngularJs App.

Meanwhile a service is a singleton, so we can only create 1 of a kind, maybe not create but we have only 1 instance when we inject in a controller, so a service provides more like a common service(rest calls,functionality.. ) to the controllers.

Conceptually you can think like services provide a service, factories can create multiple instances(objects) of a class

Spark specify multiple column conditions for dataframe join

The === options give me duplicated columns. So I use Seq instead.

val Lead_all = Leads.join(Utm_Master,
    Seq("Utm_Source","Utm_Medium","Utm_Campaign"),"left")

Of course, this only works when the names of the joining columns are the same.

Linq to SQL .Sum() without group ... into

I know this is an old question but why can't you do it like:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Ruby, remove last N characters from a string?

Ruby 2.5+

As of Ruby 2.5 you can use delete_suffix or delete_suffix! to achieve this in a fast and readable manner.

The docs on the methods are here.

If you know what the suffix is, this is idiomatic (and I'd argue, even more readable than other answers here):

'abc123'.delete_suffix('123')     # => "abc"
'abc123'.delete_suffix!('123')    # => "abc"

It's even significantly faster (almost 40% with the bang method) than the top answer. Here's the result of the same benchmark:

                     user     system      total        real
chomp            0.949823   0.001025   0.950848 (  0.951941)
range            1.874237   0.001472   1.875709 (  1.876820)
delete_suffix    0.721699   0.000945   0.722644 (  0.723410)
delete_suffix!   0.650042   0.000714   0.650756 (  0.651332)

I hope this is useful - note the method doesn't currently accept a regex so if you don't know the suffix it's not viable for the time being. However, as the accepted answer (update: at the time of writing) dictates the same, I thought this might be useful to some people.

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

Angular 2: Get Values of Multiple Checked Checkboxes

I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

Method, which called on change is pushing value in model, or removing it.

public changeModel(ev, list, val) {
  if (ev.target.checked) {
    list.push(val);
  } else {
    let i = list.indexOf(val);
    list.splice(i, 1);
  }
}

Java : How to determine the correct charset encoding of a stream

You can certainly validate the file for a particular charset by decoding it with a CharsetDecoder and watching out for "malformed-input" or "unmappable-character" errors. Of course, this only tells you if a charset is wrong; it doesn't tell you if it is correct. For that, you need a basis of comparison to evaluate the decoded results, e.g. do you know beforehand if the characters are restricted to some subset, or whether the text adheres to some strict format? The bottom line is that charset detection is guesswork without any guarantees.

add an element to int [] array in java

The ... can only be used in JDK 1.5 or later. If you are using JDK 4 or lower, use this code:'

public static int[] addElement(int[] original, int newelement) {
    int[] nEw = new int[original.length + 1];
    System.arraycopy(original, 0, nEw, 0, original.length);
    nEw[original.length] = newelement;
}

otherwise (JDK 5 or higher):

public static int[] addElement(int[] original, int... elements) { // This can add multiple elements at once; addElement(int[], int) will still work though.
    int[] nEw = new int[original.length + elements.length];
    System.arraycopy(original, 0, nEw, 0, original.length);
    System.arraycopy(elements, 0, nEw, original.length, elements.length);
    return nEw;
}

Of course, as many have mentioned above, you could use a Collection or an ArrayList, which allows you to use the .add() method.

Checking from shell script if a directory contains files

Three best tricks


shopt -s nullglob dotglob; f=your/dir/*; ((${#f}))

This trick is 100% bash and invokes (spawns) a sub-shell. The idea is from Bruno De Fraine and improved by teambob's comment.

files=$(shopt -s nullglob dotglob; echo your/dir/*)
if (( ${#files} ))
then
  echo "contains files"
else 
  echo "empty (or does not exist or is a file)"
fi

Note: no difference between an empty directory and a non-existing one (and even when the provided path is a file).

There is a similar alternative and more details (and more examples) on the 'official' FAQ for #bash IRC channel:

if (shopt -s nullglob dotglob; f=(*); ((${#f[@]})))
then
  echo "contains files"
else 
  echo "empty (or does not exist, or is a file)"
fi

[ -n "$(ls -A your/dir)" ]

This trick is inspired from nixCraft's article posted in 2007. Add 2>/dev/null to suppress the output error "No such file or directory".
See also Andrew Taylor's answer (2008) and gr8can8dian's answer (2011).

if [ -n "$(ls -A your/dir 2>/dev/null)" ]
then
  echo "contains files (or is a file)"
else
  echo "empty (or does not exist)"
fi

or the one-line bashism version:

[[ $(ls -A your/dir) ]] && echo "contains files" || echo "empty"

Note: ls returns $?=2 when the directory does not exist. But no difference between a file and an empty directory.


[ -n "$(find your/dir -prune -empty)" ]

This last trick is inspired from gravstar's answer where -maxdepth 0 is replaced by -prune and improved by phils's comment.

if [ -n "$(find your/dir -prune -empty 2>/dev/null)" ]
then
  echo "empty (directory or file)"
else
  echo "contains files (or does not exist)"
fi

a variation using -type d:

if [ -n "$(find your/dir -prune -empty -type d 2>/dev/null)" ]
then
  echo "empty directory"
else
  echo "contains files (or does not exist or is not a directory)"
fi

Explanation:

  • find -prune is similar than find -maxdepth 0 using less characters
  • find -empty prints the empty directories and files
  • find -type d prints directories only

Note: You could also replace [ -n "$(find your/dir -prune -empty)" ] by just the shorten version below:

if [ `find your/dir -prune -empty 2>/dev/null` ]
then
  echo "empty (directory or file)"
else
  echo "contains files (or does not exist)"
fi

This last code works most of the cases but be aware that malicious paths could express a command...

How to check if two arrays are equal with JavaScript?

jQuery does not have a method for comparing arrays. However the Underscore library (or the comparable Lodash library) does have such a method: isEqual, and it can handle a variety of other cases (like object literals) as well. To stick to the provided example:

var a=[1,2,3];
var b=[3,2,1];
var c=new Array(1,2,3);

alert(_.isEqual(a, b) + "|" + _.isEqual(b, c));

By the way: Underscore has lots of other methods that jQuery is missing as well, so it's a great complement to jQuery.

EDIT: As has been pointed out in the comments, the above now only works if both arrays have their elements in the same order, ie.:

_.isEqual([1,2,3], [1,2,3]); // true
_.isEqual([1,2,3], [3,2,1]); // false

Fortunately Javascript has a built in method for for solving this exact problem, sort:

_.isEqual([1,2,3].sort(), [3,2,1].sort()); // true

How to open a txt file and read numbers in Java

import java.io.*;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileWriter  fin=new FileWriter("testout.txt");    
            BufferedWriter d = new BufferedWriter(fin);
            int a[] = new int[3];
            a[0]=1;
            a[1]=22;
            a[2]=3;
            String s="";
            for(int i=0;i<3;i++)
            {
                s=Integer.toString(a[i]);
                d.write(s);
                d.newLine();
            }

            System.out.println("Success");
            d.close();
            fin.close();    



            FileReader in=new FileReader("testout.txt");
            BufferedReader br=new BufferedReader(in);
            String i="";
            int sum=0;
            while ((i=br.readLine())!= null)
            {
                sum += Integer.parseInt(i);
            }
            System.out.println(sum);
          }catch(Exception e){System.out.println(e);}    
         }    
        }  

OUTPUT:: Success 26

Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.

Using setTimeout to delay timing of jQuery actions

.html() only takes a string OR a function as an argument, not both. Try this:

 $("#showDiv").click(function () {
     $('#theDiv').show(1000, function () {
         setTimeout(function () {
             $('#theDiv').html(function () {
                 setTimeout(function () {
                     $('#theDiv').html('Here is some replacement text');
                 }, 0);
                 setTimeout(function () {
                     $('#theDiv').html('More replacement text goes here');
                 }, 2500);
             });
         }, 2500);
     });
 }); //click function ends

jsFiddle example

Java, reading a file from current directory?

None of the above answer works for me. Here is what works for me.

Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));

What is the correct syntax of ng-include?

Maybe this will help for beginners

<!doctype html>
<html lang="en" ng-app>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="custom.css">
  </head>
  <body>
    <div ng-include src="'view/01.html'"></div>
    <div ng-include src="'view/02.html'"></div>
    <script src="angular.min.js"></script>
  </body>
</html>

Set The Window Position of an application via command line

I just found this question while on a quest to do the same thing.

After some experimenting I came across an answer that works the way the OQ would want and is simple as heck, but not very general purpose.

Create a shortcut on your desktop or elsewhere (you can use the create-shortcut helper from the right-click menu), set it to run the program "cmd.exe" and run it. When the window opens, position it where you want your window to be. To save that position, bring up the properties menu and hit "Save".

Now if you want you can also set other properties like colors and I highly recommend changing the buffer to be a width of 120-240 and the height to 9999 and enable quick edit mode (why aren't these the defaults!?!)

Now you have a shortcut that will work. Make one of these for each CMD window you want opened at a different location.

Now for the trick, the windows CMD START command can run shortcuts. You can't programmatically reposition the windows before launch, but at least it comes up where you want and you can launch it (and others) from a batch file or another program.

Using a shortcut with cmd /c you can create one shortcut that can launch ALL your links at once by using a command that looks like this:

cmd /c "start cmd_link1 && start cmd_link2 && start cmd_link3"

This will open up all your command windows to your favorite positions and individually set properties like foreground color, background color, font, administrator mode, quick-edit mode, etc... with a single click. Now move that one "link" into your startup folder and you've got an auto-state restore with no external programs at all.

This is a pretty straight-forward solution. It's not general purpose, but I believe it will solve the problem that most people reading this question are trying to solve.

I did this recently so I'll post my cmd file here:

cd /d C:\shortucts
for %%f in (*.lnk *.rdp *.url) do start %%f
exit

Late EDIT: I didn't mention that if the original cmd /c command is run elevated then every one of your windows can (if elevation was selected) start elevated without individually re-prompting you. This has been really handy as I start 3 cmd windows and 3 other apps all elevated every time I start my computer.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Why I get 'list' object has no attribute 'items'?

If you don't care about the type of the numbers you can simply use:

qs[0].values()

How do I write a "tab" in Python?

As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t is actually a TAB token whereas the described method generates spaces.

Example:

print "{0:30} {1}".format("hi", "yes")
> hi                             yes

Another Example, left aligned:

print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4 

Android: Getting a file URI from a content URI?

you can get filename by uri with simple way

Retrieving file information

fun get_filename_by_uri(uri : Uri) : String{
    contentResolver.query(uri, null, null, null, null).use { cursor ->
        cursor?.let {
            val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            it.moveToFirst()
            return it.getString(nameIndex)
        }
    }
    return ""
}

and easy to read it by using

contentResolver.openInputStream(uri)

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Run Stored Procedure in SQL Developer?

Use:

BEGIN

  PACKAGE_NAME.PROCEDURE_NAME(parameter_value, ...);

END;

Replace "PACKAGE_NAME", "PROCEDURE_NAME", and "parameter_value" with what you need. OUT parameters will need to be declared prior to.

The term 'ng' is not recognized as the name of a cmdlet

Open Edit the system environment variables

In the "Path" and "PS Module Path" variable add "%AppData%\npm"

Run Visual Code as Administrator

It works for me!

Change link color of the current page with CSS

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>

<style type="text/css"><!--

.class1 A:link {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333;  border-bottom: 4px solid #333333;}

.class1 A:visited {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333;  border-bottom: 4px solid #333333;}

.class1 A:hover {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF;  border-bottom: 2px solid #0000FF;}

.class1 A:active {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF;  border-bottom: 2px solid #0000FF;}

#nav_menu .current {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #FF0000; border-right: 3px solid #FF0000; border-top: 2px solid #FF0000;  border-bottom: 2px solid #FF0000;}


a:link {text-decoration:none;}

a:visited {text-decoration:none;}

a:hover {text-decoration:none;}

a:active {text-decoration:none;}

--></style>

</head>

<body style="background:#000000 url('...../images/bg.jpg') repeat-y top center fixed; width="100%" align="center">

<table style="table-layout:fixed; border:0px" width=100% height=100% border=0 cellspacing=0 cellpadding=0 align=center><tr>

<td style="background: url(...../images/menu_bg-menu.jpg) center no-repeat;" "border:0px" width="100%" height="100%" align="center" valign="middle">

<span class="class1" id="nav_menu">

<a href="http://Yourhomepage-url.com/" ***class="current"*** target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;Home&nbsp;&nbsp;</b></font></a>

&nbsp;&nbsp;

<a href="http://Yourhomepage-url.com/yourfaqspage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;FAQs page&nbsp;&nbsp;</b></font></a>

&nbsp;&nbsp;

<a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;About&nbsp;&nbsp;</b></font></a>

&nbsp;&nbsp;

<a href="http://Yourhomepage-url.com/yourcontactpage-url.php_or_.html" target="_parent"><font face="Georgia" color="#0000FF" size="2"><b>&nbsp;&nbsp;Contact&nbsp;&nbsp;</b></font></a>
</span>

</td></tr></table></body></html>

Note: the style goes in between the head tag (<head> .... </head>) and the class="class1" and the id="nav_menu" goes in the ie: (-- <span class="class1" id="nav_menu"> --).

Then the last class attribute (class="current") goes in the hyper-link code of the link in the page that you want the active current link to correspond to.

Example: You want the link tab to stay active or highlighted when it's correspondent page is whats currently in view, go to that page itself and place the class="current" attribute by it's link's html code. Only in the page that corresponds to the link so that when ever that page is at view, the tab will stay highlighted or stand out different from the rest of the tabs.

For the Home page, go to the home page and place the class in it. example: <a href="http://Yourhomepage-url.com/" class="current" target="_parent">

For the About page, go to the about page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">

For the Contact page, go to the contact page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">

etc ......

Notice the example Table above;- Lets assume this was the Home page, so on this page, only the Home url link section has the class="current"

Sorry for any meaning-less error, am not a prof. but this worked for me and displays fine in almost all the browsers tested, including ipad, and smart phones. Hope this will help some-one out here because is very frustrating to want to and not able to. I had tried so had to get to this, and so far it's good for me.

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can make use of ::marker pseudo element. This is useful in situations when you need to have different character entities for each list item.

ul li::marker {
  content: " "; /* Your symbol here */
}

_x000D_
_x000D_
ul li:nth-child(1)::marker {
  content: "\26BD   ";
}

ul li:nth-child(2)::marker {
  content: "\26C5   ";
}

ul li:nth-child(3)::marker {
  content: "\26F3   ";
}

ul li::marker {
  font-size: 20px;
}

ul li {
  margin: 15px 0;
  font-family: sans-serif;
  background: #BADA55;
  color: black;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-top: 5px;
}
_x000D_
<ul>
  <li>France Vs Croatia</li>
  <li>Cloudy with sunshine</li>
  <li>Golf session ahead</li>
</ul>
_x000D_
_x000D_
_x000D_

Reloading submodules in IPython

For some reason, neither %autoreload, nor dreload seem to work for the situation when you import code from one notebook to another. Only plain Python reload works:

reload(module)

Based on [1].

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

Callback functions in C++

The accepted answer is comprehensive but related to the question i just want to put an simple example here. I had a code that i'd written it a long time ago. i wanted to traverse a tree with in-order way (left-node then root-node then right-node) and whenever i reach to one Node i wanted to be able to call a arbitrary function so that it could do everything.

void inorder_traversal(Node *p, void *out, void (*callback)(Node *in, void *out))
{
    if (p == NULL)
        return;
    inorder_traversal(p->left, out, callback);
    callback(p, out); // call callback function like this.
    inorder_traversal(p->right, out, callback);
}


// Function like bellow can be used in callback of inorder_traversal.
void foo(Node *t, void *out = NULL)
{
    // You can just leave the out variable and working with specific node of tree. like bellow.
    // cout << t->item;
    // Or
    // You can assign value to out variable like below
    // Mention that the type of out is void * so that you must firstly cast it to your proper out.
    *((int *)out) += 1;
}
// This function use inorder_travesal function to count the number of nodes existing in the tree.
void number_nodes(Node *t)
{
    int sum = 0;
    inorder_traversal(t, &sum, foo);
    cout << sum;
}

 int main()
{

    Node *root = NULL;
    // What These functions perform is inserting an integer into a Tree data-structure.
    root = insert_tree(root, 6);
    root = insert_tree(root, 3);
    root = insert_tree(root, 8);
    root = insert_tree(root, 7);
    root = insert_tree(root, 9);
    root = insert_tree(root, 10);
    number_nodes(root);
}

Forward host port to docker container

Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run

ip addr

This will give you a list of network adapters, one of which will look something like

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
   valid_lft forever preferred_lft forever

You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.

Setting the target version of Java in ant javac

You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

Using {% url ??? %} in django templates

The url template tag will pass the parameter as a string and not as a function reference to reverse(). The simplest way to get this working is adding a name to the view:

url(r'^/logout/' , logout_view, name='logout_view')

How to declare a variable in SQL Server and use it in the same Stored Procedure

CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS    
BEGIN

DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand 
WHERE BrandName = @BrandName

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (@CategoryID, @BrandID)

END

EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1

Possible to change where Android Virtual Devices are saved?

Variable name: ANDROID_SDK_HOME
Variable value: C:\Users>User Name

worked for me.

Function inside a function.?

function inside a function or so called nested functions are very usable if you need to do some recursion processes such as looping true multiple layer of array or a file tree without multiple loops or sometimes i use it to avoid creating classes for small jobs which require dividing and isolating functionality among multiple functions. but before you go for nested functions you have to understand that

  1. child function will not be available unless the main function is executed
  2. Once main function got executed the child functions will be globally available to access
  3. if you need to call the main function twice it will try to re define the child function and this will throw a fatal error

so is this mean you cant use nested functions? No, you can with the below workarounds

first method is to block the child function being re declaring into global function stack by using conditional block with function exists, this will prevent the function being declared multiple times into global function stack.

function myfunc($a,$b=5){
    if(!function_exists("child")){
        function child($x,$c){
            return $c+$x;   
        }
    }
    
    try{
        return child($a,$b);
    }catch(Exception $e){
        throw $e;
    }
    
}

//once you have invoke the main function you will be able to call the child function
echo myfunc(10,20)+child(10,10);

and the second method will be limiting the function scope of child to local instead of global, to do that you have to define the function as a Anonymous function and assign it to a local variable, then the function will only be available in local scope and will re declared and invokes every time you call the main function.

function myfunc($a,$b=5){
    $child = function ($x,$c){
        return $c+$x;   
    };
    
    try{
        return $child($a,$b);
    }catch(Exception $e){
        throw $e;
    }
    
}

echo myfunc(10,20);

remember the child will not be available outside the main function or global function stack

Adding an arbitrary line to a matplotlib plot in ipython notebook

Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate() function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.

ax.annotate("",
            xy=(0.2, 0.2), xycoords='data',
            xytext=(0.8, 0.8), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                      connectionstyle="arc3, rad=0"),
            )

In the documentation it says you can draw only an arrow with an empty string as the first argument.

From the OP's example:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
              xy=(70, 90), xycoords='data',
              xytext=(90, 200), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              connectionstyle="arc3,rad=0."), 
              )

plt.show()

Example inline image

Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..

Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.

# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
              xy=(70, 100), xycoords='data',
              xytext=(70, 250), textcoords='data',
              arrowprops=dict(arrowstyle="-",
                              edgecolor = "red",
                              linewidth=5,
                              alpha=0.65,
                              connectionstyle="arc3,rad=0."), 
              )

You can also add curve to the connecting line by adjusting the connectionstyle.

Get Country of IP Address with PHP

You can use https://ip-api.io/ to get country name, city name, latitude and longitude. It supports IPv6.

As a bonus it will tell if ip address is a tor node, public proxy or spammer.

Php Code:

$result = json_decode(file_get_contents('http://ip-api.io/json/64.30.228.118'));
var_dump($result);

Output:

{
"ip": "64.30.228.118",
"country_code": "US",
"country_name": "United States",
"region_code": "FL",
"region_name": "Florida",
"city": "Fort Lauderdale",
"zip_code": "33309",
"time_zone": "America/New_York",
"latitude": 26.1882,
"longitude": -80.1711,
"metro_code": 528,
"suspicious_factors": {
"is_proxy": false,
"is_tor_node": false,
"is_spam": false,
"is_suspicious": false
}

Delete item from state array in react

removePeople(e){
    var array = this.state.people;
    var index = array.indexOf(e.target.value); // Let's say it's Bob.
    array.splice(index,1);
}

Redfer doc for more info

How do I check to see if my array includes an object?

If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

unless @suggested_horses.any? {|h| h.id == horse.id }
  @suggested_horses << horse
end

How to install CocoaPods?

These are the complete steps that I usually follow. I am posting this steps as short as possible and assuming that you know about Mac and Xcode projects. First of all, open the terminal and use the following commands, and press enter after each command.

Type in the following command if you don't already have CocoaPods installed:

sudo gem install cocoapods

Now please move to your Xcode Project directory by using this following command, and replace /Your Xcode Project Directory Path with the actual path to the directory:

cd /Your Xcode Project Directory Path

Below are instructions for how to use CocoaPods. Please wait for some time after each and every command entered to the terminal to execute successfully.

  1. Searching for pods in terminal:

pod search networking (replace networking with which you want to search)

  1. Creating the pod file:

pod init

  1. Opening the pod file:

open -a Xcode Podfile

  1. Adding the pods: (After adding your pods you must save the podfile first and then head back to the terminal again.)
target 'WebServiceUsingMantleAFNetworking' do
# platform :ios, '8.0' //Choose your version of iOS
pod 'AFNetworking', '~> 2.6.0’

end

OR

platform :ios, '8.0'
pod 'AFNetworking'
pod 'Mantle'
pod 'LBBlurredImage'
pod 'TSMessages'
pod 'ReactiveCocoa'
  1. Installing the pods:

pod install

  1. Check for updates of pods on existing project:

pod outdated

  1. Update the existing pods:

pod update

  1. Uninstall the Cocoapods from system:

sudo gem uninstall cocoapods

There is a complete tutorial for removing pods from your Xcode project on stackoverflow. You can check on this following link for more info.

How to remove CocoaPods from a project?

Thanks

Hope this helped.

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

Break string into list of characters in Python

You can do this using list:

new_list = list(fL)

Be aware that any spaces in the line will be included in this list, to the best of my knowledge.

How do I install ASP.NET MVC 5 in Visual Studio 2012?

I had trouble with the web installer not "finding the product"

The stand alone installer is located here:

https://www.microsoft.com/en-us/download/details.aspx?id=41532

The release/installation notes can be found at

http://www.asp.net/visual-studio/overview/2012/aspnet-and-web-tools-20131-for-visual-studio-2012

Dependency:

  • .NET 4.5
  • You need to select this version of the framework when creating a new project in order to view the MVC 5 project templates.

Included:

  • MVC5
  • Entity Framework 6
  • Web API 2
  • Bootstrap
  • Razor
  • Nuget 2.7

Excel is not updating cells, options > formula > workbook calculation set to automatic

My problem was that excel column was showing me "=concatenate(A1,B1)" instead of it 's value after concatenation.

I added a space after "," like this =concatenate(A1, B1) and it worked.

This is just an example that solved my problem.

Try and let me know if it works for you as well.

Sometimes it works without space as well, but at other times it doesn't.

How to declare a variable in MySQL?

  • Declare: SET @a = 1;

  • Usage: INSERT INTO `t` (`c`) VALUES (@a);

Run script with rc.local: script works, but not at boot

rc.local only runs on startup. If you reboot and want the script to execute, it needs to go into the rc.0 file starting with the K99 prefix.

How do you add PostgreSQL Driver as a dependency in Maven?

From site PostgreSQL, of date 02/04/2016 (https://jdbc.postgresql.org/download.html):

"This is the current version of the driver. Unless you have unusual requirements (running old applications or JVMs), this is the driver you should be using. It supports Postgresql 7.2 or newer and requires a 1.6 or newer JVM. It contains support for SSL and the javax.sql package. If you are using the 1.6 then you should use the JDBC4 version. If you are using 1.7 then you should use the JDBC41 version. If you are using 1.8 then you should use the JDBC42 versionIf you are using a java version older than 1.6 then you will need to use a JDBC3 version of the driver, which will by necessity not be current"

how to change attribute "hidden" in jquery

You can use jquery attr method

$("#delete").attr("hidden",true);

How do I add a simple onClick event handler to a canvas element?

As an alternative to alex's answer:

You could use a SVG drawing instead of a Canvas drawing. There you can add events directly to the drawn DOM objects.

see for example:

Making an svg image object clickable with onclick, avoiding absolute positioning