Programs & Examples On #Ostream

In C++ std::ostream is the base class for output streams.

how do I print an unsigned char as hex in c++ using ostream?

In C++20 you'll be able to use std::format to do this:

std::cout << std::format("a is {:x}; b is {:x}\n", a, b);

Output:

a is 0; b is ff

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print("a is {:x}; b is {:x}\n", a, b);

Disclaimer: I'm the author of {fmt} and C++20 std::format.

How to properly overload the << operator for an ostream?

To add to Mehrdad answer ,

namespace Math
{
    class Matrix
    {
       public:

       [...]


    }   
    std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}

In your implementation

std::ostream& operator<<(std::ostream& stream, 
                     const Math::Matrix& matrix) {
    matrix.print(stream); //assuming you define print for matrix 
    return stream;
 }

How to unit test abstract classes: extend with stubs?

To make an unit test specifically on the abstract class, you should derive it for testing purpose, test base.method() results and intended behaviour when inheriting.

You test a method by calling it so test an abstract class by implementing it...

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

How to remove all white spaces from a given text file

Dude, Just python test.py in your terminal.

f = open('/home/hduser/Desktop/data.csv' , 'r')

x = f.read().split()
f.close()

y = ' '.join(x)
f = open('/home/hduser/Desktop/data.csv','w')
f.write(y)
f.close()

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

UPDATE Sep 29 2016 for Angular 2.0 Final & VS 2015

The workaround is no longer needed, to fix you just need to install TypeScript version 2.0.3.

Fix taken from the edit on this github issue comment.

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

css ellipsis on second line

As others have already answered, a pure CSS solution does not exists. There is a jQuery plugin that is very easy to use, it is called dotdotdot. It uses the container's width and height to calculate if it needs to truncate and add ellipsis.

$("#multilinedElement").dotdotdot();

Here is a jsFiddle.

Random record from MongoDB

Now you can use the aggregate. Example:

db.users.aggregate(
   [ { $sample: { size: 3 } } ]
)

See the doc.

Get url parameters from a string in .NET

@Andrew and @CZFox

I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1 and not param1 which is what one would expect.

By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString function only requires a valid query string parameter containing only characters after the question mark as in:

HttpUtility.ParseQueryString ( "param1=good&param2=bad" )

My workaround:

