Programs & Examples On #Scriptable

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

TypeError: 'float' object is not subscriptable

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
for i,price in enumerate(PriceList):
  PriceList[i] = PizzaChange + 3*int(i>=7)

'NoneType' object is not subscriptable?

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]

def printer(*lists):
    for _list in lists:
        for ele in _list:
            print(ele, end = ", ")
        print()

printer(list1, list2, list3)

Iterate over object attributes in python

in general put a __iter__ method in your class and iterate through the object attributes or put this mixin class in your class.

class IterMixin(object):
    def __iter__(self):
        for attr, value in self.__dict__.iteritems():
            yield attr, value

Your class:

>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}

How to generate entire DDL of an Oracle schema (scriptable)?

The get_ddl procedure for a PACKAGE will return both spec AND body, so it will be better to change the query on the all_objects so the package bodies are not returned on the select.

So far I changed the query to this:

SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type, ' ', '_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1')
and object_type not like '%PARTITION'
and object_type not like '%BODY'
order by object_type, object_name;

Although other changes might be needed depending on the object types you are getting...

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

TypeError: 'int' object is not subscriptable

Try this instead:

sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln

sumall is a number, and you can't access its digits using the subscript notation (sumall[0], sumall[1]). For that to work, you'll need to transform it back to a string.

TypeError: 'builtin_function_or_method' object is not subscriptable

This error arises when you don't use brackets with pop operation. Write the code in this manner.

listb.pop(0)

This is a valid python expression.

Error: 'int' object is not subscriptable - Python

You need to convert age1 into int first, so it can do the minus. After that turn the result back to string for display:

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
twentyone = str(21 - int(age1))
print "Hi, " + name1+ " you will be 21 in: " + twentyone + " years."

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

How to properly use unit-testing's assertRaises() with NoneType objects?

Complete snippet would look like the following. It expands @mouad's answer to asserting on error's message (or generally str representation of its args), which may be useful.

from unittest import TestCase


class TestNoneTypeError(TestCase):

  def setUp(self): 
    self.testListNone = None

  def testListSlicing(self):
    with self.assertRaises(TypeError) as ctx:
        self.testListNone[:1]
    self.assertEqual("'NoneType' object is not subscriptable", str(ctx.exception))

What Java FTP client library should I use?

You have also this 2006 article which lists different options for FTP clients.

commons-net is good, but FTP-GO can give you some of the more advanced features you are looking for.

kagi Ftp-Go

What does it mean if a Python object is "subscriptable" or not?

The meaning of subscript in computing is: "a symbol (notionally written as a subscript but in practice usually not) used in a program, alone or with others, to specify one of the elements of an array."

Now, in the simple example given by @user2194711 we can see that the appending element is not able to be a part of the list because of two reasons:-

1) We are not really calling the method append; because it needs () to call it.

2) The error is indicating that the function or method is not subscriptable; means they are not indexable like a list or sequence.

Now see this:-

>>> var = "myString"
>>> def foo(): return 0
... 
>>> var[3]
't'
>>> foo[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

That means there are no subscripts or say elements in function like they occur in sequences; and we cannot access them like we do, with the help of [].

Also; as mipadi said in his answer; It basically means that the object implements the __getitem__() method. (if it is subscriptable). Thus the error produced:

arr.append["HI"]

TypeError: 'builtin_function_or_method' object is not subscriptable

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.

In versions pre-G++ 4.7, you'll have to use -std=c++0x, for more recent versions you can use -std=c++11.

how to remove "," from a string in javascript

You aren't assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

<html><head></head><body>
    <script type="text/javascript">
        var str1 = "a,d,k";
        str1.replace(/\,/g,"");
        var str2 = str1.replace(/\,/g,"");
        alert (str1);
        alert (str2);
    </script>
</body></html>

In this case, str1 will still be "a,d,k" and str2 will be "adk".

If you want to change str1, you should be doing:

var str1 = "a,d,k";
str1 = str1.replace (/,/g, "");

Close pre-existing figures in matplotlib when running from eclipse

It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.

import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then  kill -9 "$x"; fi done'])

How can I show a combobox in Android?

Here is an example of custom combobox in android:

package myWidgets;
import android.content.Context;
import android.database.Cursor;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;

public class ComboBox extends LinearLayout {

   private AutoCompleteTextView _text;
   private ImageButton _button;

   public ComboBox(Context context) {
       super(context);
       this.createChildControls(context);
   }

   public ComboBox(Context context, AttributeSet attrs) {
       super(context, attrs);
       this.createChildControls(context);
}

 private void createChildControls(Context context) {
    this.setOrientation(HORIZONTAL);
    this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                   LayoutParams.WRAP_CONTENT));

   _text = new AutoCompleteTextView(context);
   _text.setSingleLine();
   _text.setInputType(InputType.TYPE_CLASS_TEXT
                   | InputType.TYPE_TEXT_VARIATION_NORMAL
                   | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                   | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE
                   | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
   _text.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
   this.addView(_text, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT, 1));

   _button = new ImageButton(context);
   _button.setImageResource(android.R.drawable.arrow_down_float);
   _button.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {
                   _text.showDropDown();
           }
   });
   this.addView(_button, new LayoutParams(LayoutParams.WRAP_CONTENT,
                   LayoutParams.WRAP_CONTENT));
 }

/**
    * Sets the source for DDLB suggestions.
    * Cursor MUST be managed by supplier!!
    * @param source Source of suggestions.
    * @param column Which column from source to show.
    */
 public void setSuggestionSource(Cursor source, String column) {
    String[] from = new String[] { column };
    int[] to = new int[] { android.R.id.text1 };
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this.getContext(),
                   android.R.layout.simple_dropdown_item_1line, source, from, to);
    // this is to ensure that when suggestion is selected
    // it provides the value to the textbox
    cursorAdapter.setStringConversionColumn(source.getColumnIndex(column));
    _text.setAdapter(cursorAdapter);
 }

/**
    * Gets the text in the combo box.
    *
    * @return Text.
    */
public String getText() {
    return _text.getText().toString();
 }

/**
    * Sets the text in combo box.
    */
public void setText(String text) {
    _text.setText(text);
   }
}

Hope it helps!!

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

Using a Loop to add objects to a list(python)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

If you use MVC, tables, it works like this:

<td>@(((DateTime)detalle.fec).ToString("dd'/'MM'/'yyyy"))</td>

Else clause on Python while statement

The else-clause is executed when the while-condition evaluates to false.

From the documentation:

The while statement is used for repeated execution as long as an expression is true:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Are the shift operators (<<, >>) arithmetic or logical in C?

will typically use logical shifts on unsigned variables and for left-shifts on signed variables. The arithmetic right shift is the truly important one because it will sign extend the variable.

will will use this when applicable, as other compilers are likely to do.

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

'React' must be in scope when using JSX react/react-in-jsx-scope?

For those who still don't get the accepted solution :

Add

import React from 'react'
import ReactDOM from 'react-dom'

at the top of the file.

Open page in new window without popup blocking

As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)

Try launching after a click event

Typescript sleep

If you are using angular5 and above, please include the below method in your ts file.

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

then call this delay() method wherever you want.

e.g:

validateInputValues() {
    if (null == this.id|| this.id== "") {
        this.messageService.add(
            {severity: 'error', summary: 'ID is Required.'});
        this.delay(3000).then(any => {
            this.messageService.clear();
        });
    }
}

This will disappear message growl after 3 seconds.

Gson: How to exclude specific fields from Serialization without annotations

Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:

Gson gson = new GsonBuilder()
.registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())

In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.

public class BloodPressurePostSerializer implements JsonSerializer<BloodPressurePost> {

    @Override
    public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
        final JsonObject jsonObject = new JsonObject();

        if (src.systolic > 0) {
            jsonObject.addProperty("systolic", src.systolic);
        }

        if (src.diastolic > 0) {
            jsonObject.addProperty("diastolic", src.diastolic);
        }

        jsonObject.addProperty("units", src.units);

        return jsonObject;
    }
}

Stylesheet not loaded because of MIME-type

You must have imported multiple stylesheets. try to remove one and try again

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Matching strings with wildcard

It is necessary to take into consideration, that Regex IsMatch gives true with XYZ, when checking match with Y*. To avoid it, I use "^" anchor

isMatch(str1, "^" + str2.Replace("*", ".*?"));  

So, full code to solve your problem is

    bool isMatchStr(string str1, string str2)
    {
        string s1 = str1.Replace("*", ".*?");
        string s2 = str2.Replace("*", ".*?");
        bool r1 = Regex.IsMatch(s1, "^" + s2);
        bool r2 = Regex.IsMatch(s2, "^" + s1);
        return r1 || r2;
    }

What causes "Unable to access jarfile" error?

Fixed

I just placed it in a different folder and it worked.

How to import a class from default package

Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.

In PowerShell, how do I test whether or not a specific variable exists in global scope?

$myvar = if ($env:variable) { $env:variable } else { "default_value" } 

How to Multi-thread an Operation Within a Loop in Python

First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.

This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.


Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing and concurrent.futures libraries both wraps up most of the details for you.

The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures, 4 lines with multiprocessing.)

If you're using 2.6-2.7 or 3.0-3.1, futures isn't built in, but you can install it from PyPI (pip install futures).


Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map), so let's do that first:

def try_my_operation(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

Putting it all together:

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)

If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper from the itertools recipes, which you can copy and paste into your code, or get from the more-itertools project on PyPI):

def try_multiple_operations(items):
    for item in items:
        try:
            api.my_operation(item)
        except:
            print('error with item')

executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group) 
           for group in grouper(5, items)]
concurrent.futures.wait(futures)

Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.

So, how do you use threads instead of processes? Just change ProcessPoolExecutor to ThreadPoolExecutor.

If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.


Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?

Yes. In fact, there are two different ways to do it.

First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.

Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.

If you don't know which is appropriate for your program, usually it's the first.

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