string RawUrl = "http://www.example.com?param1=good&param2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
    RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );

Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`

Console.log(); How to & Debugging javascript

Breakpoints and especially conditional breakpoints are your friends.

Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)

Truncate/round whole number in JavaScript?

I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:

function truncateToInt(x)
{
    if(x > 0)
    {
         return Math.floor(x);
    }
    else
    {
         return Math.ceil(x);
    }
 }

Then:

y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3

Notice: This answer was written when Math.trunc(x) was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x).

Possible to make labels appear when hovering over a point in matplotlib?

It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(ind):

    pos = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

enter image description here

Because people also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently).

_x000D_
_x000D_
import matplotlib.pyplot as plt_x000D_
import numpy as np; np.random.seed(1)_x000D_
_x000D_
x = np.sort(np.random.rand(15))_x000D_
y = np.sort(np.random.rand(15))_x000D_
names = np.array(list("ABCDEFGHIJKLMNO"))_x000D_
_x000D_
norm = plt.Normalize(1,4)_x000D_
cmap = plt.cm.RdYlGn_x000D_
_x000D_
fig,ax = plt.subplots()_x000D_
line, = plt.plot(x,y, marker="o")_x000D_
_x000D_
annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",_x000D_
                    bbox=dict(boxstyle="round", fc="w"),_x000D_
                    arrowprops=dict(arrowstyle="->"))_x000D_
annot.set_visible(False)_x000D_
_x000D_
def update_annot(ind):_x000D_
    x,y = line.get_data()_x000D_
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])_x000D_
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), _x000D_
                           " ".join([names[n] for n in ind["ind"]]))_x000D_
    annot.set_text(text)_x000D_
    annot.get_bbox_patch().set_alpha(0.4)_x000D_
_x000D_
_x000D_
def hover(event):_x000D_
    vis = annot.get_visible()_x000D_
    if event.inaxes == ax:_x000D_
        cont, ind = line.contains(event)_x000D_
        if cont:_x000D_
            update_annot(ind)_x000D_
            annot.set_visible(True)_x000D_
            fig.canvas.draw_idle()_x000D_
        else:_x000D_
            if vis:_x000D_
                annot.set_visible(False)_x000D_
                fig.canvas.draw_idle()_x000D_
_x000D_
fig.canvas.mpl_connect("motion_notify_event", hover)_x000D_
_x000D_
plt.show()
_x000D_
_x000D_
_x000D_

In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis?

In case someone is looking for a solution for bar plots, please refer to e.g. this answer.

How to add a line to a multiline TextBox?

Above methods did not work for me. I got the following exception:

Exception : 'System.InvalidOperationException' in System.Windows.Forms.dll

Turns out I needed to call Invoke on my controls first. See answer here.

How to Git stash pop specific stash in 1.8.3?

You need to escape the braces:

git stash pop stash@\{1\}

How do I write out a text file in C# with a code page other than UTF-8?

Simple!

System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));

How do I conditionally apply CSS styles in AngularJS?

Another option when you need a simple css style of one or two properties:

View:

<tr ng-repeat="element in collection">
    [...amazing code...] 
    <td ng-style="{'background-color': getTrColor(element.myvar)}">
        {{ element.myvar }}
    </td>
    [...more amazing code...]
</tr>

Controller:

$scope.getTrColor = function (colorIndex) {
    switch(colorIndex){
        case 0: return 'red';
        case 1: return 'green';
        default: return 'yellow';
    }
};

How to run php files on my computer

You have to run a web server (e.g. Apache) and browse to your localhost, mostly likely on port 80.

What you really ought to do is install an all-in-one package like XAMPP, it bundles Apache, MySQL PHP, and Perl (if you were so inclined) as well as a few other tools that work with Apache and MySQL - plus it's cross platform (that's what the 'X' in 'XAMPP' stands for).

Once you install XAMPP (and there is an installer, so it shouldn't be hard) open up the control panel for XAMPP and then click the "Start" button next to Apache - note that on applications that require a database, you'll also need to start MySQL (and you'll be able to interface with it through phpMyAdmin). Once you've started Apache, you can browse to http://localhost.

Again, regardless of whether or not you choose XAMPP (which I would recommend), you should just have to start Apache.

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

How to call another controller Action From a controller in Mvc

This is exactly what I was looking for after finding that RedirectToAction() would not pass complex class objects.

As an example, I want to call the IndexComparison method in the LifeCycleEffectsResults controller and pass it a complex class object named model.

Here is the code that failed:

return RedirectToAction("IndexComparison", "LifeCycleEffectsResults", model);

Worth noting is that Strings, integers, etc were surviving the trip to this controller method, but generic list objects were suffering from what was reminiscent of C memory leaks.

As recommended above, here's the code I replaced it with:

var controller = DependencyResolver.Current.GetService<LifeCycleEffectsResultsController>();

var result = controller.IndexComparison(model);
return result;

All is working as intended now. Thank you for leading the way.

Node Sass couldn't find a binding for your current environment

node-sass runs an install script to download the required binary. If there are no environment variables, .npmrc variables or process arguments set then the binary is determined by using the current process platform, architecture and Node ABI version. Therefore, if you run node install in one application and then try to run node-sass in an application with a different platform/architecture/ABI, the binary won't have been downloaded. The solution is to manually download the binary or to fix the binary version using an environment variable (SASS_BINARY_NAME) or a .npmrc variable (sass_binary_name)

You can see the logic for this in the getBinaryPath function in node-sass\lib\extensions.js

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

I suppose one thing that may be concerning you is whether or not the entries could change, so that the 2 becomes a different number, for instance. You can put your mind at ease here, because in Python, integers are immutable, meaning they cannot change after they are created.

Not everything in Python is immutable, though. For example, lists are mutable---they can change after being created. So for example, if you had a list of lists

>>> a = [[1], [2], [3]]
>>> a[0].append(7)
>>> a
[[1, 7], [2], [3]]

Here, I changed the first entry of a (I added 7 to it). One could imagine shuffling things around, and getting unexpected things here if you are not careful (and indeed, this does happen to everyone when they start programming in Python in some way or another; just search this site for "modifying a list while looping through it" to see dozens of examples).

It's also worth pointing out that x = x + [a] and x.append(a) are not the same thing. The second one mutates x, and the first one creates a new list and assigns it to x. To see the difference, try setting y = x before adding anything to x and trying each one, and look at the difference the two make to y.

jQuery UI DatePicker - Change Date Format

This is what worked for me:

$.fn.datepicker.defaults.format = 'yy-mm-dd'

What are the best JVM settings for Eclipse?

Eclipse likes lots of RAM. Use at least -Xmx512M. More if available.

How to rename a single column in a data.frame?

You can use the rename.vars in the gdata package.

library(gdata)
df <- rename.vars(df, from = "oldname", to = "newname")

This is particularly useful where you have more than one variable name to change or you want to append or pre-pend some text to the variable names, then you can do something like:

df <- rename.vars(df, from = c("old1", "old2", "old3", 
         to = c("new1", "new2", "new3"))

For an example of appending text to a subset of variables names see: https://stackoverflow.com/a/28870000/180892

How to change sa password in SQL Server 2008 express?

You need to follow the steps described in Troubleshooting: Connecting to SQL Server When System Administrators Are Locked Out and add your own Windows user as a member of sysadmin:

  • shutdown MSSQL$EXPRESS service (or whatever the name of your SQL Express service is)
  • start add the -m and -f startup parameters (or you can start sqlservr.exe -c -sEXPRESS -m -f from console)
  • connect to DAC: sqlcmd -E -A -S .\EXPRESS or from SSMS use admin:.\EXPRESS
  • run create login [machinename\username] from windows to create your Windows login in SQL
  • run sp_addsrvrolemember 'machinename\username', 'sysadmin'; to make urself sysadmin member
  • restart service w/o the -m -f

Use ASP.NET MVC validation with jquery ajax?

What you should do is to serialize your form data and send it to the controller action. ASP.NET MVC will bind the form data to the EditPostViewModel object( your action method parameter), using MVC model binding feature.

You can validate your form at client side and if everything is fine, send the data to server. The valid() method will come in handy.

$(function () {

    $("#yourSubmitButtonID").click(function (e) {

        e.preventDefault();
        var _this = $(this);
        var _form = _this.closest("form");

        var isvalid = _form .valid();  // Tells whether the form is valid

        if (isvalid)
        {           
           $.post(_form.attr("action"), _form.serialize(), function (data) {
              //check the result and do whatever you want
           })
        }

    });

});

How to calculate a mod b in Python?

you can also try divmod(x, y) which returns a tuple (x // y, x % y)

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

Have you unistalled your Internet Explorer? I did, and I had the same issues, if so, you have to:

  1. Reactivate IE (Control Panel -- Programs and Features -- Turn Windows features on or off).
  2. restarting the computer
  3. (important!) running Windows Update to get all available updates for Microsoft Explorer
  4. restarting the computer (again)

Finally it works!

How do I concatenate or merge arrays in Swift?

Swift 5 Array Extension

extension Array where Element: Sequence {
    func join() -> Array<Element.Element> {
        return self.reduce([], +)
    }
}

Example:

let array = [[1,2,3], [4,5,6], [7,8,9]]
print(array.join())

//result: [1, 2, 3, 4, 5, 6, 7, 8, 9]

How to convert Map keys to array?

Array.from(myMap.keys()) does not work in google application scripts.

Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }.

To get a list of keys in GAS do this:

var keysList = Object.keys(myMap);

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o or netstat -ab, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.

I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.

Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.

How to select Python version in PyCharm?

Go to:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

There you can see which external libraries you have installed for python2 and which for python3.

Select the required python version according to your requirements.

Image

Change Volley timeout duration

req.setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

You can set MY_SOCKET_TIMEOUT_MS as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES can be 0 default is 1.

How to get label of select option with jQuery?

To get the label of a specific option in a dropdown yo can ty this --

$('.class_of_dropdown > option[value='value_to_be_searched']').html();

or

$('#id_of_dropdown > option[value='value_to_be_Searched']').html();

how to implement a long click listener on a listview

If you want to do it in the adapter, you can simply do this:

itemView.setOnLongClickListener(new View.OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(mContext, "Long pressed on item", Toast.LENGTH_SHORT).show();
            }
        });

Removing "http://" from a string

Use look behinds in preg_replace to remove anything before //.

preg_replace('(^[a-z]+:\/\/)', '', $url); 

This will only replace if found in the beginning of the string, and will ignore if found later

mysqldump data only

Would suggest using the following snippet. Works fine even with huge tables (otherwise you'd open dump in editor and strip unneeded stuff, right? ;)

mysqldump --no-create-info --skip-triggers --extended-insert --lock-tables --quick DB TABLE > dump.sql

At least mysql 5.x required, but who runs old stuff nowadays.. :)

Docker is installed but Docker Compose is not ? why?

I'm on debian, I found something quite natural to do :

apt-get install docker-compose

and it did the job (not tested on centos)

Reverse Contents in Array

Both answers look correct to me.

  1. The first arr[i] = temp; should be removed

  2. You should do a second loop to print all elements, not just half the array. The loop that does the reverse doesn't need to print it.

How to use variables in SQL statement in Python?

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Note that the parameters are passed as a tuple.

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. it does not do any escaping or quoting.
  2. it is prone to Uncontrolled string format attacks e.g. SQL injection.

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

How to extract the decision rules from scikit-learn decision-tree?

Now you can use export_text.

from sklearn.tree import export_text

r = export_text(loan_tree, feature_names=(list(X_train.columns)))
print(r)

A complete example from [sklearn][1]

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
X = iris['data']
y = iris['target']
decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
decision_tree = decision_tree.fit(X, y)
r = export_text(decision_tree, feature_names=iris['feature_names'])
print(r)

Why doesn't importing java.util.* include Arrays and Lists?

The difference between

import java.util.*;

and

import java.util.*;
import java.util.List;
import java.util.Arrays;

becomes apparent when the code refers to some other List or Arrays (for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays will be used.

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

How can I get the first two digits of a number?

Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:

num // 10 ** (int(math.log(num, 10)) - 1)

Function:

import math

def first_n_digits(num, n):
    return num // 10 ** (int(math.log(num, 10)) - n + 1)

Output:

>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456

You will need to add some checks if it's possible that your input number has less digits than you want.

sorting a vector of structs

Yes: you can sort using a custom comparison function:

std::sort(info.begin(), info.end(), my_custom_comparison);

my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.

Either way, the comparison function must yield a strict weak ordering of the elements.

How to capture a backspace on the onkeydown event

In your function check for the keycode 8 (backspace) or 46 (delete)

Keycode information
Keycode list

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

How to get all options of a select using jQuery?

For multiselect option:

$('#test').val() returns list of selected values. $('#test option').length returns total number of options (both selected and not selected)

Add zero-padding to a string

myInt.ToString("D4");

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

Parse JSON file using GSON

One thing that to be remembered while solving such problems is that in JSON file, a { indicates a JSONObject and a [ indicates JSONArray. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.

The Gson JsonReader documentation explains how to handle parsing of JsonObjects and JsonArrays:

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

Get generic type of java.util.List

You can do the same for method parameters as well:

Method method = someClass.getDeclaredMethod("someMethod");
Type[] types = method.getGenericParameterTypes();
//Now assuming that the first parameter to the method is of type List<Integer>
ParameterizedType pType = (ParameterizedType) types[0];
Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[0];
System.out.println(clazz); //prints out java.lang.Integer

How to add a tooltip to an svg graphic?

You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

C# Convert a Base64 -> byte[]

You're looking for the FromBase64Transform class, used with the CryptoStream class.

If you have a string, you can also call Convert.FromBase64String.

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

$lookup on ObjectId's in an array

I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

_x000D_
_x000D_
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
            localField: "products",_x000D_
            foreignField: "_id",_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

_x000D_
_x000D_
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
             let: { products: "$products"},_x000D_
             pipeline: [_x000D_
                 { $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
                 { $project: {_id: 0} } // suppress _id_x000D_
             ],_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

How can I use SUM() OVER()

Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID.

To obtain running totals with SUM() OVER (), you need to add an ORDER BY sub-clause after PARTITION BY …, like this:

SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)

But remember, not all database systems support ORDER BY in the OVER clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

My problem was: django-reversion>=1.8.7,<1.9

for django 1.9.7 you should use: django-reversion==1.10.0

I were upgraded django-cms 3.2 to 3.3, and found it by commenting apps, then uncommenting back.

Correct answer here: https://stackoverflow.com/a/34040556/2837890

An efficient way to Base64 encode a byte array?

Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):

    static public void testBase64EncodeToBuffer()
    {
        for (int i = 1; i < 200; ++i)
        {
            // prep test data
            byte[] testData = new byte[i];
            for (int j = 0; j < i; ++j)
                testData[j] = (byte)(j ^ i);

            // test
            testBase64(testData);
        }
    }

    static void testBase64(byte[] data)
    {
        if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
    }

    static public byte[] appendBase64(byte[] data
                              , int offset
                              , int size
                              , bool addLineBreaks = false)
    {
        byte[] buffer;
        int bufferPos = 0;
        int requiredSize = (4 * ((size + 2) / 3));
        // size/76*2 for 2 line break characters    
        if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);

        buffer = new byte[requiredSize];

        UInt32 octet_a;
        UInt32 octet_b;
        UInt32 octet_c;
        UInt32 triple;
        int lineCount = 0;
        int sizeMod = size - (size % 3);
        // adding all data triplets
        for (; offset < sizeMod;)
        {
            octet_a = data[offset++];
            octet_b = data[offset++];
            octet_c = data[offset++];

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
            if (addLineBreaks)
            {
                if (++lineCount == 19)
                {
                    buffer[bufferPos++] = 13;
                    buffer[bufferPos++] = 10;
                    lineCount = 0;
                }
            }
        }

        // last bytes
        if (sizeMod < size)
        {
            octet_a = offset < size ? data[offset++] : (UInt32)0;
            octet_b = offset < size ? data[offset++] : (UInt32)0;
            octet_c = (UInt32)0; // last character is definitely padded

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];

            // add padding '='
            sizeMod = size % 3;
            // last character is definitely padded
            buffer[bufferPos - 1] = (byte)'=';
            if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
        }
        return buffer;
    }

Place input box at the center of div

#the_div input {
  margin: 0 auto;
}

I'm not sure if this works in good ol' IE6, so you might have to do this instead.

/* IE 6 (probably) */
#the_div {
  text-align: center;
}

List all of the possible goals in Maven 2?

If you use IntelliJ IDEA you can browse all maven goals/tasks (including plugins) in Maven Projects tab:

Maven Projects

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

Python has a "not" operator, right? Is it not just "not"? As in,

  return not bool

Concat a string to SELECT * MySql

You cannot concatenate multiple fields with a string. You need to select a field instand of all (*).

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

If you are using XAMPP rather than WAMP, the path you go to is:

C:\xampp\phpMyAdmin\config.inc.php

Invoking modal window in AngularJS Bootstrap UI using JavaScript

OK, so first of all the http://angular-ui.github.io/bootstrap/ has a <modal> directive and the $dialog service and both of those can be used to open modal windows.

The difference is that with the <modal> directive content of a modal is embedded in a hosting template (one that triggers modal window opening). The $dialog service is far more flexible and allow you to load modal's content from a separate file as well as trigger modal windows from any place in AngularJS code (this being a controller, a service or another directive).

Not sure what you mean exactly by "using JavaScript code" but assuming that you mean any place in AngularJS code the $dialog service is probably a way to go.

It is very easy to use and in its simplest form you could just write:

$dialog.dialog({}).open('modalContent.html');  

To illustrate that it can be really triggered by any JavaScript code here is a version that triggers modal with a timer, 3 seconds after a controller was instantiated:

function DialogDemoCtrl($scope, $timeout, $dialog){
  $timeout(function(){
    $dialog.dialog({}).open('modalContent.html');  
  }, 3000);  
}

This can be seen in action in this plunk: http://plnkr.co/edit/u9HHaRlHnko492WDtmRU?p=preview

Finally, here is the full reference documentation to the $dialog service described here: https://github.com/angular-ui/bootstrap/blob/master/src/dialog/README.md

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

Concatenate two NumPy arrays vertically

Because both a and b have only one axis, as their shape is (3), and the axis parameter specifically refers to the axis of the elements to concatenate.

this example should clarify what concatenate is doing with axis. Take two vectors with two axis, with shape (2,3):

a = np.array([[1,5,9], [2,6,10]])
b = np.array([[3,7,11], [4,8,12]])

concatenates along the 1st axis (rows of the 1st, then rows of the 2nd):

np.concatenate((a,b), axis=0)
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

concatenates along the 2nd axis (columns of the 1st, then columns of the 2nd):

np.concatenate((a, b), axis=1)
array([[ 1,  5,  9,  3,  7, 11],
       [ 2,  6, 10,  4,  8, 12]])

to obtain the output you presented, you can use vstack

a = np.array([1,2,3])
b = np.array([4,5,6])
np.vstack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

You can still do it with concatenate, but you need to reshape them first:

np.concatenate((a.reshape(1,3), b.reshape(1,3)))
array([[1, 2, 3],
       [4, 5, 6]])

Finally, as proposed in the comments, one way to reshape them is to use newaxis:

np.concatenate((a[np.newaxis,:], b[np.newaxis,:]))

How to get the absolute path to the public_html folder?

something I found today, after reading this question and continuing on my googlesurf:

https://docs.joomla.org/How_to_find_your_absolute_path

<?php
$path = getcwd();
echo "This Is Your Absolute Path: ";
echo $path;
?>

works for me

Java: export to an .jar file in eclipse

FatJar can help you in this case.

In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects

This is useful if your final exported jar includes other external jars.

If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.

After Ganymede, you have:

Export Jar

How to refresh Android listview?

I was only able to get notifyDataSetChanged only by getting new adapter data, then resetting the adapter for the list view, then making the call like so:

    expandableAdapter = baseFragmentParent.setupEXLVAdapter();
    baseFragmentParent.setAdapter(expandableAdapter);
    expandableAdapter.notifyDataSetChanged(); 

Validation to check if password and confirm password are same is not working

if((pswd.length<6 || pswd.length>12) || pswd == ""){
        document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;

} 

else {  
    if(pswd != pswdcnf) {
        document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
    } else {
        document.getElementById("passwordconfirm").innerHTML="password  matche";
        document.getElementById("passwordloc").innerHTML = '';
    }

}

Lock, mutex, semaphore... what's the difference?

There are a lot of misconceptions regarding these words.

This is from a previous post (https://stackoverflow.com/a/24582076/3163691) which fits superb here:

1) Critical Section= User object used for allowing the execution of just one active thread from many others within one process. The other non selected threads (@ acquiring this object) are put to sleep.

[No interprocess capability, very primitive object].

2) Mutex Semaphore (aka Mutex)= Kernel object used for allowing the execution of just one active thread from many others, among different processes. The other non selected threads (@ acquiring this object) are put to sleep. This object supports thread ownership, thread termination notification, recursion (multiple 'acquire' calls from same thread) and 'priority inversion avoidance'.

[Interprocess capability, very safe to use, a kind of 'high level' synchronization object].

3) Counting Semaphore (aka Semaphore)= Kernel object used for allowing the execution of a group of active threads from many others. The other non selected threads (@ acquiring this object) are put to sleep.

[Interprocess capability however not very safe to use because it lacks following 'mutex' attributes: thread termination notification, recursion?, 'priority inversion avoidance'?, etc].

4) And now, talking about 'spinlocks', first some definitions:

Critical Region= A region of memory shared by 2 or more processes.

Lock= A variable whose value allows or denies the entrance to a 'critical region'. (It could be implemented as a simple 'boolean flag').

Busy waiting= Continuosly testing of a variable until some value appears.

Finally:

Spin-lock (aka Spinlock)= A lock which uses busy waiting. (The acquiring of the lock is made by xchg or similar atomic operations).

[No thread sleeping, mostly used at kernel level only. Ineffcient for User level code].

As a last comment, I am not sure but I can bet you some big bucks that the above first 3 synchronizing objects (#1, #2 and #3) make use of this simple beast (#4) as part of their implementation.

Have a good day!.

References:

-Real-Time Concepts for Embedded Systems by Qing Li with Caroline Yao (CMP Books).

-Modern Operating Systems (3rd) by Andrew Tanenbaum (Pearson Education International).

-Programming Applications for Microsoft Windows (4th) by Jeffrey Richter (Microsoft Programming Series).

Also, you can take a look at look at: https://stackoverflow.com/a/24586803/3163691

'sudo gem install' or 'gem install' and gem locations

In case you

  • installed ruby gems with sudo
  • want to install gems without sudo
  • don't want to install rvm/rbenv

add the following to your .bash_profile :

export GEM_HOME=/Users/‹your_user›/.gem
export PATH="$GEM_HOME/bin:$PATH"

Open a new tab in Terminal OR source ~/.bash_profile and you're good to go!

Why aren't Xcode breakpoints functioning?

Another thing to check is that if you have an "Entitlements" plist file for your debug mode (possibly because you're doing stuff with the Keychain), make sure that plist file has the "get-task-allow" = YES row. Without it, debugging and logging will be broken.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

Django error - matching query does not exist

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return Comment.objects.get(pk=id)
    except Comment.DoesNotExist:
        return False

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

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

run the following command

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

then

sudo apt-get install oracle-java8-installer

this would install oracle java 8 on ubuntu properly.

find it from this post

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

Xcode 'CodeSign error: code signing is required'

Make sure that you have created provisioning profiles correctly.. if you did.. you must be having ... public key, private key and Certificate in Keychain Access. CHECK if you have all these..

XCode 3.2.4 Comes with the Auto device provisioning ... so you just have to sign in to your developers account it will download all valid profiles..

If you have all you need in keychain and downloaded profiles... When you are selecting iPhone Developer: Aaron Milam'. in build settings.. make sure you have selected Configuration ( on left top inside Target->Build ) you want to make build for. or you can do All configuration to make changes in all available configurations i.e. Debug, Release etc.

error::make_unique is not a member of ‘std’

1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>

How to make space between LinearLayout children?

An easy way to do it dynamically is to add padding to the children. You can just set it using .setPadding() on the object to be added. This example is adding an ImageView to a LinearLayout:

LinearLayout userFeedLinearLayout = (LinearLayout) findViewById(R.id.userFeedLinearLayout);
imageView.setImageBitmap(bitmap);
imageView.setPadding(0, 30, 0, 30);
userFeedLinearLayout.addView(imageView);

The following image shows two ImageViews that have been added with padding:

Padding On Children

How to use Select2 with JSON via Ajax request?

Here you have an example

$("#profiles-thread").select2({
    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: URL,
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.completeName,
                        slug: item.slug,
                        id: item.id
                    }
                })
            };
        }
    }
});

It's quite easy

Application Installation Failed in Android Studio

Easily can be solved this problem.

Ex:- in Huawei GR3 mobile,

Goto Setting in your mobile -> Storage -> Storage Cleaner

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

About "*.d.ts" in TypeScript

This answer assumes you have some JavaScript that you don't want to convert to TypeScript, but you want to benefit from type checking with minimal changes to your .js. A .d.ts file is very much like a C or C++ header file. Its purpose is to define an interface. Here is an example:

mashString.d.ts

/** Makes a string harder to read. */
declare function mashString(
    /** The string to obscure */
    str: string
):string;
export = mashString;

mashString.js

// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");

main.js

// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));

The relationship here is: mashString.d.ts defines an interface, mashString.js implements the interface and main.js uses the interface.

To get the type checking to work you add // @ts-check to your .js files. But this only checks that main.js uses the interface correctly. To also ensure that mashString.js implements it correctly we add /** @type {import("./mashString")} */ before the export.

You can create your initial .d.ts files using tsc -allowJs main.js -d then edit them as required manually to improve the type checking and documentation.

In most cases the implementation and interface have the same name, here mashString. But you can have alternative implementations. For example we could rename mashString.js to reverse.js and have an alternative encryptString.js.

possibly undefined macro: AC_MSG_ERROR

I solved this by yum install libtool

Hibernate throws org.hibernate.AnnotationException: No identifier specified for entity: com..domain.idea.MAE_MFEView

This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too

In my case I had

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import org.springframework.data.annotation.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

when I change the code like this, it got worked

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;

import javax.persistence.Id;

@Entity
public class Status {

    @Id
    @GeneratedValue
    private int id;

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

List of standard lengths for database fields

W3C's recommendation:

If designing a form or database that will accept names from people with a variety of backgrounds, you should ask yourself whether you really need to have separate fields for given name and family name.

… Bear in mind that names in some cultures can be quite a lot longer than your own. … Avoid limiting the field size for names in your database. In particular, do not assume that a four-character Japanese name in UTF-8 will fit in four bytes – you are likely to actually need 12.

https://www.w3.org/International/questions/qa-personal-names

For database fields, VARCHAR(255) is a safe default choice, unless you can actually come up with a good reason to use something else. For typical web applications, performance won't be a problem. Don't prematurely optimize.

How to make fixed header table inside scrollable div?

use StickyTableHeaders.js for this.

Header was transparent . so try to add this css .

thead {
    border-top: none;
    border-bottom: none;
    background-color: #FFF;
}

Can a local variable's memory be accessed outside its scope?

Your code is very risky. You are creating a local variable (wich is considered destroyed after function ends) and you return the address of memory of that variable after it is destoyed.

That means the memory address could be valid or not, and your code will be vulnerable to possible memory address issues (for example segmentation fault).

This means that you are doing a very bad thing, becouse you are passing a memory address to a pointer wich is not trustable at all.

Consider this example, instead, and test it:

int * foo()
{
   int *x = new int;
   *x = 5;
   return x;
}

int main()
{
    int* p = foo();
    std::cout << *p << "\n"; //better to put a new-line in the output, IMO
    *p = 8;
    std::cout << *p;
    delete p;
    return 0;
}

Unlike your example, with this example you are:

  • allocating memory for int into a local function
  • that memory address is still valid also when function expires, (it is not deleted by anyone)
  • the memory address is trustable (that memory block is not considered free, so it will be not overridden until it is deleted)
  • the memory address should be deleted when not used. (see the delete at the end of the program)

What is an .axd file?

from Google

An .axd file is a HTTP Handler file. There are two types of .axd files.

  1. ScriptResource.axd
  2. WebResource.axd

These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.

Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere

And ofcourse it is necessary

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

onchange event on input type=range is not triggering in firefox while dragging

You could use the JavaScript "ondrag" event to fire continuously. It is better than "input" due to the following reasons:

  1. Browser support.

  2. Could differentiate between "ondrag" and "change" event. "input" fires for both drag and change.

In jQuery:

$('#sample').on('drag',function(e){

});

Reference: http://www.w3schools.com/TAgs/ev_ondrag.asp

Finding median of list in Python

Python 3.4 has statistics.median:

Return the median (middle value) of numeric data.

When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values:

>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0

Usage:

import statistics

items = [6, 1, 8, 2, 3]

statistics.median(items)
#>>> 3

It's pretty careful with types, too:

statistics.median(map(float, items))
#>>> 3.0

from decimal import Decimal
statistics.median(map(Decimal, items))
#>>> Decimal('3')

How do I get into a Docker container's shell?

If you have Docker installed with Kitematic, you can use the GUI. Open Kitematic from the Docker icon and in the Kitematic window select your container, and then click on the exec icon.

You can see the container log and lots of container information (in settings tab) in this GUI too.

Select Kitematic from menu

Click on exec

How to add anchor tags dynamically to a div in Javascript?

With jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript

   var new_a = document.createElement('a');
   new_a.setAttribute("href", "link url here");
   new_a.innerHTML = "your link text";
   //add new link to the DOM
   document.appendChild(new_a);

A completely free agile software process tool

Try http://www.icescrum.org . It is free to use. And it has lot of cool features. Perfect for scrum teams.

Recursively find all files newer than a given time

Given a unix timestamp (seconds since epoch) of 1494500000, do:

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)"

To grep those files for "foo":

find . -type f -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d @1494500000)" -exec grep -H 'foo' '{}' \;

How to set the context path of a web application in Tomcat 7.0

Here follows the only solutions that worked for me. Add this to the Host node in the conf/server.xml

<Context path="" docBase="yourAppContextName">

  <!-- Default set of monitored resources -->
  <WatchedResource>WEB-INF/web.xml</WatchedResource>

</Context>

go to Tomcat server.xml file and set path blank

What are the most common naming conventions in C?

There could be many, mainly IDEs dictate some trends and C++ conventions are also pushing. For C commonly:

  • UNDERSCORED_UPPER_CASE (macro definitions, constants, enum members)
  • underscored_lower_case (variables, functions)
  • CamelCase (custom types: structs, enums, unions)
  • uncappedCamelCase (oppa Java style)
  • UnderScored_CamelCase (variables, functions under kind of namespaces)

Hungarian notation for globals are fine but not for types. And even for trivial names, please use at least two characters.

mysqldump with create database line

The simplest solution is to use option -B or --databases.Then CREATE database command appears in the output file. For example:

mysqldump -uuser -ppassword -d -B --events --routines --triggers database_example > database_example.sql

Here is a dumpfile's header:

-- MySQL dump 10.13  Distrib 5.5.36-34.2, for Linux (x86_64)
--
-- Host: localhost    Database: database_example
-- ------------------------------------------------------
-- Server version       5.5.36-34.2-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `database_example`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `database_example` /*!40100 DEFAULT CHARACTER SET utf8 */;

How do I remove background-image in css?

If your div rule is just div {...}, then #a {...} will be sufficient. If it is more complicated, you need a "more specific" selector, as defined by the CSS specification on specificity. (#a being more specific than div is just single aspect in the algorithm.)

estimating of testing effort as a percentage of development time

The Google Testing Blog discussed this problem recently:

So a naive answer is that writing test carries a 10% tax. But, we pay taxes in order to get something in return.

(snip)

These benefits translate to real value today as well as tomorrow. I write tests, because the additional benefits I get more than offset the additional cost of 10%. Even if I don't include the long term benefits, the value I get from test today are well worth it. I am faster in developing code with test. How much, well that depends on the complexity of the code. The more complex the thing you are trying to build is (more ifs/loops/dependencies) the greater the benefit of tests are.

How to update ruby on linux (ubuntu)?

Ruby is v2.0 now. Programs like Jekyll (and I am sure many others) require it. I just ran:

sudo apt-get install ruby2.0

check version

ruby --version

Hope that helps

Python exit commands - why so many and when should each be used?

sys.exit is the canonical way to exit.

Internally sys.exit just raises SystemExit. However, calling sys.exitis more idiomatic than raising SystemExit directly.

os.exit is a low-level system call that exits directly without calling any cleanup handlers.

quit and exit exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit or quit. While this will not exit the interpreter, it at least issues a message that tells them a way out:

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$

This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__ of any expression that you enter at the prompt.

How do I count unique values inside a list

How about:

import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

It returns how many unique values are in a list

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Efficiently replace all accented characters in a string?

Simply should be normalized chain and run a replacement codes:

var str = "Letras Á É Í Ó Ú Ñ - á é í ó ú ñ...";
console.log (str.normalize ("NFKD").replace (/[\u0300-\u036F]/g, ""));
// Letras A E I O U N - a e i o u n...

See normalize

Then you can use this function:

function noTilde (s) {
    if (s.normalize != undefined) {
        s = s.normalize ("NFKD");
    }
    return s.replace (/[\u0300-\u036F]/g, "");
}

changing the language of error message in required field in html5 contact form

setCustomValidity's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.

You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.

The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message.

<input type="text" required title="Lütfen isaretli yerleri doldurunuz" />

enter image description here

If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.

Check if current directory is a Git repository

Another solution is to check for the command's exit code.

git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1

This will print 1 if you're in a git repository folder.

Insert data into hive table

If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query

INSERT INTO TABLE tweet_table 
  SELECT  "my_data" AS my_column 
    FROM   pre_loaded_tbl 
   LIMIT   5;

Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.

However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.

How to convert String object to Boolean Object?

To get the boolean value of a String, try this:

public boolean toBoolean(String s) {
    try {
        return Boolean.parseBoolean(s); // Successfully converted String to boolean
    } catch(Exception e) {
        return null; // There was some error, so return null.
    }
}

If there is an error, it will return null. Example:

toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

After experimenting on that case: android:textColor="@colors/text_color" is wrong since @color is not filename dependant. You can name your resource file foobar.xml, it doesn't matter but if you have defined some colors in it you can access them using @color/some_color.

Update:

file location: res/values/colors.xml The filename is arbitrary. The element's name will be used as the resource ID. (Source)

keycode 13 is for which key

The Enter key should have the keycode 13. Is it not working?

How can I add comments in MySQL?

Three types of commenting are supported

  1. Hash base single line commenting using #

    Select * from users ; # this will list users
    
    1. Double Dash commenting using --

    Select * from users ; -- this will list users

Note : Its important to have single white space just after --

3) Multi line commenting using /* */

Select * from users ; /* this will list users */

What's the best way of scraping data from a website?

You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.

Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.

Tools

Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.

You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.

Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.

Language

PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.

A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.

Javascript-heavy sites

In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.

There are two approaches to this problem:

The low level approach:

You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.

The embedded browser approach:

Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.

If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.

You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.

Which approach is best?

That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.

The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.

Rate Limiting/Bot behaviour

You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.

Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.

You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.

Testing

Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.

There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.

The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.

You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.

Legal Issues

The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.

The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.

It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.

Who am I to write this giant wall of text anyway?

I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.

I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)

I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.

I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.

Private vs Protected - Visibility Good-Practice Concern

Stop abusing private fields!!!

The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.

Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.

There are two cases you want to extend a class:

  • You want to add extra functionality to a base class
  • You want to modify existing class that's outside the current package (in some libraries perhaps)

There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.

Consider a simple library that models cars:

class Car {
    private screw;
    public assembleCar() {
       screw.install();
    };
    private putScrewsTogether() {
       ...
    };
}

The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.

Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.

Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.

The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.

I very much support Nick's answer.

ASP.NET Web API application gives 404 when deployed at IIS 7

I had as same problem . afer lot of R&D i found the problem.

but as long as your configuration are finne mean that aspnet 64 bit and the IIS well then the only problem i saw is the path " web api taking the local directiry path" so that you need to avid it. by like this.. ~../../../api/products/

thank you very much for posting the problem. i leanred alot abt iis and other setting in config file.

Get the _id of inserted document in Mongo database in NodeJS

There is a second parameter for the callback for collection.insert that will return the doc or docs inserted, which should have _ids.

Try:

collection.insert(objectToInsert, function(err,docsInserted){
    console.log(docsInserted);
});

and check the console to see what I mean.

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

Echo tab characters in bash script

echo -e ' \t '

will echo 'space tab space newline' (-e means 'enable interpretation of backslash escapes'):

$ echo -e ' \t ' | hexdump -C
00000000  20 09 20 0a                                       | . .|

Push Notifications in Android Platform

I recommend using GCM - Google Cloud Messaging for Android It's free, and for simple uses it's should be very easy.

However it requires to maintain a 3rd side server to send the notifications on your behalf. If you want to avoid that there are some very good industrial solutions for Android push notifications service:

  • Urban Airship - free up to 1M notifications per month, afterwards you are charged per 1000 notifications
  • PushApps - free for 1M notifications per month, and unlimited notifications for 19.99 per month
  • PushWoosh - free for 1M devices, premium plans are from 39 EURO

Diclaimer - I work in PushApps and also use their product in my applications for over a year now.

How to open a different activity on recyclerView item onclick

iconView = (ImageView) itemLayoutView .findViewById(R.id.iconId);

        itemLayoutView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), SecondPage.class);
                v.getContext().startActivity(intent);
                Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });

How to use Class<T> in Java?

As other answers point out, there are many and good reasons why this class was made generic. However there are plenty of times that you don't have any way of knowing the generic type to use with Class<T>. In these cases, you can simply ignore the yellow eclipse warnings or you can use Class<?> ... That's how I do it ;)

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

Android WebView Cookie Problem

This is a working bit of code.

    private void setCookie(DefaultHttpClient httpClient, String url) {
    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    if (cookies != null) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);

        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = cookies.get(i);
            String cookieString = cookie.getName() + "=" + cookie.getValue();
            cookieManager.setCookie(url, cookieString);
        }
        CookieSyncManager.getInstance().sync();
    }
}

Here the httpclient is the DefaultHttpClient object you used in the HttpGet/HttpPost request. Also one thing to make sure is the cookie name and value, it should be given

String cookieString = cookie.getName() + "=" + cookie.getValue();

setCookie will the set the cookie for the given URL.

What are the main differences between JWT and OAuth authentication?

It looks like everybody who answered here missed the moot point of OAUTH

From Wikipedia

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.

The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access

There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points

You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general

Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials

crop text too long inside div

Why not use relative units?

.cropText {
    max-width: 20em;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

How does database indexing work?

Just think of Database Index as Index of a book.

If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast.

Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for.

In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where 0x77129 is the address on the disk where the row data for German Shepherd is stored.

In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.

Why Choose Struct Over Class?

Answering the question from the perspective of value types vs reference types, from this Apple blog post it would appear very simple:

Use a value type [e.g. struct, enum] when:

  • Comparing instance data with == makes sense
  • You want copies to have independent state
  • The data will be used in code across multiple threads

Use a reference type [e.g. class] when:

  • Comparing instance identity with === makes sense
  • You want to create shared, mutable state

As mentioned in that article, a class with no writeable properties will behave identically with a struct, with (I will add) one caveat: structs are best for thread-safe models -- an increasingly imminent requirement in modern app architecture.

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

Expected corresponding JSX closing tag for input Reactjs

All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.

Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:

<hr class="my-4">
<input
  type="password"
  id="inputPassword"
  class="form-control"
  placeholder="Password"
  required
 >

Fix:

<hr class="my-4"/>
<input
 type="password"
 id="inputPassword"
 class="form-control"
 placeholder="Password"
 required
/>

The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Windows batch: sleep

The Windows 2003 Resource Kit has a sleep batch file. If you ever move up to PowerShell, you can use:

Start-Sleep -s <time to sleep>

Or something like that.

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

MySQL - ignore insert error: duplicate entry

You can use INSERT... IGNORE syntax if you want to take no action when there's a duplicate record.

You can use REPLACE INTO syntax if you want to overwrite an old record with a new one with the same key.

Or, you can use INSERT... ON DUPLICATE KEY UPDATE syntax if you want to perform an update to the record instead when you encounter a duplicate.

Edit: Thought I'd add some examples.

Examples

Say you have a table named tbl with two columns, id and value. There is one entry, id=1 and value=1. If you run the following statements:

REPLACE INTO tbl VALUES(1,50);

You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then:

INSERT IGNORE INTO tbl VALUES (1,10);

The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally:

INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;

You now have a single record with id=1 and value=200.

Is there a css cross-browser value for "width: -moz-fit-content;"?

Mozilla's MDN suggests something like the following [source]:

 p {
  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
  width: -moz-max-content;    /* Firefox/Gecko */
  width: -webkit-max-content; /* Chrome */
}

Copying files from one directory to another in Java

Spring Framework has many similar util classes like Apache Commons Lang. So there is org.springframework.util.FileSystemUtils

File src = new File("/home/user/src");
File dest = new File("/home/user/dest");
FileSystemUtils.copyRecursively(src, dest);

How to download/upload files from/to SharePoint 2013 using CSOM?

A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .

https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/

The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.

using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;

using ClientOM = Microsoft.SharePoint.Client;

namespace MvcApplication.Models.Home
{
    public class SharepointModel
    {
        public ClientContext clientContext { get; set; }
        private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
        private string LibraryUrl = "Shared Documents/Invoices/";
        private string UserName = "[email protected]";
        private string Password = "********";
        private Web WebClient { get; set; }

        public SharepointModel()
        {
            this.Connect();
        }

        public void Connect()
        {
            try
            {
                using (clientContext = new ClientContext(ServerSiteUrl))
                {
                    var securePassword = new SecureString();
                    foreach (char c in Password)
                    {
                        securePassword.AppendChar(c);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
                    WebClient = clientContext.Web;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
        {
            try
            {
                HttpPostedFileBase file = null;
                for (int f = 0; f < Request.Files.Count; f++)
                {
                    file = Request.Files[f] as HttpPostedFileBase;

                    string[] SubFolders = LibraryUrl.Split('/');
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
                    file.SaveAs(path);

                    clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    //https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
                    List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
                    clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
                    clientContext.ExecuteQuery();

                    string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
                    var folderToBindTo = documentsList.RootFolder.Folders;
                    var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();

                    var fileCreationInformation = new FileCreationInformation();
                    //Assign to content byte[] i.e. documentStream
                    fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
                    //Allow owerwrite of document
                    fileCreationInformation.Overwrite = true;
                    //Upload URL
                    fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;

                    Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);

                    //Update the metadata for a field having name "DocType"
                    uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";

                    uploadFile.ListItemAllFields.Update();
                    clientContext.ExecuteQuery();
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string DownloadFiles()
        {
            try
            {
                string tempLocation = @"c:\Downloads\Sharepoint\";
                System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }

                FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
                clientContext.Load(files);
                clientContext.ExecuteQuery();

                if (clientContext.HasPendingRequest)
                    clientContext.ExecuteQuery();

                foreach (ClientOM.File file in files)
                {
                    FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    var filePath = tempLocation + file.Name;
                    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                    {
                        fileInfo.Stream.CopyTo(fileStream);
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

    }
}

Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.


using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;

namespace MvcApplication.Controllers
{
    public class SharepointController : MvcBoostraBaseController
    {
        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }

        public ActionResult Download(string ServerUrl, string RelativeUrl)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }
    }
}

If you need the source code of this project you can request it to [email protected]

How to part DATE and TIME from DATETIME in MySQL

Try:

SELECT DATE(`date_time_field`) AS date_part, TIME(`date_time_field`) AS time_part FROM `your_table`

Print a div content using Jquery

Print only selected element on codepen

HTML:

<div class="print">
 <p>Print 1</p>
 <a href="#" class="js-print-link">Click Me To Print</a>
</div>

<div class="print">
 <p>Print 2</p>
 <a href="#" class="js-print-link">Click Me To Print</a>
</div>

JQuery:

$('.js-print-link').on('click', function() {
  var printBlock = $(this).parents('.print').siblings('.print');
  printBlock.hide();
  window.print();
  printBlock.show();
});

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

How to Implement

It looks like iOS 8 opens up this API. Hints of such functionality are present in Beta 2.

To get something working, implement the following two methods on your UITableView's delegate to get the desired effect (see gist for an example).

- tableView:editActionsForRowAtIndexPath:
- tableView:commitEditingStyle:forRowAtIndexPath:


Known Issues

The documentation says tableView:commitEditingStyle:forRowAtIndexPath is:

"Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead."

However, the swiping doesn't work without it. Even if the method stub is blank, it still needs it, for now. This is most obviously a bug in beta 2.


Sources

https://twitter.com/marksands/status/481642991745265664 https://gist.github.com/marksands/76558707f583dbb8f870

Original Answer: https://stackoverflow.com/a/24540538/870028


Update:

Sample code with this working (In Swift): http://dropbox.com/s/0fvxosft2mq2v5m/DeleteRowExampleSwift.zip

The sample code contains this easy-to-follow method in MasterViewController.swift, and with just this method you get the behavior shown in the OP screenshot:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

    var moreRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "More", handler:{action, indexpath in
        println("MORE•ACTION");
    });
    moreRowAction.backgroundColor = UIColor(red: 0.298, green: 0.851, blue: 0.3922, alpha: 1.0);

    var deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler:{action, indexpath in
        println("DELETE•ACTION");
    });

    return [deleteRowAction, moreRowAction];
}

How does one set up the Visual Studio Code compiler/debugger to GCC?

Caution

A friendly reminder: The following tutorial is for Linux user instead of Windows

Tutorial

If you want to debug your c++ code with GDB

You can read this ( Debugging your code ) article from Visual Studio Code official website.

Step 1: Compilation

You need to set up task.json for compilation of your cpp file

or simply type in the following command in the command window

g++ -g file.cpp -o file.exe

to generate a debuggable .exe file

Step 2: Set up the launch.json file

To enable debugging, you will need to generate a launch.json file

follow the launch.json example or google others

Step 3: Press (Ctrl+F5) to start compiling

this launch.json file will launch the configuration when you press the shortcut (Ctrl+F5)

Enjoy it!

ps. For those who want to set up tasks.json, you can read this from vscode official (-> TypeScript Hello World)

Add column with constant value to pandas dataframe

The reason this puts NaN into a column is because df.index and the Index of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN wherever they aren't aligned. Play around with the reindex and align methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align() works with partially aligned indices:

In [7]: from pandas import DataFrame

In [8]: from numpy.random import randint

In [9]: df = DataFrame({'a': randint(3, size=10)})

In [10]:

In [10]: df
Out[10]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [11]: s = df.a[:5]

In [12]: dfa, sa = df.align(s, axis=0)

In [13]: dfa
Out[13]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [14]: sa
Out[14]:
0     0
1     2
2     0
3     1
4     0
5   NaN
6   NaN
7   NaN
8   NaN
9   NaN
Name: a, dtype: float64

JSON - Iterate through JSONArray

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/

How should I cast in VB.NET?

According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.

Convert String to double in Java

double d = Double.parseDouble(aString);

This should convert the string aString into the double d.

Calculate compass bearing / heading to location in Android

If you are on the same timezone

Convert GPS to UTM

http://www.ibm.com/developerworks/java/library/j-coordconvert/ http://stackoverflow.com/questions/176137/java-convert-lat-lon-to-utm

UTM coordinates get you a simples X Y 2D

Calculate the angle between both UTM locations

http://forums.groundspeak.com/GC/index.php?showtopic=146917

This gives the direction as if you were looking north

So whatever you rotate related do North just subtract this angle

If both point have a UTM 45º degree angle and you are 5º east of north, your arrow will point to 40º of north

How to close TCP and UDP ports via windows command line

I found the right answer to this one. Try TCPView from Sysinternals, now owned by Microsoft. You can find it at http://technet.microsoft.com/en-us/sysinternals/bb897437

django no such table:

You can try this!

python manage.py migrate --run-syncdb

I have the same problem with Django 1.9 and 1.10. This code works!

How many bytes does one Unicode character take?

Well I just pulled up the Wikipedia page on it too, and in the intro portion I saw "Unicode can be implemented by different character encodings. The most commonly used encodings are UTF-8 (which uses one byte for any ASCII characters, which have the same code values in both UTF-8 and ASCII encoding, and up to four bytes for other characters), the now-obsolete UCS-2 (which uses two bytes for each character but cannot encode every character in the current Unicode standard)"

As this quote demonstrates, your problem is that you are assuming Unicode is a single way of encoding characters. There are actually multiple forms of Unicode, and, again in that quote, one of them even has 1 byte per character just like what you are used to.

So your simple answer that you want is that it varies.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I have answered on this.

In my case, the problem was because of Video Downloader professional and AdBlock

In short, this problem occurs due to some google chrome plugins

Set content of iframe

Unified Solution:

In order to work on all modern browsers, you will need two steps:

  1. Add javascript:void(0); as src attribute for the iframe element. Otherwise the content will be overriden by the empty src on Firefox.

    <iframe src="javascript:void(0);"></iframe>
    
  2. Programatically change the content of the inner html element.

    $(iframeSelector).contents().find('html').html(htmlContent);
    

Credits:

Step 1 from comment (link) by @susan

Step 2 from solutions (link1, link2) by @erimerturk and @x10

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

Convert data file to blob

As pointed in the comments, file is a blob:

file instanceof Blob; // true

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

_x000D_
_x000D_
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

function readFile(event) {
  textarea.textContent = event.target.result;
  console.log(event.target.result);
}

function changeFile() {
  var file = input.files[0];
  var reader = new FileReader();
  reader.addEventListener('load', readFile);
  reader.readAsText(file);
}

input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

Execute cmd command from VBScript

Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.

Download an SVN repository?

If you have proxy i suggest using SVNGITDownloader it is under .NET Framework and its source code is available

Avoid duplicates in INSERT INTO SELECT query in SQL Server

From SQL Server you can set a Unique key index on the table for (Columns that needs to be unique)

From sql server right click on the table design select Indexes/Keys

Select column(s) that will be not duplicate , then type Unique Key

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

A saw a different post that also had diacritical marks, which is great

s.replace(/[^a-zA-Z0-9À-ž\s]/g, "")

How to toggle a boolean?

Let's see this in action:

_x000D_
_x000D_
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
_x000D_
_x000D_

Anyways, there is no shorter way than what you currently have.

how to send multiple data with $.ajax() jquery

  var value1=$("id1").val();
  var value2=$("id2").val();
    data:"{'data1':'"+value1+"','data2':'"+value2+"'}"

You can use this way to pass data

How to hide console window in python?

In linux, just run it, no problem. In Windows, you want to use the pythonw executable.

Update

Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?

  • UNIX (Linux)

$ nohup mypythonprog &

  • Windows

C:/> start pythonw mypythonprog

I think that's right. In any case, now you can close the terminal.

Cannot use object of type stdClass as array?

The function json_decode() returns an object by default.

You can access the data like this:

var_dump($result->context);

If you have identifiers like from-date (the hyphen would cause a PHP error when using the above method) you have to write:

var_dump($result->{'from-date'});

If you want an array you can do something like this:

$result = json_decode($json, true);

Or cast the object to an array:

$result = (array) json_decode($json);

"Post Image data using POSTMAN"

That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.

What you should do is;

  1. After setting request method to POST, click to the 'body' tab.
  2. Select form-data. At first line, you'll see text boxes named key and value. Write 'image' to the key. You'll see value type which is set to 'text' as default. Make it File and upload your file.
  3. Then select 'raw' and paste your json file. Also just next to the binary choice, You'll see 'Text' is clicked. Make it JSON.

form-data section

raw section

You're ready to go.

In your Django view,

from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes

@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):

    def post(self, request, format=None):
        thumbnail = request.FILES["file"]
        info = json.loads(request.data['info'])
        ...
        return HttpResponse()

Align DIV to bottom of the page

Right I think I know what you mean so lets see....

HTML:

<div id="con">
   <div id="content">Results will go here</div>
   <div id="footer">Footer will always be at the bottom</div>
</div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
div {
    outline: 1px solid;
}
#con {
   min-height:100%;
   position:relative;
}
#content {
   height: 1000px; /* Changed this height */
   padding-bottom:60px;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
}

This demo have the height of contentheight: 1000px; so you can see what it would look like scrolling down the bottom.

DEMO HERE

This demo has the height of content height: 100px; so you can see what it would look like with no scrolling.

DEMO HERE

So this will move the footer below the div content but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.

Updated fiddles so its easier to see with backgrounds.

How do I connect to my existing Git repository using Visual Studio Code?

  1. Use git clone to clone your repository into a folder (say work). You should see a new subfolder, work/.git.
  2. Open folder work in Visual Studio Code - everything should work fine!

PS: Blow away the temporary folder.

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

You can try with the following way,

 <parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>
  </parent>

So that the parent jar will be fetching from the repository.

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

Add this Annotation to Entity Class (Model) that works for me this cause lazy loading via the hibernate proxy object.

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

How do you test to see if a double is equal to NaN?

Use the static Double.isNaN(double) method, or your Double's .isNaN() method.

// 1. static method
if (Double.isNaN(doubleValue)) {
    ...
}
// 2. object's method
if (doubleObject.isNaN()) {
    ...
}

Simply doing:

if (var == Double.NaN) {
    ...
}

is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

IMHO, most arguments against recursive locks (which are what I use 99.9% of the time over like 20 years of concurrent programming) mix the question if they are good or bad with other software design issues, which are quite unrelated. To name one, the "callback" problem, which is elaborated on exhaustively and without any multithreading related point of view, for example in the book Component software - beyond Object oriented programming.

As soon as you have some inversion of control (e.g. events fired), you face re-entrance problems. Independent of whether there are mutexes and threading involved or not.

class EvilFoo {
  std::vector<std::string> data;
  std::vector<std::function<void(EvilFoo&)> > changedEventHandlers;
public:
  size_t registerChangedHandler( std::function<void(EvilFoo&)> handler) { // ...  
  }
  void unregisterChangedHandler(size_t handlerId) { // ...
  }
  void fireChangedEvent() { 
    // bad bad, even evil idea!
    for( auto& handler : changedEventHandlers ) {
      handler(*this);
    }
  }
  void AddItem(const std::string& item) { 
    data.push_back(item);
    fireChangedEvent();
  }
};

Now, with code like the above you get all error cases, which would usually be named in the context of recursive locks - only without any of them. An event handler can unregister itself once it has been called, which would lead to a bug in a naively written fireChangedEvent(). Or it could call other member functions of EvilFoo which cause all sorts of problems. The root cause is re-entrance. Worst of all, this could not even be very obvious as it could be over a whole chain of events firing events and eventually we are back at our EvilFoo (non- local).

So, re-entrance is the root problem, not the recursive lock. Now, if you felt more on the safe side using a non-recursive lock, how would such a bug manifest itself? In a deadlock whenever unexpected re-entrance occurs. And with a recursive lock? The same way, it would manifest itself in code without any locks.

So the evil part of EvilFoo are the events and how they are implemented, not so much a recursive lock. fireChangedEvent() would need to first create a copy of changedEventHandlers and use that for iteration, for starters.

Another aspect often coming into the discussion is the definition of what a lock is supposed to do in the first place:

  • Protect a piece of code from re-entrance
  • Protect a resource from being used concurrently (by multiple threads).

The way I do my concurrent programming, I have a mental model of the latter (protect a resource). This is the main reason why I am good with recursive locks. If some (member) function needs locking of a resource, it locks. If it calls another (member) function while doing what it does and that function also needs locking - it locks. And I don't need an "alternate approach", because the ref-counting of the recursive lock is quite the same as if each function wrote something like:

void EvilFoo::bar() {
   auto_lock lock(this); // this->lock_holder = this->lock_if_not_already_locked_by_same_thread())
   // do what we gotta do
   
   // ~auto_lock() { if (lock_holder) unlock() }
}

And once events or similar constructs (visitors?!) come into play, I do not hope to get all the ensuing design problems solved by some non-recursive lock.

Order data frame rows according to vector with specific order

Here's a similar system for the situation where you have a variable you want to sort by, initially, but then you want to sort by a secondary variable according to the order that this secondary variable first appears in the initial sort.

In the function below, the initial sort variable is called order_by and the secondary variable is called order_along - as in "order by this variable along its initial order".

library(dplyr, warn.conflicts = FALSE)
df <- structure(
  list(
    msoa11hclnm = c(
      "Bewbush", "Tilgate", "Felpham",
      "Selsey", "Brunswick", "Ratton", "Ore", "Polegate", "Mile Oak",
      "Upperton", "Arundel", "Kemptown"
    ),
    lad20nm = c(
      "Crawley", "Crawley",
      "Arun", "Chichester", "Brighton and Hove", "Eastbourne", "Hastings",
      "Wealden", "Brighton and Hove", "Eastbourne", "Arun", "Brighton and Hove"
    ),
    shape_area = c(
      1328821, 3089180, 3540014, 9738033, 448888, 10152663, 5517102,
      7036428, 5656430, 2653589, 72832514, 826151
    )
  ),
  row.names = c(NA, -12L), class = "data.frame"
)

this does not give me what I need:

df %>% 
  dplyr::arrange(shape_area, lad20nm)
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3      Bewbush           Crawley    1328821
#> 4     Upperton        Eastbourne    2653589
#> 5      Tilgate           Crawley    3089180
#> 6      Felpham              Arun    3540014
#> 7          Ore          Hastings    5517102
#> 8     Mile Oak Brighton and Hove    5656430
#> 9     Polegate           Wealden    7036428
#> 10      Selsey        Chichester    9738033
#> 11      Ratton        Eastbourne   10152663
#> 12     Arundel              Arun   72832514

Here’s a function:

order_along <- function(df, order_along, order_by) {
  cols <- colnames(df)
  
  df <- df %>%
    dplyr::arrange({{ order_by }})
  
  df %>% 
    dplyr::select({{ order_along }}) %>% 
    dplyr::distinct() %>% 
    dplyr::full_join(df) %>% 
    dplyr::select(dplyr::all_of(cols))
  
}

order_along(df, lad20nm, shape_area)
#> Joining, by = "lad20nm"
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3     Mile Oak Brighton and Hove    5656430
#> 4      Bewbush           Crawley    1328821
#> 5      Tilgate           Crawley    3089180
#> 6     Upperton        Eastbourne    2653589
#> 7       Ratton        Eastbourne   10152663
#> 8      Felpham              Arun    3540014
#> 9      Arundel              Arun   72832514
#> 10         Ore          Hastings    5517102
#> 11    Polegate           Wealden    7036428
#> 12      Selsey        Chichester    9738033

Created on 2021-01-12 by the reprex package (v0.3.0)

Scraping data from website using vba

you can use winhttprequest object instead of internet explorer as it's good to load data excluding pictures n advertisement instead of downloading full webpage including advertisement n pictures those make internet explorer object heavy compare to winhttpRequest object.

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

History or log of commands executed in Git

If you are using CentOS or another Linux flavour then just do Ctrl+R at the prompt and type git.

If you keep hitting Ctrl+R this will do a reverse search through your history for commands that start with git

ruby LoadError: cannot load such file

I just came across a similar problem. Try

require './st.rb'

This should do the trick.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

Class not registered Error

In 64 bit windows machines the COM components need to register itself in HKEY_CLASSES_ROOT\CLSID (64 bit component) OR HKEY_CLASSES_ROOT\Wow6432Node\CLSID (32 bit component) . If your application is a 32 bit application running on 64-bit machine the COM library would typically look for the GUID under Wow64 node and if your application is a 64 bit application, the COM library would try to load from HKEY_CLASSES_ROOT\CLSID. Make sure you are targeting the correct platform and ensure you have installed the correct version of library(32/64 bit).

How can I position my div at the bottom of its container?

Likely not.

Assign position:relative to #container, and then position:absolute; bottom:0; to #copyright.


_x000D_
_x000D_
#container {_x000D_
    position: relative;_x000D_
}_x000D_
#copyright {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
}
_x000D_
<div id="container">_x000D_
  <!-- Other elements here -->_x000D_
  <div id="copyright">_x000D_
    Copyright Foo web designs_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to urlencode a querystring in Python?

If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

The syntax is as follows :

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

How to test an SQL Update statement before running it?

One more option is to ask MySQL for the query plan. This tells you two things:

  • Whether there are any syntax errors in the query, if so the query plan command itself will fail
  • How MySQL is planning to execute the query, e.g. what indexes it will use

In MySQL and most SQL databases the query plan command is describe, so you would do:

describe update ...;