Yes, __attribute__((packed)) is potentially unsafe on some systems. The symptom probably won't show up on an x86, which just makes the problem more insidious; testing on x86 systems won't reveal the problem. (On the x86, misaligned accesses are handled in hardware; if you dereference an int* pointer that points to an odd address, it will be a little slower than if it were properly aligned, but you'll get the correct result.)

On some other systems, such as SPARC, attempting to access a misaligned int object causes a bus error, crashing the program.

There have also been systems where a misaligned access quietly ignores the low-order bits of the address, causing it to access the wrong chunk of memory.

Consider the following program:

#include <stdio.h>
#include <stddef.h>
int main(void)
{
    struct foo {
        char c;
        int x;
    } __attribute__((packed));
    struct foo arr[2] = { { 'a', 10 }, {'b', 20 } };
    int *p0 = &arr[0].x;
    int *p1 = &arr[1].x;
    printf("sizeof(struct foo)      = %d\n", (int)sizeof(struct foo));
    printf("offsetof(struct foo, c) = %d\n", (int)offsetof(struct foo, c));
    printf("offsetof(struct foo, x) = %d\n", (int)offsetof(struct foo, x));
    printf("arr[0].x = %d\n", arr[0].x);
    printf("arr[1].x = %d\n", arr[1].x);
    printf("p0 = %p\n", (void*)p0);
    printf("p1 = %p\n", (void*)p1);
    printf("*p0 = %d\n", *p0);
    printf("*p1 = %d\n", *p1);
    return 0;
}

On x86 Ubuntu with gcc 4.5.2, it produces the following output:

sizeof(struct foo)      = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = 0xbffc104f
p1 = 0xbffc1054
*p0 = 10
*p1 = 20

On SPARC Solaris 9 with gcc 4.5.1, it produces the following:

sizeof(struct foo)      = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = ffbff317
p1 = ffbff31c
Bus error

In both cases, the program is compiled with no extra options, just gcc packed.c -o packed.

(A program that uses a single struct rather than array doesn't reliably exhibit the problem, since the compiler can allocate the struct on an odd address so the x member is properly aligned. With an array of two struct foo objects, at least one or the other will have a misaligned x member.)

(In this case, p0 points to a misaligned address, because it points to a packed int member following a char member. p1 happens to be correctly aligned, since it points to the same member in the second element of the array, so there are two char objects preceding it -- and on SPARC Solaris the array arr appears to be allocated at an address that is even, but not a multiple of 4.)

When referring to the member x of a struct foo by name, the compiler knows that x is potentially misaligned, and will generate additional code to access it correctly.

Once the address of arr[0].x or arr[1].x has been stored in a pointer object, neither the compiler nor the running program knows that it points to a misaligned int object. It just assumes that it's properly aligned, resulting (on some systems) in a bus error or similar other failure.

Fixing this in gcc would, I believe, be impractical. A general solution would require, for each attempt to dereference a pointer to any type with non-trivial alignment requirements either (a) proving at compile time that the pointer doesn't point to a misaligned member of a packed struct, or (b) generating bulkier and slower code that can handle either aligned or misaligned objects.

I've submitted a gcc bug report. As I said, I don't believe it's practical to fix it, but the documentation should mention it (it currently doesn't).

UPDATE: As of 2018-12-20, this bug is marked as FIXED. The patch will appear in gcc 9 with the addition of a new -Waddress-of-packed-member option, enabled by default.

When address of packed member of struct or union is taken, it may result in an unaligned pointer value. This patch adds -Waddress-of-packed-member to check alignment at pointer assignment and warn unaligned address as well as unaligned pointer

I've just built that version of gcc from source. For the above program, it produces these diagnostics:

c.c: In function ‘main’:
c.c:10:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   10 |     int *p0 = &arr[0].x;
      |               ^~~~~~~~~
c.c:11:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   11 |     int *p1 = &arr[1].x;
      |               ^~~~~~~~~

How do I conditionally apply CSS styles in AngularJS?

Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:

  • ng-class - use when the set of CSS styles is static/known ahead of time
  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)
  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)
  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)
  • ng-disabled and ng-readonly - use to restrict form element behavior
  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations

The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.

When the user changes the UI, Angular will automatically update the associated elements on the page.


Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class.

ng-class accepts an "expression" that must evaluate to one of the following:

  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values

Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:

<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
   ... HTML to display the item ...
   <input type="checkbox" ng-model="item.checked">
</div>

Above, we used ng-class expression type #3 - a map/object of class names to boolean values.


Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this.

ng-style accepts an "expression" that must evaluate to:

  1. an map/object of CSS style names to CSS values

For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):

<div class="main-body" ng-style="{color: myColor}">
   ...
   <input type="text" ng-model="myColor" placeholder="enter a color name">


Fiddle for both of the above.

The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.

How do I convert seconds to hours, minutes and seconds?

I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

or if you don't want anything fancy like animation etc. you can create a label and dock it to form then change it's z-index from document outline window to 0 and give it a background color so other controls wont be visible than run Application.DoEvents() once in form load event and do all your coding in form shown event and at the and of shown event set your label visible property to false then run Application.DoEvents() again.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

smtpclient " failure sending mail"

apparently this problem got solved just by increasing queue size on my 3rd party smtp server. but the answer by Nip sounds like it is fairly usefull too

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).

RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.

WebView : to load html, static or dynamic pages.

For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html

Passing command line arguments to R CMD BATCH

In your R script, called test.R:

args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")

From the command line run:

R CMD BATCH -4 test.R

Your output file, test.Rout, will show that the argument 4 has been successfully passed to R:

cat test.Rout

> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user  system elapsed 
0.222   0.022   0.236 

Android Studio: Application Installation Failed

For me it only started working after I rebooted device (Motorola-Nexus-6).

(I also tried to clean, disable "instant run", reopen Android Studio, verified installed applications to be sure there are no clashes, disable and reenable Debug mode in phone, reconnect USB cable)

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

As an option, you can use a type casting. If you have this error from typescript that means that some variable has type or is undefined:

let a: string[] | undefined;

let b: number = a.length; // [ts] Object is possibly 'undefined'
let c: number = (a as string[]).length; // ok

Be sure that a really exist in your code.

SQL Server ORDER BY date and nulls last

I know this is old but this is what worked for me

Order by Isnull(Date,'12/31/9999')

How to update gradle in android studio?

after release of android studio v 3.0(stable), It will show popup, If gradle update is available

OR

Manually, just change version of gradle in top-level(project-level) build.gradle file to latest,

   buildscript {
      ...
      dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
      }
    }

check below chart

The Android Gradle Plugin and Gradle

 Android Gradle Plugin            Requires Gradle
 1.0.0 - 1.1.3                    2.2.1 - 2.3
 1.2.0 - 1.3.1                    2.2.1 - 2.9
 1.5.0   2.2.1+                   2.2.1 - 2.13
 2.0.0 - 2.1.2                    2.10  - 2.13
 2.1.3 - 2.2.3                    2.14.1+
 2.3.0+                           3.3+
 3.0.0+                           4.1+    
 3.1.0+                           4.4+    
 3.2.0 - 3.2.1                    4.6+    
 3.3.0 - 3.3.1                    4.10.1+ 
 3.4.0 - 3.4.1                    5.1.1+
 3.5.0                            5.4.1+

check gradle revisions

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

<a href="page.html" onclick="return false" style="cursor:default;">page link</a>

Importing a long list of constants to a Python file

Python isn't preprocessed. You can just create a file myconstants.py:

MY_CONSTANT = 50

And importing them will just work:

import myconstants
print myconstants.MY_CONSTANT * 2

Is there a destructor for Java?

No, java.lang.Object#finalize is the closest you can get.

However, when (and if) it is called, is not guaranteed.
See: java.lang.Runtime#runFinalizersOnExit(boolean)

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

It's probably because your SSH key has been removed/revoked. Make a new one and add it to your GitHub account.

Performing Inserts and Updates with Dapper

Performing CRUD operations using Dapper is an easy task. I have mentioned the below examples that should help you in CRUD operations.

Code for CRUD:

Method #1: This method is used when you are inserting values from different entities.

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";

    var result = db.Execute(insertQuery, new
    {
        customerModel.FirstName,
        customerModel.LastName,
        StateModel.State,
        CityModel.City,
        isActive,
        CreatedOn = DateTime.Now
    });
}

Method #2: This method is used when your entity properties have the same names as the SQL columns. So, Dapper being an ORM maps entity properties with the matching SQL columns.

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";

    var result = db.Execute(insertQuery, customerViewModel);
}

Code for CRUD:

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string selectQuery = @"SELECT * FROM [dbo].[Customer] WHERE FirstName = @FirstName";

    var result = db.Query(selectQuery, new
    {
        customerModel.FirstName
    });
}

Code for CRUD:

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string updateQuery = @"UPDATE [dbo].[Customer] SET IsActive = @IsActive WHERE FirstName = @FirstName AND LastName = @LastName";

    var result = db.Execute(updateQuery, new
    {
        isActive,
        customerModel.FirstName,
        customerModel.LastName
    });
}

Code for CRUD:

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string deleteQuery = @"DELETE FROM [dbo].[Customer] WHERE FirstName = @FirstName AND LastName = @LastName";

    var result = db.Execute(deleteQuery, new
    {
        customerModel.FirstName,
        customerModel.LastName
    });
}

jackson deserialization json to java-objects

 JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"

 System.out.println("id : "+node.findValues("id").get(0).asText());

this also done the trick.

how to iterate through dictionary in a dictionary in django template?

Lets say your data is -

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Am pretty sure you can extend this logic to your specific dict.


To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

Play an audio file using jQuery when a button is clicked

For anyone else following along, I've simply taken Ahmet's answer and updated the original asker's jsfiddle here, substituting:

audio.mp3

for

http://www.uscis.gov/files/nativedocuments/Track%2093.mp3

linking in a freely available mp3 off the web. Thank you for sharing the easy solution!

Mockito: Trying to spy on method is calling the original method

Let me quote the official documentation:

Important gotcha on spying real objects!

Sometimes it's impossible to use when(Object) for stubbing spies. Example:

List list = new LinkedList();
List spy = spy(list);

// Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");

// You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

In your case it goes something like:

doReturn(resultsIWant).when(myClassSpy).method1();

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

It might help somebody.

I had the similar error message, but only in dev and staging environments, not in production. The valid redirect URIs were correctly set, for the dev and staging subdomains as well as for production.

It turned out I forgot that for those environments we use the testing FB app, which is a separate one in the FB developer page. Had to select that and update its settings.

how to parse JSONArray in android

getJSONArray(attrname) will get you an array from the object of that given attribute name in your case what is happening is that for

{"abridged_cast":["name": blah...]}
^ its trying to search for a value "characters"

but you need to get into the array and then do a search for "characters"

try this

String json="{'abridged_cast':[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},{'name':'JessicaLange','id':'162653068','characters':['Dwan']},{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";

    JSONObject jsonResponse;
    try {
        ArrayList<String> temp = new ArrayList<String>();
        jsonResponse = new JSONObject(json);
        JSONArray movies = jsonResponse.getJSONArray("abridged_cast");
        for(int i=0;i<movies.length();i++){
            JSONObject movie = movies.getJSONObject(i);
            JSONArray characters = movie.getJSONArray("characters");
            for(int j=0;j<characters.length();j++){
                temp.add(characters.getString(j));
            }
        }
        Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

checked it :)

Can't perform a React state update on an unmounted component

Inspired by @ford04 answer I use this hook, which also takes callbacks for success, errors, finally and an abortFn:

export const useAsync = (
        asyncFn, 
        onSuccess = false, 
        onError = false, 
        onFinally = false, 
        abortFn = false
    ) => {

    useEffect(() => {
        let isMounted = true;
        const run = async () => {
            try{
                let data = await asyncFn()
                if (isMounted && onSuccess) onSuccess(data)
            } catch(error) {
                if (isMounted && onError) onSuccess(error)
            } finally {
                if (isMounted && onFinally) onFinally()
            }
        }
        run()
        return () => {
            if(abortFn) abortFn()
            isMounted = false
        };
    }, [asyncFn, onSuccess])
}

If the asyncFn is doing some kind of fetch from back-end it often makes sense to abort it when the component is unmounted (not always though, sometimes if ie. you're loading some data into a store you might as well just want to finish it even if component is unmounted)

Find element's index in pandas Series

In [92]: (myseries==7).argmax()
Out[92]: 3

This works if you know 7 is there in advance. You can check this with (myseries==7).any()

Another approach (very similar to the first answer) that also accounts for multiple 7's (or none) is

In [122]: myseries = pd.Series([1,7,0,7,5], index=['a','b','c','d','e'])
In [123]: list(myseries[myseries==7].index)
Out[123]: ['b', 'd']

Entity Framework 5 Updating a Record

foreach(PropertyInfo propertyInfo in original.GetType().GetProperties()) {
    if (propertyInfo.GetValue(updatedUser, null) == null)
        propertyInfo.SetValue(updatedUser, propertyInfo.GetValue(original, null), null);
}
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();

SQL string value spanning multiple lines in query

with your VARCHAR, you may also need to specify the length, or its usually good to

What about grabbing the text, making a sting of it, then putting it into the query witrh

String TableName = "ComplicatedTableNameHere";  
EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere); 
String editTextString1 = editText1.getText().toString();  

BROKEN DOWN

String TableName = "ComplicatedTableNameHere";            
    //sets the table name as a string so you can refer to TableName instead of writing out your table name everytime

EditText editText1 = (EditText) findViewById(R.id.EditTextIDhere); 
    //gets the text from your edit text fieldfield 
    //editText1 = your edit text name
    //EditTextIDhere = the id of your text field

String editTextString1 = editText1.getText().toString();  
    //sets the edit text as a string
    //editText1 is the name of the Edit text from the (EditText) we defined above
    //editTextString1 = the string name you will refer to in future

then use

       /* Insert data to a Table*/
       myDB.execSQL("INSERT INTO "
         + TableName
         + " (Column_Name, Column_Name2, Column_Name3, Column_Name4)"
         + " VALUES ( "+EditTextString1+", 'Column_Value2','Column_Value3','Column_Value4');");

Hope this helps some what...

NOTE each string is within

'"+stringname+"'

its the 'and' that enable the multi line element of the srting, without it you just get the first line, not even sure if you get the whole line, it may just be the first word

Is there an alternative to string.Replace that is case-insensitive?

Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:

string res = Microsoft.VisualBasic.Strings.Replace(res, 
                                   "%PolicyAmount%", 
                                   "$0", 
                                   Compare: Microsoft.VisualBasic.CompareMethod.Text);

In order to use this method, you have to add a Reference to the Microsoft.VisualBasic assemblly. This assembly is a standard part of the .Net runtime, it is not an extra download or marked as obsolete.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;
}

Pandas DataFrame: replace all values in a column, based on condition

df['First Season'].loc[(df['First Season'] > 1990)] = 1

strange that nobody has this answer, the only missing part of your code is the ['First Season'] right after df and just remove your curly brackets inside.

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just want to add another way of doing this. I've seen multiple people on various related threads ask if you can use VerifyRenderingInServerForm without adding it to the parent page.

You actually can do this but it's a bit of a bodge.

First off create a new Page class which looks something like the following:

public partial class NoRenderPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Allows for printing
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /*Do nothing*/ }
    }
}

Does not need to have an .ASPX associated with it.

Then in the control you wish to render you can do something like the following.

    StringWriter tw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    var page = new NoRenderPage();
    page.DesignerInitialize();
    var form = new HtmlForm();
    page.Controls.Add(form);
    form.Controls.Add(pnl);
    controlToRender.RenderControl(hw);

Now you've got your original control rendered as HTML. If you need to, add the control back into it's original position. You now have the HTML rendered, the page as normal and no changes to the page itself.

What are DDL and DML?

DDL is Data Definition Language: Just think you are defining the DB. So we use CREATE,ALTER TRUNCATE commands.
DML is after defining we are Manipulating the data. So we use SELECT,INSERT, UPDATE, DELETE command.

Remember DDL commands are auto-committed. You don't need to use COMMIT statements.
DML (Data Manipulation Language) commands need to be commited/rolled back.

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

Will #if RELEASE work like #if DEBUG does in C#?

Nope.

While in debug configuration there is a DEBUG defined constant (automatically defined by Visual Studio) while there is no such constant defined for release mode. Check your project settings under build.

Selecting [Define DEBUG constant] under Project -> Build is like including #define DEBUG at the beginning of every file.

If you want to define a RELEASE constant for the release configuration go to:

  • Project Properties -> Build
  • Select Release Mode
  • in the Conditional compilation symbols textbox enter: RELEASE

Change navbar text color Bootstrap

Try this in your css:

#ntext{
 color: #000000;
  }

Then the following in all your navigation bar list codes:

<li><a href="#" id="ntext"><span class="glyphicon glyphicon-user"></span> About</a></li>

Android - R cannot be resolved to a variable

Are you targeting the android.R or the one in your own project?

Are you sure your own R.java file is generated? Mistakes in your xml views could cause the R.java not to be generated. Go through your view files and make sure all the xml is right!

cartesian product in pandas

As an alternative, one can rely on the cartesian product provided by itertools: itertools.product, which avoids creating a temporary key or modifying the index:

import numpy as np 
import pandas as pd 
import itertools

def cartesian(df1, df2):
    rows = itertools.product(df1.iterrows(), df2.iterrows())

    df = pd.DataFrame(left.append(right) for (_, left), (_, right) in rows)
    return df.reset_index(drop=True)

Quick test:

In [46]: a = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])

In [47]: b = pd.DataFrame(np.random.rand(5, 3), columns=["d", "e", "f"])    

In [48]: cartesian(a,b)
Out[48]:
           a         b         c         d         e         f
0   0.436480  0.068491  0.260292  0.991311  0.064167  0.715142
1   0.436480  0.068491  0.260292  0.101777  0.840464  0.760616
2   0.436480  0.068491  0.260292  0.655391  0.289537  0.391893
3   0.436480  0.068491  0.260292  0.383729  0.061811  0.773627
4   0.436480  0.068491  0.260292  0.575711  0.995151  0.804567
5   0.469578  0.052932  0.633394  0.991311  0.064167  0.715142
6   0.469578  0.052932  0.633394  0.101777  0.840464  0.760616
7   0.469578  0.052932  0.633394  0.655391  0.289537  0.391893
8   0.469578  0.052932  0.633394  0.383729  0.061811  0.773627
9   0.469578  0.052932  0.633394  0.575711  0.995151  0.804567
10  0.466813  0.224062  0.218994  0.991311  0.064167  0.715142
11  0.466813  0.224062  0.218994  0.101777  0.840464  0.760616
12  0.466813  0.224062  0.218994  0.655391  0.289537  0.391893
13  0.466813  0.224062  0.218994  0.383729  0.061811  0.773627
14  0.466813  0.224062  0.218994  0.575711  0.995151  0.804567
15  0.831365  0.273890  0.130410  0.991311  0.064167  0.715142
16  0.831365  0.273890  0.130410  0.101777  0.840464  0.760616
17  0.831365  0.273890  0.130410  0.655391  0.289537  0.391893
18  0.831365  0.273890  0.130410  0.383729  0.061811  0.773627
19  0.831365  0.273890  0.130410  0.575711  0.995151  0.804567
20  0.447640  0.848283  0.627224  0.991311  0.064167  0.715142
21  0.447640  0.848283  0.627224  0.101777  0.840464  0.760616
22  0.447640  0.848283  0.627224  0.655391  0.289537  0.391893
23  0.447640  0.848283  0.627224  0.383729  0.061811  0.773627
24  0.447640  0.848283  0.627224  0.575711  0.995151  0.804567

How to normalize a vector in MATLAB efficiently? Any related built-in function?

Fastest by far (time is in comparison to Jacobs):

clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; 
for i=1:N, 
    d = 1/sqrt(V(1)*V(1)+V(2)*V(2)+V(3)*V(3)); 
    V1 = V*d;
end; 
toc % 1.5s

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Thank you to all the commenters on this page. When I first installed the latest TortoiseSVN I got this error.

I was using the latest version, so decided to downgrade to 1.5.9 (as the rest of my colleagues were using) and this got it to work. Then, once built, my machine was moved onto another subnet and the problem started again.

I went to TortoiseSVN->Settings->Saved Data and cleared the Authentication data. After this it worked fine.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

However, numbering starts at 1, so:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)

Also, if you have multiple axes on a figure, such as subplots, use the axes(h) command where h is the handle of the desired axes object to focus on that axes.

(don't have comment privileges yet, sorry for new answer!)

Quicksort: Choosing the pivot

Ideally the pivot should be the middle value in the entire array. This will reduce the chances of getting worst case performance.

How does the "view" method work in PyTorch?

What is the meaning of parameter -1?

You can read -1 as dynamic number of parameters or "anything". Because of that there can be only one parameter -1 in view().

If you ask x.view(-1,1) this will output tensor shape [anything, 1] depending on the number of elements in x. For example:

import torch
x = torch.tensor([1, 2, 3, 4])
print(x,x.shape)
print("...")
print(x.view(-1,1), x.view(-1,1).shape)
print(x.view(1,-1), x.view(1,-1).shape)

Will output:

tensor([1, 2, 3, 4]) torch.Size([4])
...
tensor([[1],
        [2],
        [3],
        [4]]) torch.Size([4, 1])
tensor([[1, 2, 3, 4]]) torch.Size([1, 4])

How do you pull first 100 characters of a string in PHP

$x = '1234567';

echo substr ($x, 0, 3);  // outputs 123

echo substr ($x, 1, 1);  // outputs 2

echo substr ($x, -2);    // outputs 67

echo substr ($x, 1);     // outputs 234567

echo substr ($x, -2, 1); // outputs 6

Convert string to JSON array

Try this piece of code:

try {        
    Log.e("log_tag", "Error in convert String" + result.toString());
    JSONObject json_data = new JSONObject(result);

    String status = json_data.getString("Status");
    {
        String data = json_data.getString("locations");
        JSONArray json_data1 = new JSONArray(data);
        for (int i = 0; i < json_data1.length(); i++) {
            json_data = json_data1.getJSONObject(i);

            String lat = json_data.getString("lat");
            String lng = json_data.getString("long");
        }
    }
}

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

PHP function to get the subdomain of a URL

I'm doing something like this

$url = https://en.example.com

$splitedBySlash = explode('/', $url);
$splitedByDot = explode('.', $splitedBySlash[2]);

$subdomain = $splitedByDot[0];

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

How do I add a delay in a JavaScript loop?

   let counter =1;
   for(let item in items) {
        counter++;
        setTimeout(()=>{
          //your code
        },counter*5000); //5Sec delay between each iteration
    }

phonegap open link in browser

I also faced the issue that link was not opening on browser here is my fix with steps:

1: Install this cordova plugin.

cordova plugin add cordova-plugin-inappbrowser

2: add the open link in the html like following.

<a href="#" onclick="window.open('https://www.google.com/', '_system', 'location=yes');" >Google</a>

3: this is the most importaint step due to this I faced lots of issue: download the cordova.js file and paste it in the www folder. Then make a reference of this in the index.html file.

<script src="cordova.js"></script>

This solution will work for both the environment android and iPhone.

An efficient compression algorithm for short text strings

I don't have code to hand, but I always liked the approach of building a 2D lookup table of size 256 * 256 chars (RFC 1978, PPP Predictor Compression Protocol). To compress a string you loop over each char and use the lookup table to get the 'predicted' next char using the current and previous char as indexes into the table. If there is a match you write a single 1 bit, otherwise write a 0, the char and update the lookup table with the current char. This approach basically maintains a dynamic (and crude) lookup table of the most probable next character in the data stream.

You can start with a zeroed lookup table, but obviosuly it works best on very short strings if it is initialised with the most likely character for each character pair, for example, for the English language. So long as the initial lookup table is the same for compression and decompression you don't need to emit it into the compressed data.

This algorithm doesn't give a brilliant compression ratio, but it is incredibly frugal with memory and CPU resources and can also work on a continuous stream of data - the decompressor maintains its own copy of the lookup table as it decompresses, thus the lookup table adjusts to the type of data being compressed.

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Main advantage of <jsp:include /> over <%@ include > is:

<jsp:include /> allows to pass parameters

<jsp:include page="inclusion.jsp">
    <jsp:param name="menu" value="objectValue"/>
</jsp:include>

which is not possible in <%@include file="somefile.jsp" %>

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Maybe you should reset frame of the button, I had some problem too, and nslog the view of keyboard like this:

ios8:

"<UIInputSetContainerView: 0x7fef0364b0d0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7fef0364b1e0>>"

before8:

"<UIPeripheralHostView: 0x11393c860; frame = (0 352; 320 216); autoresizesSubviews = NO; layer = <CALayer: 0x11393ca10>>"

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

My experience:

  var text = $('#myInputField');  
  var myObj = {title: 'Some title', content: text};  
  $.post(myUrl, myObj, callback);

The problem is that I forgot to add .val() to the end of $('#myInputField'); this action makes me waste time trying to figure out what was wrong, causing Illegal Invocation Error, since $('#myInputField') was in a different file than that system pointed out incorrect code. Hope this answer help fellows in the same mistake to avoid to loose time.

Is there a "do ... while" loop in Ruby?

This works correctly now:

begin
    # statment
end until <condition>

But, it may be remove in the future, because the begin statement is counterintuitive. See: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745

Matz (Ruby’s Creator) recommended doing it this way:

loop do
    # ...
    break if <condition>
end

Android WebView Cookie Problem

I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").

Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment {
    private static final String BLANK_PAGE = "/blank.html"

    private CookieSyncManager mSyncManager;
    private CookieManager mCookieManager;

    private String mTargetUrl;
    private boolean mInitializedCookies;
    private List<Cookie> mAllCookies;

    public WebViewFragment(Context ctx) {
        // We are still required to create an instance of Cookie/SyncManager.
        mSyncManager = CookieSyncManager.createInstance(ctx);
        mCookieManager = CookieManager.getInstance();
    }

    @SuppressLint("SetJavaScriptEnabled") public void loadWebView(
                String url, List<Cookie> cookies, String domain) {
        final WebView webView = ...

        webView.setWebViewClient(new CookeWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        mInitializedCookies = false;
        mTargetUrl = url;
        mAllCookies = cookies;
        // This is where the hack starts.
        // Instead of loading the url, we load a blank page.
        webView.loadUrl("http://" + domain + BLANK_PAGE);
    }

    public static String buildCookieString(final Cookie cookie) {
        // You may want to add the secure flag for https:
        // + "; secure"
        // In case you wish to convert session cookies to have an expiration:
        // + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
        // Note that you cannot set the HttpOnly flag as we are using
        // javascript to set the cookies.
        return cookie.getName() + "=" + cookie.getValue()
                    + "; path=" + cookie.getPath()
                    + "; domain=" + cookie.getDomain()
    };

    public synchronized String generateCookieJavascript() {
        StringBuilder javascriptCode = new StringBuilder();
        javascriptCode.append("javascript:(function(){");
        for (final Cookie cookie : mAllCookies) {
            String cookieString = buildCookieString(cookie);
            javascriptCode.append("document.cookie=\"");
            javascriptCode.append(
                     StringEscapeUtils.escapeJavascriptString(cookieString));
            javascriptCode.append("\";");
        }
        // We use javascript to load the next url because we do not
        // receive an onPageFinished event when this code finishes.
        javascriptCode.append("document.location=\"");
        javascriptCode.append(
                StringEscapeUtils.escapeJavascriptString(mTargetUrl));
        javascriptCode.append("\";})();");
        return javascriptCode.toString();
    }

    private class CookieWebViewClient extends WebViewClient {
        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!mInitializedCookies) {
                mInitializedCookies = true;
                // Run our javascript code now that the temp page is loaded.
                view.loadUrl(generateCookieJavascript());
                return;
            }
        }
    }
}

If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In my case this error was specific to the hello-world docker image. I used the nginx image instead of the hello-world image and the error was resolved.

When to throw an exception?

The exceptions versus returning error code argument should be about flow control not philosophy (how "exceptional" an error is):

void f1() throws ExceptionType1, ExceptionType2 {}

void catchFunction() {
  try{
    while(someCondition){
      try{
        f1(); 
      }catch(ExceptionType2 e2){
        //do something, don't break the loop
      }
    }
  }catch(ExceptionType1 e1){
    //break the loop, do something else
  }

}

How to convert Blob to String and String to Blob in java

How are you setting blob to DB? You should do:

 //imagine u have a a prepared statement like:
 PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
 String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
 byte[] buff = blobString.getBytes();
 myBlob.putBytes(1,buff);
 ps.setBlob(1, myBlob);
 ps.executeUpdate();

is there any IE8 only css hack?

Use conditional comments in HTML, like this:

<!--[if IE 8]>
<style>...</style>
<![endif]-->

See here: http://www.quirksmode.org/css/condcom.html

You can test for IE versions reliably and also be sure other browsers won't be confused.

PostgreSQL Autoincrement

Create Sequence.

CREATE SEQUENCE user_role_id_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 3
  CACHE 1;
ALTER TABLE user_role_id_seq
  OWNER TO postgres;

and alter table

ALTER TABLE user_roles ALTER COLUMN user_role_id SET DEFAULT nextval('user_role_id_seq'::regclass);

What's the easy way to auto create non existing dir in ansible

AFAIK, the only way this could be done is by using the state=directory option. While template module supports most of copy options, which in turn supports most file options, you can not use something like state=directory with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf is a directory ? or would it mean that {{project_root}}/conf/ should be created first.

So I don't think this is possible right now without adding a previous file task.

- file: 
    path: "{{project_root}}/conf"
    state: directory
    recurse: yes

MySQL date formats - difficulty Inserting a date

An add-on to the previous answers since I came across this concern:

If you really want to insert something like 24-May-2005 to your DATE column, you could do something like this:

INSERT INTO someTable(Empid,Date_Joined)
VALUES
    ('S710',STR_TO_DATE('24-May-2005', '%d-%M-%Y'));

In the above query please note that if it's May(ie: the month in letters) the format should be %M.

NOTE: I tried this with the latest MySQL version 8.0 and it works!

XSLT counting elements with a given value

This XPath:

count(//Property[long = '11007'])

returns the same value as:

count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.

As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:

count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:

count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.

EDIT (after question edit)


You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!

Here you go:

count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.

Binding an Image in WPF MVVM

If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.

Refer to the ".Source" of the image in the binding statement.

XAML

<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>

View Model Field

private Image _imageOpenClose;
public Image ImageOpenClose
{
    get
    {
        return _imageOpenClose;
    }
    set
    {
        _imageOpenClose = value;
        OnPropertyChanged();
    }
}

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

  • char: fixed-length character data with a maximum length of 8000 characters.
  • nchar: fixed-length unicode data with a maximum length of 4000 characters.
  • Char = 8 bit length
  • NChar = 16 bit length

Python: Get relative path from comparing two absolute paths

os.path.commonprefix() and os.path.relpath() are your friends:

>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var'])  # No common prefix: the root is the common prefix
'/'

You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:

paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
    …

You can then find the relative paths:

relative_paths = [os.path.relpath(path, common_prefix) for path in paths]

You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.

PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().

PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:

>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'

even though /usr/var is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix() solves this (specific) problem.

PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?

PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()), taking the intersection of all these parent sets, and selecting the longest common prefix.

PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath(), which returns a valid path.

Multi-select dropdown list in ASP.NET

I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.

laravel select where and where condition

$userRecord = Model::where([['email','=',$email],['password','=', $password]])->first();

or

$userRecord = self::where([['email','=',$email],['password','=', $password]])->first();

I` think this condition is better then 2 where. Its where condition array in array of where conditions;

Make column fixed position in bootstrap

Updated for Bootstrap 4

Bootstrap 4 now includes a position-fixed class for this purpose so there is no need for additional CSS...

<div class="container">
    <div class="row">
        <div class="col-lg-3">
            <div class="position-fixed">
                Fixed content
            </div>
        </div>
        <div class="col-lg-9">
            Normal scrollable content
        </div>
    </div>
</div>

https://www.codeply.com/go/yOF9csaptw

How to grep and replace

I got the answer.

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

Transaction marked as rollback only: How do I find the cause

Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/

1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.

OR:

2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.

window.open with headers

You can't directly add custom headers with window.open() in popup window but to work that we have two possible solutions


  1. Write Ajax method to call that particular URL with headers in a separate HTML file and use that HTML as url in<i>window.open()</i> here is abc.html
        $.ajax({
        url: "ORIGIONAL_URL",
        type: 'GET',
        dataType: 'json',
        headers: {
            Authorization : 'Bearer ' + data.id_token,
            AuthorizationCheck : 'AccessCode ' +data.checkSum , 
            ContentType :'application/json'
        },

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

        } });

call html

window.open('*\abc.html')

here CORS policy can block the request if CORS is not enabled in requested URL.


  1. You can request a URL that triggers a server-side program which makes the request with custom headers and then returns the response redirecting to that particular url.

Suppose in Java Servlet(/requestURL) we'll make this request

`

        String[] responseHeader= new String[2];
        responseHeader[0] = "Bearer " + id_token;
        responseHeader[1] = "AccessCode " + checkSum;

        String url = "ORIGIONAL_URL";

        URL obj = new URL(url);
        HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestProperty("Authorization", responseHeader[0]);
        urlConnection.setRequestProperty("AuthorizationCheck", responseHeader[1]);
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new 
                         InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuffer response1 = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response1.append(inputLine);
            }
            in.close();
            response.sendRedirect(response1.toString());
            // print result
            System.out.println(response1.toString());
        } else {
            System.out.println("GET request not worked");
        }

`

call servlet in window.open('/requestURL')

'gulp' is not recognized as an internal or external command

You need to make sure, when you run command (install npm -g gulp), it will create install gulp on C:\ directory.

that directory should match with whatver npm path variable set in your java path.

just run path from command prompt, and verify this. if not, change your java class path variable wherever you gulp is instaled.

It should work.

How to sort the letters in a string alphabetically in Python

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'

How to include view/partial specific styling in AngularJS

I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.

UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.

UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.

In case anyone in the future is interested, here's what I came up with:

1. Create a custom directive for the <head> element:

app.directive('head', ['$rootScope','$compile',
    function($rootScope, $compile){
        return {
            restrict: 'E',
            link: function(scope, elem){
                var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
                elem.append($compile(html)(scope));
                scope.routeStyles = {};
                $rootScope.$on('$routeChangeStart', function (e, next, current) {
                    if(current && current.$$route && current.$$route.css){
                        if(!angular.isArray(current.$$route.css)){
                            current.$$route.css = [current.$$route.css];
                        }
                        angular.forEach(current.$$route.css, function(sheet){
                            delete scope.routeStyles[sheet];
                        });
                    }
                    if(next && next.$$route && next.$$route.css){
                        if(!angular.isArray(next.$$route.css)){
                            next.$$route.css = [next.$$route.css];
                        }
                        angular.forEach(next.$$route.css, function(sheet){
                            scope.routeStyles[sheet] = sheet;
                        });
                    }
                });
            }
        };
    }
]);

This directive does the following things:

  1. It compiles (using $compile) an html string that creates a set of <link /> tags for every item in the scope.routeStyles object using ng-repeat and ng-href.
  2. It appends that compiled set of <link /> elements to the <head> tag.
  3. It then uses the $rootScope to listen for '$routeChangeStart' events. For every '$routeChangeStart' event, it grabs the "current" $$route object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head> tag. It also grabs the "next" $$route object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head> tag.
  4. And the ng-repeat part of the compiled <link /> tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles object.

Note: this requires that your ng-app attribute is on the <html> element, not on <body> or anything inside of <html>.

2. Specify which stylesheets belong to which routes using the $routeProvider:

app.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/some/route/1', {
            templateUrl: 'partials/partial1.html', 
            controller: 'Partial1Ctrl',
            css: 'css/partial1.css'
        })
        .when('/some/route/2', {
            templateUrl: 'partials/partial2.html',
            controller: 'Partial2Ctrl'
        })
        .when('/some/route/3', {
            templateUrl: 'partials/partial3.html',
            controller: 'Partial3Ctrl',
            css: ['css/partial3_1.css','css/partial3_2.css']
        })
}]);

This config adds a custom css property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart' event as .$$route. So when listening to the '$routeChangeStart' event, we can grab the css property that we specified and append/remove those <link /> tags as needed. Note that specifying a css property on the route is completely optional, as it was omitted from the '/some/route/2' example. If the route doesn't have a css property, the <head> directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3' example above, where the css property is an array of relative paths to the stylesheets needed for that route.

3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.

Hope that helps someone else who might be struggling with this issue as much as I was.

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

What is the best free SQL GUI for Linux for various DBMS systems

I'm sticking with DbVisualizer Free until something better comes along.

EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this

How to iterate over arguments in a Bash script

Note that Robert's answer is correct, and it works in sh as well. You can (portably) simplify it even further:

for i in "$@"

is equivalent to:

for i

I.e., you don't need anything!

Testing ($ is command prompt):

$ set a b "spaces here" d
$ for i; do echo "$i"; done
a
b
spaces here
d
$ for i in "$@"; do echo "$i"; done
a
b
spaces here
d

I first read about this in Unix Programming Environment by Kernighan and Pike.

In bash, help for documents this:

for NAME [in WORDS ... ;] do COMMANDS; done

If 'in WORDS ...;' is not present, then 'in "$@"' is assumed.

grep exclude multiple strings

The greps can be chained. For example:

tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"

Resetting a form in Angular 2 after submit

I used in similar case the answer from Günter Zöchbauer, and it was perfect to me, moving the form creation to a function and calling it from ngOnInit().

For illustration, that's how I made it, including the fields initialization:

ngOnInit() {
    // initializing the form model here
    this.createForm();
}

createForm() {
    let EMAIL_REGEXP = /^[^@]+@([^@\.]+\.)+[^@\.]+$/i; // here just to add something more, useful too

    this.userForm = new FormGroup({
        name: new FormControl('', [Validators.required, Validators.minLength(3)]),
        city: new FormControl(''),
        email: new FormControl(null, Validators.pattern(EMAIL_REGEXP))
    });

    this.initializeFormValues();
}

initializeFormValues() {
    const people = {
        name: '',
        city: 'Rio de Janeiro',  // Only for demonstration
        email: ''
    };
    (<FormGroup>this.userForm).setValue(people, { onlySelf: true });
}

resetForm() {
    this.createForm();
    this.submitted = false;
}

I added a button to the form for a smart reset (with the fields initialization):

In the HTML file (or inline template):

<button type="button" [disabled]="userForm.pristine" (click)="resetForm()">Reset</button>

After loading the form at first time or after clicking the reset button we have the following status:

FORM pristine: true 
FORM valid: false (because I have required a field) 
FORM submitted: false
Name pristine: true
City pristine: true
Email pristine: true

And all the field initializations that a simple form.reset() doesn't make for us! :-)

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

How to send a simple email from a Windows batch file?

$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"@
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )

C# List<> Sort by x then y

The trick is to implement a stable sort. I've created a Widget class that can contain your test data:

public class Widget : IComparable
{
    int x;
    int y;
    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public Widget(int argx, int argy)
    {
        x = argx;
        y = argy;
    }

    public int CompareTo(object obj)
    {
        int result = 1;
        if (obj != null && obj is Widget)
        {
            Widget w = obj as Widget;
            result = this.X.CompareTo(w.X);
        }
        return result;
    }

    static public int Compare(Widget x, Widget y)
    {
        int result = 1;
        if (x != null && y != null)                
        {                
            result = x.CompareTo(y);
        }
        return result;
    }
}

I implemented IComparable, so it can be unstably sorted by List.Sort().

However, I also implemented the static method Compare, which can be passed as a delegate to a search method.

I borrowed this insertion sort method from C# 411:

 public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)
        {           
            int count = list.Count;
            for (int j = 1; j < count; j++)
            {
                T key = list[j];

                int i = j - 1;
                for (; i >= 0 && comparison(list[i], key) > 0; i--)
                {
                    list[i + 1] = list[i];
                }
                list[i + 1] = key;
            }
    }

You would put this in the sort helpers class that you mentioned in your question.

Now, to use it:

    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();

        widgets.Add(new Widget(0, 1));
        widgets.Add(new Widget(1, 1));
        widgets.Add(new Widget(0, 2));
        widgets.Add(new Widget(1, 2));

        InsertionSort<Widget>(widgets, Widget.Compare);

        foreach (Widget w in widgets)
        {
            Console.WriteLine(w.X + ":" + w.Y);
        }
    }

And it outputs:

0:1
0:2
1:1
1:2
Press any key to continue . . .

This could probably be cleaned up with some anonymous delegates, but I'll leave that up to you.

EDIT: And NoBugz demonstrates the power of anonymous methods...so, consider mine more oldschool :P

Calling dynamic function with dynamic number of parameters

If you want to pass with "arguments" a few others, you have to create the array of all arguments together, i.e. like this:

var Log = {
    log: function() {
        var args = ['myarg here'];
        for(i=0; i<arguments.length; i++) args = args.concat(arguments[i]);
        console.log.apply(this, args);
    }
}

NuGet behind a proxy

Another flavor for same "proxy for nuget": alternatively you can set your nuget proxing settings to connect through fiddler. Below cmd will save proxy settings in in default nuget config file for user at %APPDATA%\NuGet\NuGet.Config

nuget config -Set HTTP_PROXY=http://127.0.0.1:8888

Whenever you need nuget to reach out the internet, just open Fiddler, asumming you have fiddler listening on default port 8888.

This configuration is not sensitive to passwork changes because fiddler will resolve any authentication with up stream proxy for you.

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

How to select all instances of selected region in Sublime Text

Note: You should not edit the default settings, because they get reset on updates/upgrades. For customization, you should override any setting by using the user bindings.

On Mac:

  • Sublime Text 2 > Preferences > Key Bindings-Default
  • Sublime Text 3 > Preferences > Key Bindings

This opens a document that you can edit the keybindings for Sublime.

If you search "ctrl+super+g" you find this:

{ "keys": ["ctrl+super+g"], "command": "find_all_under" },

Jenkins not executing jobs (pending - waiting for next executor)

In my case it is similar to @Michael Easter: I got a problem in a job due to lack of disk space. I cleared some space, restarted Jenkins but still the problem persisted.

The solution was to go to Jenkins -> Manage Jenkins -> Manage Nodes and just Click on the button to update the status.

Mongoose.js: Find user by username LIKE value

Just complementing @PeterBechP 's answer.

Don't forget to scape the special chars. https://stackoverflow.com/a/6969486

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

var name = 'Peter+with+special+chars';

model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
  //Do your action here..
});

How do I select an element in jQuery by using a variable for the ID?

Doing $('body').find(); is not necessary when looking up by ID; there is no performance gain.

Please also note that having an ID that starts with a number is not valid HTML:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Selecting option by text content with jQuery

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

PostgreSQL how to see which queries have run

PostgreSql is very advanced when related to logging techniques

Logs are stored in Installationfolder/data/pg_log folder. While log settings are placed in postgresql.conf file.

Log format is usually set as stderr. But CSV log format is recommended. In order to enable CSV format change in

log_destination = 'stderr,csvlog'   
logging_collector = on

In order to log all queries, very usefull for new installations, set min. execution time for a query

log_min_duration_statement = 0

In order to view active Queries on your database, use

SELECT * FROM pg_stat_activity

To log specific queries set query type

log_statement = 'all'           # none, ddl, mod, all

For more information on Logging queries see PostgreSql Log.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:

SELECT 
    name, author_id, count(*), t.total
FROM
    names as n1
    INNER JOIN LATERAL (
        SELECT 
            count(*) as total
        FROM 
            names as n2
        WHERE 
            n2.id = n1.id
            AND n2.author_id = n1.author_id
    ) as t ON 1=1
GROUP BY 
    n1.name, n1.author_id

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

You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo["bar"]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]

But you can make a filter which lets you pass in an argument:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}

Template not provided using create-react-app

One of the easiest way to do it is by using

npx --ignore-existing create-react-app [project name]

This will remove the old cached version of create-react-app and then get the new version to create the project.

Note: Adding the name of the project is important as just ignoring the existing create-react-app version is stale and the changes in your machines global env is temporary and hence later just using npx create-react-app [project name] will not provide the desired result.

How to turn off caching on Firefox?

First of All, this can be easily done, for e.g. by PHP to force the browser to renew files based on cache date (expiration time). If you just need it for experimental needs, then try to use ctrl+shift+del to clear all cache at once inside Firefox browser. The third solution is to use many add-ons that exits for Firefox to clear cache based on time lines.

ESRI : Failed to parse source map

The error in the Google DevTools are caused Google extensions.

  1. I clicked on my Google icon in the browser
  2. created a guest profile at the bottom of the popup window.
  3. I then pasted my localhost address and voila!!

No more errors in the console.

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Align Div at bottom on main Div

Give your parent div position: relative, then give your child div position: absolute, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;

See example here:

http://jsfiddle.net/PGMqs/1/

How to set all elements of an array to zero or any same value?

If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};

Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};

Limiting Python input strings to certain characters and lengths

Regexes can also limit the number of characters.

r = re.compile("^[a-z]{1,15}$")

gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Issue in my case: Some updates were made to some rows within a transaction and before the transaction was committed, in another place, the same rows were being updated outside this transaction. Ensuring that all the updates to the rows are made within the same transaction resolved my issue.

How can I account for period (AM/PM) using strftime?

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

In my case, in the host file, the machine name is hard coded with older IP. I replace the older IP with the new one, the issue is resolved.

Host file location

WindowsDrive:\Windows\System32\drivers\etc\hosts

Modifications done 159.xx.xx.xxx MachineName

CSV API for Java

Update: The code in this answer is for Super CSV 1.52. Updated code examples for Super CSV 2.4.0 can be found at the project website: http://super-csv.github.io/super-csv/index.html


The SuperCSV project directly supports the parsing and structured manipulation of CSV cells. From http://super-csv.github.io/super-csv/examples_reading.html you'll find e.g.

given a class

public class UserBean {
    String username, password, street, town;
    int zip;

    public String getPassword() { return password; }
    public String getStreet() { return street; }
    public String getTown() { return town; }
    public String getUsername() { return username; }
    public int getZip() { return zip; }
    public void setPassword(String password) { this.password = password; }
    public void setStreet(String street) { this.street = street; }
    public void setTown(String town) { this.town = town; }
    public void setUsername(String username) { this.username = username; }
    public void setZip(int zip) { this.zip = zip; }
}

and that you have a CSV file with a header. Let's assume the following content

username, password,   date,        zip,  town
Klaus,    qwexyKiks,  17/1/2007,   1111, New York
Oufu,     bobilop,    10/10/2007,  4555, New York

You can then create an instance of the UserBean and populate it with values from the second line of the file with the following code

class ReadingObjects {
  public static void main(String[] args) throws Exception{
    ICsvBeanReader inFile = new CsvBeanReader(new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
    try {
      final String[] header = inFile.getCSVHeader(true);
      UserBean user;
      while( (user = inFile.read(UserBean.class, header, processors)) != null) {
        System.out.println(user.getZip());
      }
    } finally {
      inFile.close();
    }
  }
}

using the following "manipulation specification"

final CellProcessor[] processors = new CellProcessor[] {
    new Unique(new StrMinMax(5, 20)),
    new StrMinMax(8, 35),
    new ParseDate("dd/MM/yyyy"),
    new Optional(new ParseInt()),
    null
};

How do I trim a file extension from a String in Java?

String[] splitted = fileName.split(".");
String fileNameWithoutExtension = fileName.replace("." + splitted[splitted.length - 1], "");

Mix Razor and Javascript code

Inside a code block (eg, @foreach), you need to mark the markup (or, in this case, Javascript) with @: or the <text> tag.

Inside the markup contexts, you need to surround code with code blocks (@{ ... } or @if, ...)

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

SQL Server SELECT LAST N Rows

DECLARE @MYVAR  NVARCHAR(100)
DECLARE @step  int
SET @step = 0;


DECLARE MYTESTCURSOR CURSOR
DYNAMIC 
FOR
SELECT col FROM [dbo].[table]
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO @MYVAR
print @MYVAR;


WHILE @step < 10
BEGIN   
    FETCH PRIOR FROM MYTESTCURSOR INTO @MYVAR
        print @MYVAR;
        SET @step = @step + 1;
END   
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR

How to Edit a row in the datatable

You can find that row with

DataRow row = table.Select("Product_id=2").FirstOrDefault();

and update it

row["Product_name"] = "cde";

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I have solved this problem by importing the following dependency. you must manually import httpclient

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>*</artifactId>
        </exclusion>
    </exclusions>
</dependency>

How do you reindex an array in PHP but with indexes starting from 1?

I just found out you can also do a

array_splice($ar, 0, 0);

That does the re-indexing inplace, so you don't end up with a copy of the original array.

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

Event binding on dynamically created elements?

You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;

Javascript : natural sort of alphanumerical strings

This is now possible in modern browsers using localeCompare. By passing the numeric: true option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'. Tested in Chrome, Firefox, and IE11.

Here's an example. It returns 1, meaning 10 goes after 2:

'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})

For performance when sorting large numbers of strings, the article says:

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link

_x000D_
_x000D_
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});_x000D_
var myArray = ['1_Document', '11_Document', '2_Document'];_x000D_
console.log(myArray.sort(collator.compare));
_x000D_
_x000D_
_x000D_

View the change history of a file using Git versioning

For a graphical view I'd use gitk:

gitk [filename]

or to follow filename past renames

gitk --follow [filename]

Grep to find item in Perl array

In addition to what eugene and stevenl posted, you might encounter problems with using both <> and <STDIN> in one script: <> iterates through (=concatenating) all files given as command line arguments.

However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input

Create <div> and append <div> dynamically

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';

var iDiv2 = document.createElement('div');
iDiv2.className = "block-2";

iDiv.appendChild(iDiv2);
// Append to the document last so that the first append is more efficient.
document.body.appendChild(iDiv);

Command CompileSwift failed with a nonzero exit code in Xcode 10

My problem was I had due to the non-existence of a native Swift CommonCrypto, used a bridging header and a target that with some magic included it in the build. Since CommonCrypto is now native, I solved the problem by removing the target and the #import and instead added an import CommonCrypto where I used it.

When use getOne and findOne methods Spring Data JPA

1. Why does the getOne(id) method fail?

See this section in the docs. You overriding the already in place transaction might be causing the issue. However, without more info this one is difficult to answer.

2. When I should use the getOne(id) method?

Without digging into the internals of Spring Data JPA, the difference seems to be in the mechanism used to retrieve the entity.

If you look at the JavaDoc for getOne(ID) under See Also:

See Also:
EntityManager.getReference(Class, Object)

it seems that this method just delegates to the JPA entity manager's implementation.

However, the docs for findOne(ID) do not mention this.

The clue is also in the names of the repositories. JpaRepository is JPA specific and therefore can delegate calls to the entity manager if so needed. CrudRepository is agnostic of the persistence technology used. Look here. It's used as a marker interface for multiple persistence technologies like JPA, Neo4J etc.

So there's not really a 'difference' in the two methods for your use cases, it's just that findOne(ID) is more generic than the more specialised getOne(ID). Which one you use is up to you and your project but I would personally stick to the findOne(ID) as it makes your code less implementation specific and opens the doors to move to things like MongoDB etc. in the future without too much refactoring :)

Failed to install *.apk on device 'emulator-5554': EOF

you could try this:

   1. Open the "Android Virtual device Manager"
   2. Select from one the listed devices there and run it.
   3. Right click your Android App -> Run As -> Android Application

It worked for me. I tried this on an emulator in eclipse. It takes a while before the app is run. For me it took 33 seconds. Wait until the message in the console says "Success!"

How to filter object array based on attributes?

const state.contactList = [{
    name: 'jane',
    email: '[email protected]'
  },{},{},...]

const fileredArray = state.contactsList.filter((contactItem) => {
  const regex = new RegExp(`${action.payload}`, 'gi');
  return contactItem.nameProperty.match(regex) || 
    contactItem.emailProperty.match(regex);
});


// contactList: all the contacts stored in state
// action.payload: whatever typed in search field

Postgresql GROUP_CONCAT equivalent?

Since 9.0 this is even easier:

SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Ahah! Cade is on the money.

An artifact in TOAD prints \r\n as two placeholder 'blob' characters, but prints a single \r also as two placeholders. The 1st step toward a solution is to use ..

REPLACE( col_name, CHR(13) || CHR(10) )

.. but I opted for the slightly more robust ..

REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )

.. which catches offending characters in any order. My many thanks to Cade.

M.

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

How do I pass environment variables to Docker containers?

Using jq to convert the env to JSON:

env_as_json=`jq -c -n env`
docker run -e HOST_ENV="$env_as_json" <image>

this requires jq version 1.6 or newer

this pust the host env as json, essentially like so in Dockerfile:

ENV HOST_ENV  (all env from the host as json)

JavaScript click event listener on class

Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.

const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
  i.addEventListener("click", (e) => {
    if (e.target.classList.contains("className")) {
        console.log("Perfrom Action")
    }
  })
}

Returning multiple objects in an R function

You could use for() with assign() to create many objects. See the example from assign():

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
    nam <- paste("r", i, sep = ".")
    assign(nam, 1:i)

Looking the new objects

ls(pattern = "^r..$")

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
     {
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "message_id": 1
       },
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0].chat.id, save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

Determine the type of an object?

Determine the type of a Python object

Determine the type of an object with type

>>> obj = object()
>>> type(obj)
<class 'object'>

Although it works, avoid double underscore attributes like __class__ - they're not semantically public, and, while perhaps not in this case, the builtin functions usually have better behavior.

>>> obj.__class__ # avoid this!
<class 'object'>

type checking

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.

Well that's a different question, don't use type - use isinstance:

def foo(obj):
    """given a string with items separated by spaces, 
    or a list or tuple, 
    do something sensible
    """
    if isinstance(obj, str):
        obj = str.split()
    return _foo_handles_only_lists_or_tuples(obj)

This covers the case where your user might be doing something clever or sensible by subclassing str - according to the principle of Liskov Substitution, you want to be able to use subclass instances without breaking your code - and isinstance supports this.

Use Abstractions

Even better, you might look for a specific Abstract Base Class from collections or numbers:

from collections import Iterable
from numbers import Number

def bar(obj):
    """does something sensible with an iterable of numbers, 
    or just one number
    """
    if isinstance(obj, Number): # make it a 1-tuple
        obj = (obj,)
    if not isinstance(obj, Iterable):
        raise TypeError('obj must be either a number or iterable of numbers')
    return _bar_sensible_with_iterable(obj)

Or Just Don't explicitly Type-check

Or, perhaps best of all, use duck-typing, and don't explicitly type-check your code. Duck-typing supports Liskov Substitution with more elegance and less verbosity.

def baz(obj):
    """given an obj, a dict (or anything with an .items method) 
    do something sensible with each key-value pair
    """
    for key, value in obj.items():
        _baz_something_sensible(key, value)

Conclusion

  • Use type to actually get an instance's class.
  • Use isinstance to explicitly check for actual subclasses or registered abstractions.
  • And just avoid type-checking where it makes sense.

How do I get bit-by-bit data from an integer value in C?

Using std::bitset

int value = 123;
std::bitset<sizeof(int)> bits(value);
std::cout <<bits.to_string();

Splitting comma separated string in a PL/SQL stored proc

I am not sure if this fits your oracle version. On my 10g I can use pipelined table functions:

set serveroutput on

create type number_list as table of number;

-- since you want this solution
create or replace function split_csv (i_csv varchar2) return number_list pipelined 
  is 
    mystring varchar2(2000):= i_csv;
  begin
    for r in
    ( select regexp_substr(mystring,'[^,]+',1,level) element
        from dual
     connect by level <= length(regexp_replace(mystring,'[^,]+')) + 1
    )
    loop
      --dbms_output.put_line(r.element);
      pipe row(to_number(r.element, '999999.99'));
    end loop;
  end;
/

insert into foo
select column_a,column_b from 
  (select column_value column_a, rownum rn from table(split_csv('0.75, 0.64, 0.56, 0.45'))) a 
 ,(select column_value column_b, rownum rn from table(split_csv('0.25, 0.5, 0.65, 0.8'))) b
 where a.rn = b.rn
;

Best XML Parser for PHP

Have a look at PHP's available XML extensions.

The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load the current node into memory. You define handlers for specific nodes which will get triggered when the Parser encounters it. That is faster and saves on memory. You pay for that with not being able to use XPath.

Personally, I find SimpleXml quite limiting (hence simple) in what it offers over DOM. You can switch between DOM and SimpleXml easily though, but I usually dont bother and go the DOM route directly. DOM is an implementation of the W3C DOM API, so you might be familiar with it from other languages, for instance JavaScript.

How to normalize a signal to zero mean and unit variance?

It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)

This should work:

%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)

%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)

How can I make a Python script standalone executable to run without ANY dependency?

I like PyInstaller - especially the "windowed" variant:

pyinstaller --onefile --windowed myscript.py

It will create one single *.exe file in a distination/folder.

Compile a DLL in C/C++, then call it from another program

The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.

You have two options to use a dll

  • Either use a lib file to link the symbols -- compile time dynamic linking
  • Use LoadLibrary() or some suitable function to load the library, retrieve a function pointer (GetProcAddress) and call it -- runtime dynamic linking

Exporting classes will not work if you follow the second method though.

Attempt to write a readonly database - Django w/ SELinux error

You have to add writing rights to the directory in which your sqlite database is stored. So running chmod 664 /srv/mysite should help.

This is a security risk, so better solution is to change the owner of your database to www-data:

chown www-data:www-data /srv/mysite
chown www-data:www-data /srv/mysite/DATABASE.sqlite

Typescript: difference between String and string

TypeScript: String vs string

Argument of type 'String' is not assignable to parameter of type 'string'.

'string' is a primitive, but 'String' is a wrapper object.

Prefer using 'string' when possible.

demo

String Object

// error
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: String = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: String = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

string primitive

// ok
class SVGStorageUtils {
  store: object;
  constructor(store: object) {
    this.store = store;
  }
  setData(key: string = ``, data: object) {
    sessionStorage.setItem(key, JSON.stringify(data));
  }
  getData(key: string = ``) {
    const obj = JSON.parse(sessionStorage.getItem(key));
  }
}

enter image description here

How to prettyprint a JSON file?

You can do this on the command line:

python3 -m json.tool some.json

(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).

Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing.

You can also use jq:

jq . some.json

and you get colors as a bonus (and way easier extendability).

Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  $(window).scroll(function() {_x000D_
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
      }_x000D_
    });_x000D_
  }).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/2/)

  • I wrapped the fade-codeline in an if-clause: if ($(this).css("opacity")==0) {...}. This makes sure the object is only faded in when the opacity is 0. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object.
  • I changed .animate() to .fadeTo(). It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate.
  • I changed .position() to .offset(). This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.
  • I changed $(window).height() to $(window).innerHeight(). The latter is more reliable in my experience.
  • Directly after the scroll-handler, I invoke that handler once on page-load with $(window).scroll();. Now you can give all desired objects on the page the .fade class, and objects that should be invisible at page-load, will be faded out immediately.
  • I removed #container from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px because you used .position() instead of .offset(), otherwise I don't know. Feel free of course to leave it in your code.)

UPDATE

If you want opacity values other than 0 and 1, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
    var min = 0.3;_x000D_
    var max = 0.7;_x000D_
    var threshold = 0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
      }_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/3/)

  • I added a threshold to the if-clause, see explanation below.
  • I created variables for the threshold and for min/max at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.
  • I also added || pageLoad to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad is a boolean that is send along as an argument when fade() is invoked.
    I had to put the fade-code inside the extra function fade() {...}, in order to be able to send along the pageLoad boolean when the scroll-handler is invoked.
    I did't see any other way to do this, if anyone else does, please leave a comment.

Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3, the actual value (in this case) is 0.300000011920929. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}.

I added a threshold, to take that difference into account: == 0.3 becomes <= 0.31.
(I've set the threshold to 0.01, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)

The operators are now changed from == to <= and >=.


UPDATE 2:

If you want to fade the elements based on their visible percentage, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
    var min=0.3, max=0.7, threshold=0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
      _x000D_
      /* Fade element in/out based on its visible percentage */_x000D_
      if (objectTop < windowTop) {_x000D_
        if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if (objectBottom > windowBottom) {_x000D_
        if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/5/)

What exceptions should be thrown for invalid or unexpected parameters in .NET?

I like to use: ArgumentException, ArgumentNullException, and ArgumentOutOfRangeException.

There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:

  • InvalidOperationException – The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote his answer up as well.
  • NotSupportedException – The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.

The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.

I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. “Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”. When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.

Thanks to STW (ex Yoooder) again for the comments.


In response to your followup, I would throw an ArgumentOutOfRangeException. Look at what MSDN says about this exception:

ArgumentOutOfRangeException is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference (Nothing in Visual Basic) and does not contain a valid value.

So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say ArgumentOutOfRangeException, another developer might say ArgumentException. Make it easy and document the behavior.

Copy/Paste from Excel to a web page

In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:

http://jsfiddle.net/duwood/sTX7y/

HTML

<p>Paste excel data here:</p>  
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
    <p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>

JS

function generateTable() {
    var data = $('textarea[name=excel_data]').val();
    console.log(data);
    var rows = data.split("\n");

    var table = $('<table />');

    for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);
}

Where is Ubuntu storing installed programs?

for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.

hope it helps

Automatic vertical scroll bar in WPF TextBlock?

Something better would be:

<Grid Width="Your-specified-value" >
    <ScrollViewer>
         <TextBlock Width="Auto" TextWrapping="Wrap" />
    </ScrollViewer>
</Grid>

This makes sure that the text in your textblock does not overflow and overlap the elements below the textblock as may be the case if you do not use the grid. That happened to me when I tried other solutions even though the textblock was already in a grid with other elements. Keep in mind that the width of the textblock should be Auto and you should specify the desired with in the Grid element. I did this in my code and it works beautifully. HTH.

Throwing exceptions from constructors

Adding to all the answers here, I thought to mention, a very specific reason/scenario where you might want to prefer to throw the exception from the class's Init method and not from the Ctor (which off course is the preferred and more common approach).

I will mention in advance that this example (scenario) assumes that you don't use "smart pointers" (i.e.- std::unique_ptr) for your class' s pointer(s) data members.

So to the point: In case, you wish that the Dtor of your class will "take action" when you invoke it after (for this case) you catch the exception that your Init() method threw - you MUST not throw the exception from the Ctor, cause a Dtor invocation for Ctor's are NOT invoked on "half-baked" objects.

See the below example to demonstrate my point:

#include <iostream>

using namespace std;

class A
{
    public:
    A(int a)
        : m_a(a)
    {
        cout << "A::A - setting m_a to:" << m_a << endl;
    }

    ~A()
    {
        cout << "A::~A" << endl;
    }

    int m_a;
};

class B
{
public:
    B(int b)
        : m_b(b)
    {
        cout << "B::B - setting m_b to:" << m_b << endl;
    }

    ~B()
    {
        cout << "B::~B" << endl;
    }

    int m_b;
};

class C
{
public:
    C(int a, int b, const string& str)
        : m_a(nullptr)
        , m_b(nullptr)
        , m_str(str)
    {
        m_a = new A(a);
        cout << "C::C - setting m_a to a newly A object created on the heap (address):" << m_a << endl;
        if (b == 0)
        {
            throw exception("sample exception to simulate situation where m_b was not fully initialized in class C ctor");
        }

        m_b = new B(b);
        cout << "C::C - setting m_b to a newly B object created on the heap (address):" << m_b << endl;
    }

    ~C()
    {
        delete m_a;
        delete m_b;
        cout << "C::~C" << endl;
    }

    A* m_a;
    B* m_b;
    string m_str;
};

class D
{
public:
    D()
        : m_a(nullptr)
        , m_b(nullptr)
    {
        cout << "D::D" << endl;
    }

    void InitD(int a, int b)
    {
        cout << "D::InitD" << endl;
        m_a = new A(a);
        throw exception("sample exception to simulate situation where m_b was not fully initialized in class D Init() method");
        m_b = new B(b);
    }

    ~D()
    {
        delete m_a;
        delete m_b;
        cout << "D::~D" << endl;
    }

    A* m_a;
    B* m_b;
};

void item10Usage()
{
    cout << "item10Usage - start" << endl;

    // 1) invoke a normal creation of a C object - on the stack
    // Due to the fact that C's ctor throws an exception - its dtor
    // won't be invoked when we leave this scope
    {
        try
        {
            C c(1, 0, "str1");
        }
        catch (const exception& e)
        {
            cout << "item10Usage - caught an exception when trying to create a C object on the stack:" << e.what() << endl;
        }
    }

    // 2) same as in 1) for a heap based C object - the explicit call to 
    //    C's dtor (delete pc) won't have any effect
    C* pc = 0;
    try
    {
        pc = new C(1, 0, "str2");
    }
    catch (const exception& e)
    {
        cout << "item10Usage - caught an exception while trying to create a new C object on the heap:" << e.what() << endl;
        delete pc; // 2a)
    }

    // 3) Here, on the other hand, the call to delete pd will indeed 
    //    invoke D's dtor
    D* pd = new D();
    try
    {
        pd->InitD(1,0);
    }
    catch (const exception& e)
    {
        cout << "item10Usage - caught an exception while trying to init a D object:" << e.what() << endl;
        delete pd; 
    }

    cout << "\n \n item10Usage - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    item10Usage();
    cout << "\n \n main - end" << endl;
    return 0;
}

I will mention again, that it is not the recommended approach, just wanted to share an additional point of view.

Also, as you might have seen from some of the print in the code - it is based on item 10 in the fantastic "More effective C++" by Scott Meyers (1st edition).

Get the Highlighted/Selected text

This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)

Oracle - How to create a materialized view with FAST REFRESH and JOINS

You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.

How to change file encoding in NetBeans?

The NetBeans documentation merely states a hierarchy for FileEncodingQuery (FEQ), suggesting that you can set encoding on a per-file basis:

Just for reference, this is the wiki-page regarding project-wide settings:

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):

@using (Html.BeginForm("RemoveFromCart", "Cart")) {
                    @Html.Hidden("ProductId", line.Product.ProductID)
                    @Html.HiddenFor(x => x.ReturnUrl)
                    <input class="btn btn-sm btn-warning"
                           type="submit" value="Remove" />
                }

If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".

public ViewResult RemoveFromCart(int productId, string returnUrl){...}

If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.

*Adam Freeman (Apress - Pro ASP.Net MVC 5)

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Another approach(Inside of $function to asure that the each is executed on document ready):

var ids = [1,2];
$(function(){
  $('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
    if(ids.indexOf($(item).data('id')) > -1){
       $(item).prop("checked", "checked");
    }
  });
});

Working fiddle: https://jsfiddle.net/robertrozas/w5uda72v/

What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?

Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the length:0 means that it doesn't find any element based on your search criteria.

About n.fn.init[0], lets look at the core of the Jquery Library:

var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};

Looks familiar, right?, now in a minified version of jquery, this should looks like:

var n = function( selector, context ) {
   return new n.fn.init( selector, context );
};

So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.

How to center text vertically with a large font-awesome icon?

a flexbox option - font awesome 4.7 and below

FA 4.x Hosted URL - https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css

_x000D_
_x000D_
div {_x000D_
  display: inline-flex; /* make element size relative to content */_x000D_
  align-items: center; /* vertical alignment of items */_x000D_
  line-height: 40px; /* vertically size by height, line-height or padding */_x000D_
  padding: 0px 10px; /* horizontal with padding-l/r */_x000D_
  border: 1px solid #ccc;_x000D_
}_x000D_
_x000D_
/* unnecessary styling below, ignore */_x000D_
body {display: flex;justify-content: center;align-items: center;height: 100vh;}div i {margin-right: 10px;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(34, 100%, 52%, 0.5);cursor: pointer;}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<div>_x000D_
    <i class='fa fa-2x fa-camera'></i>_x000D_
    hello world_x000D_
</div>
_x000D_
_x000D_
_x000D_

fiddle

http://jsfiddle.net/Hastig/V7DLm/180/


using flex and font awesome 5

FA 5.x Hosted URL - https://use.fontawesome.com/releases/v5.0.8/js/all.js

_x000D_
_x000D_
div {_x000D_
  display: inline-flex; /* make element size relative to content */_x000D_
  align-items: center; /* vertical alignment of items */_x000D_
  padding: 3px 10px; /* horizontal vertical position with padding */_x000D_
  border: 1px solid #ccc;_x000D_
}_x000D_
.svg-inline--fa { /* target all FA icons */_x000D_
  padding-right: 10px;_x000D_
}_x000D_
.icon-camera .svg-inline--fa { /* target specific icon */_x000D_
  font-size: 50px;_x000D_
}_x000D_
/* unnecessary styling below, ignore */_x000D_
body {display: flex;justify-content: center;align-items: center;height: 100vh; flex-direction: column;}div{margin: 10px 0;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(212, 100%, 63%, 1);cursor: pointer;}
_x000D_
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>_x000D_
<div class="icon-camera">_x000D_
    <i class='fas fa-camera'></i>_x000D_
    hello world_x000D_
</div>_x000D_
<div class="icon-clock">_x000D_
    <i class='fas fa-clock'></i>_x000D_
    hello world_x000D_
</div>
_x000D_
_x000D_
_x000D_

fiddle

https://jsfiddle.net/3bpjvof2/

How to get the first word in the string

You don't need regex to split a string on whitespace:

In [1]: text = '''WYATT    - Ranked # 855 with    0.006   %
   ...: XAVIER   - Ranked # 587 with    0.013   %
   ...: YONG     - Ranked # 921 with    0.006   %
   ...: YOUNG    - Ranked # 807 with    0.007   %'''

In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG

Overlapping Views in Android

Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView in front of a Gallery) is certainly possible.

If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/gallerylayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Gallery
    android:id="@+id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
  <ImageView
    android:id="@+id/navigmaske"
    android:background="#0000"      
    android:src="@drawable/navigmask"
    android:scaleType="fitXY"
    android:layout_alignTop="@id/overview"
    android:layout_alignBottom="@id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
</RelativeLayout>

Note that I've changed the parent RelativeLayout to a height and width of fill_parent as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView to the top and bottom of the Gallery to ensure it's centered in front of it.

I've also explicitly set the background of the ImageView to be transparent.

As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.

updating Google play services in Emulator

You need install Google play image, Android SDK -> SDK platforms --> check show Package details --> install Google play. enter image description here

Detect if a jQuery UI dialog box is open

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

Passing parameters to JavaScript files

might be very simple

for example

<script src="js/myscript.js?id=123"></script>
<script>
    var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>

You can then convert query string into json like below

var json = $.parseJSON('{"' 
            + queryString.replace(/&/g, '","').replace(/=/g, '":"') 
            + '"}');

and then can use like

console.log(json.id);

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

look at

http://jtds.sourceforge.net/faq.html#driverImplementation

What is the URL format used by jTDS?

The URL format for jTDS is:

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

... domain Specifies the Windows domain to authenticate in. If present and the user name and password are provided, jTDS uses Windows (NTLM) authentication instead of the usual SQL Server authentication (i.e. the user and password provided are the domain user and password). This allows non-Windows clients to log in to servers which are only configured to accept Windows authentication.

If the domain parameter is present but no user name and password are provided, jTDS uses its native Single-Sign-On library and logs in with the logged Windows user's credentials (for this to work one would obviously need to be on Windows, logged into a domain, and also have the SSO library installed -- consult README.SSO in the distribution on how to do this).

How to bind bootstrap popover on dynamic elements

Probably way too late but this is another option:

 $('body').popover({
    selector: '[rel=popover]',
    trigger: 'hover',
    html: true,
    content: function () {
        return $(this).parents('.row').first().find('.metaContainer').html();
    }
});

IntelliJ IDEA generating serialVersionUID

I am using Android Studio 2.1 and I have better consistency of getting the lightbulb by clicking on the class Name and hover over it for a second.

Check if a temporary table exists and delete if it exists before creating a temporary table

I cannot reproduce the error.

Perhaps I'm not understanding the problem.

The following works fine for me in SQL Server 2005, with the extra "foo" column appearing in the second select result:

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO
CREATE TABLE #Results ( Company CHAR(3), StepId TINYINT, FieldId TINYINT )
GO
select company, stepid, fieldid from #Results
GO
ALTER TABLE #Results ADD foo VARCHAR(50) NULL
GO
select company, stepid, fieldid, foo from #Results
GO
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
GO

How to format DateTime in Flutter , How to get current time in flutter?

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

Android Studio how to run gradle sync manually?

I think ./gradlew tasks is same with Android studio sync. Why? I will explain it.

I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest in command line directly , error appear.

Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar

However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar appear naturally. I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks makes the jar appear as well. So I can get the same result in gralde script.

Besides, gradle --recompile-scripts does not work for the problem.

Insert node at a certain position in a linked list C++

 void addToSpecific()
 {
 int n;   
 int f=0;   //flag
 Node *temp=H;    //H-Head, T-Tail
 if(NULL!=H)  
 {
    cout<<"Enter the Number"<<endl;
    cin>>n;
    while(NULL!=(temp->getNext()))
    {
       if(n==(temp->getInfo()))
       {
      f=1;
      break;
       }
       temp=temp->getNext();
    }
 }
 if(NULL==H)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T=H=nn;
 }
 else if(0==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T->setNext(nn);
    T=nn;
 }
 else if(1==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    nn->setNext((temp->getNext()));
    temp->setNext(nn);
 }
 }

How to enable scrolling of content inside a modal?

.modal-body {
    max-height: 80vh;
    overflow-y: scroll;
}

it's works for me

DateTime vs DateTimeOffset

Most of the answers are good , but i thought of adding some more links of MSDN for more information

Making a triangle shape using xml definitions?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate
            android:fromDegrees="45"
            android:toDegrees="45"
            android:pivotX="-40%"
            android:pivotY="87%" >
            <shape
                android:shape="rectangle" >
                <stroke android:color="@android:color/transparent" android:width="0dp"/>
                <solid
                    android:color="#fff" />
            </shape>
        </rotate>
    </item>
</layer-list>

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Draw a connecting line between two elements

VisJS supports this with its Arrows example, that supports draggable elements.

It also supports editable connections, with its Interaction Events example.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

jEdit:

With the keyboard: press Alt-\ (Opt-\ in Mac OS X) to toggle between rectangular and normal selection mode; then use Shift plus arrow keys to extend selection. You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.

With the mouse: Either use Alt-\ (Opt-\ in Mac OS X) as above to toggle rectangular selection mode, then drag as usual; or Ctrl-drag (Cmd-drag in Mac OS X). You can switch back to regular selection mode with another Alt-\ (Opt-\ in Mac OS X), if desired.

Actually, you can even make a non-rectangular selection the normal way and then hit Alt-\ (Opt-\ in Mac OS X) to convert it into a rectangular one.