Programs & Examples On #Typeerror

A TypeError is a specific type of error raised when an operation or function is applied to an object of inappropriate type. You might encounter it in Python or JavaScript.

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

There are a few things you can try to get this working.

  1. Be ABSOLUTELY sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file.

  2. Be sure that you've included the script after you've included jQuery, as it is most certainly dependant upon that.

Other than that, I checked out the API and you're definitely doing everything right as far as I can see. Best of luck friend!

EDIT: Ensure you close your script tag. There's an answer below that points to that being the solution.

TypeError: module.__init__() takes at most 2 arguments (3 given)

In my case where I had the problem I was referring to a module when I tried extending the class.

import logging
class UserdefinedLogging(logging):

If you look at the Documentation Info, you'll see "logging" displayed as module.

In this specific case I had to simply inherit the logging module to create an extra class for the logging.

TypeError: $ is not a function when calling jQuery function

You can avoid confliction like this

var jq=jQuery.noConflict();
jq(document).ready(function(){  
  alert("Hi this will not conflict now");
  jq('selector').show();
});

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

I found my problem. The issue was that my integers were actually type numpy.int64.

How to overcome TypeError: unhashable type: 'list'

The reason you're getting the unhashable type: 'list' exception is because k = list[0:j] sets k to be a "slice" of the list, which is logically another, often shorter, list. What you need is to get just the first item in list, written like so k = list[0]. The same for v = list[j + 1:] which should just be v = list[2] for the third element of the list returned from the call to readline.split(" ").

I noticed several other likely problems with the code, of which I'll mention a few. A big one is you don't want to (re)initialize d with d = {} for each line read in the loop. Another is it's generally not a good idea to name variables the same as any of the built-ins types because it'll prevent you from being able to access one of them if you need it — and it's confusing to others who are used to the names designating one of these standard items. For that reason, you ought to rename your variable list variable something different to avoid issues like that.

Here's a working version of your with these changes in it, I also replaced the if statement expression you used to check to see if the key was already in the dictionary and now make use of a dictionary's setdefault() method to accomplish the same thing a little more succinctly.

d = {}
with open("nameerror.txt", "r") as file:
    line = file.readline().rstrip()
    while line:
        lst = line.split() # Split into sequence like ['AAA', 'x', '111'].
        k, _, v = lst[:3]  # Get first and third items.
        d.setdefault(k, []).append(v)
        line = file.readline().rstrip()

print('d: {}'.format(d))

Output:

d: {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

TypeError: 'list' object cannot be interpreted as an integer

Error messages usually mean precisely what they say. So they must be read very carefully. When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is. It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.

So the question is: why does the interpreter seem to want to interpret your list as an integer? The answer is that you are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in myList instead.

Uncaught Typeerror: cannot read property 'innerHTML' of null

Update:

The question doesn't ask for jquery. So lets do it without jquery:

document.addEventListener("DOMContentLoaded", function(event) { 
    //Do work
});

Note this method will not work on IE8.

Old Answer:

You are calling this script before DOM is ready. If you write this code into jquery's $(function() method it will work.

Slick Carousel Uncaught TypeError: $(...).slick is not a function

It's hard to tell without looking at the full code but this type of error

Uncaught TypeError: $(...).slick is not a function

Usually means that you either forgot to include slick.js in the page or you included it before jquery.

Make sure jquery is the first js file and you included the slick.js library after it.

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

Python TypeError: not enough arguments for format string

You need to put the format arguments into a tuple (add parentheses):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

What you currently have is equivalent to the following:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

Example:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

Javascript "Not a Constructor" Exception while creating objects

Sometimes it is just how you export and import it. For this error message it could be, that the default keyword is missing.

export default SampleClass {}

Where you instantiate it:

import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();

Option 2, with curly braces:

export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.

TypeError: 'builtin_function_or_method' object is not subscriptable

instead of writing listb.pop[0] write

listb.pop()[0]
         ^
         |

TypeError: not all arguments converted during string formatting python

For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.

x = (f"{id}", f"{name}", f"{age}")
print(x) 

Python TypeError must be str not int

you need to cast int to str before concatenating. for that use str(temperature). Or you can print the same output using , if you don't want to convert like this.

print("the furnace is now",temperature , "degrees!")

Uncaught TypeError: Cannot read property 'value' of undefined

Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

In my case I was using ClassName.

getComputedStyle( document.getElementsByClassName(this_id)) //error

It will also work without 2nd argument " ".

Here is my complete running code :

function changeFontSize(target) {

  var minmax = document.getElementById("minmax");

  var computedStyle = window.getComputedStyle
        ? getComputedStyle(minmax) // Standards
        : minmax.currentStyle;     // Old IE

  var fontSize;

  if (computedStyle) { // This will be true on nearly all browsers
      fontSize = parseFloat(computedStyle && computedStyle.fontSize);

      if (target == "sizePlus") {
        if(fontSize<20){
        fontSize += 5;
        }

      } else if (target == "sizeMinus") {
        if(fontSize>15){
        fontSize -= 5;
        }
      }
      minmax.style.fontSize = fontSize + "px";
  }
}


onclick= "changeFontSize(this.id)"

TypeError: unsupported operand type(s) for /: 'str' and 'str'

There is another error with the forwars=d slash.

if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

TypeError: unsupported operand type(s) for -: 'list' and 'list'

The operations needed to be performed, require numpy arrays either created via

np.array()

or can be converted from list to an array via

np.stack()

As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

TypeError: coercing to Unicode: need string or buffer

Here is the best way I found for Python 2:

def inplace_change(file,old,new):
        fin = open(file, "rt")
        data = fin.read()
        data = data.replace(old, new)
        fin.close()

        fin = open(file, "wt")
        fin.write(data)
        fin.close()

An example:

inplace_change('/var/www/html/info.txt','youtub','youtube')

Uncaught TypeError: (intermediate value)(...) is not a function

When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.

class C {
  x = () => 1; 
 };
 
class CC extends C {
  x = (foo) =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

this is solved by defining the method of the parent class without arrow functions

class C {
  x() { 
    return 1; 
  }; 
 };
 
class CC extends C {
  x = foo =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

that is referring to the expected dtype of your image
"image".astype('float32') should solve your issue

super() raises "TypeError: must be type, not classobj" for new-style class

FWIW and though I'm no Python guru I got by with this

>>> class TextParser(HTMLParser):
...    def handle_starttag(self, tag, attrs):
...        if tag == "b":
...            self.all_data.append("bold")
...        else:
...            self.all_data.append("other")
...     
...         
>>> p = TextParser()
>>> p.all_data = []
>>> p.feed(text)
>>> print p.all_data
(...)

Just got me the parse results back as needed.

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

How to link an image and target a new window

you can do like this

<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>

find this page

http://www.corelangs.com/html/links/new-window.html

goreb

Capitalize the first letter of both words in a two word string

Try:

require(Hmisc)
sapply(name, function(x) {
  paste(sapply(strsplit(x, ' '), capitalize), collapse=' ')
})

How to play .wav files with java

Finally I managed to do the following and it works fine

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class MakeSound {

    private final int BUFFER_SIZE = 128000;
    private File soundFile;
    private AudioInputStream audioStream;
    private AudioFormat audioFormat;
    private SourceDataLine sourceLine;

    /**
     * @param filename the name of the file that is going to be played
     */
    public void playSound(String filename){

        String strFilename = filename;

        try {
            soundFile = new File(strFilename);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        try {
            audioStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        audioFormat = audioStream.getFormat();

        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        try {
            sourceLine = (SourceDataLine) AudioSystem.getLine(info);
            sourceLine.open(audioFormat);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        sourceLine.start();

        int nBytesRead = 0;
        byte[] abData = new byte[BUFFER_SIZE];
        while (nBytesRead != -1) {
            try {
                nBytesRead = audioStream.read(abData, 0, abData.length);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (nBytesRead >= 0) {
                @SuppressWarnings("unused")
                int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
            }
        }

        sourceLine.drain();
        sourceLine.close();
    }
}

Using DISTINCT and COUNT together in a MySQL Query

FYI, this is probably faster,

SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp

than this,

SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

Formatting code snippets for blogging on Blogger

I use SyntaxHighlighter with my Blogger powered blog. The actual site is hosted on my own server rather than Blogger's though (Blogger has an option of ftping posts to your own site), but having your own domain and web hosting only costs a couple of dollars a month.

How to update a git clone --mirror?

This is the command that you need to execute on the mirror:

git remote update

Using number_format method in Laravel

If you are using Eloquent, in your model put:

public function getPriceAttribute($price)
{
    return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}

Where getPriceAttribute is your field on database. getSomethingAttribute.

How to save the output of a console.log(object) to a file?

There is another open-source tool that allows you to save all console.log output in a file on your server - JS LogFlush (plug!).

JS LogFlush is an integrated JavaScript logging solution which include:

  • cross-browser UI-less replacement of console.log - on client side.
  • log storage system - on server side.

Demo

'mvn' is not recognized as an internal or external command, operable program or batch file

First of all make sure you java is working or not run this command in cmd

 C:\>java -version

if it's working it will show this output:-

C:\>java -version
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) Client VM (build 25.74-b02, mixed mode)

step 1. First set your java_home[C:\Program Files\Java\jdk1.8.0_74] path in user variable.

step 2. Then set MAVEN_HOME[C:\Program Files\maven\apache-maven-3.3.9] path in system variable and make sure your maven folder should be present in C folder only.

step 3. Then set M2 path in system variable and give maven bin location there i.e.[C:\Program Files\maven\apache-maven-3.3.9\bin].

Step 4. Then set new system variable i.e. variable name = MAVEN_OPTS in and variable value =-Xms256m -Xmx512m

Step 5. Then edit path/system path variable be care full don't remove anything from there simply add java_home path i.e=;C:\Program Files\Java\jdk1.8.0_74 and M2 variable=;%M2% in the end.

Step 6. To make sure maven is now working or not run this command in cmd

> C:\>mvn --version

if it's working it will show this result :-

Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-
7+05:30)
Maven home: C:\Program Files\maven\apache-maven-3.3.9\bin\..
Java version: 1.8.0_74, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_74\jre
Default locale: en_IN, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "dos"

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

Find nearest latitude/longitude with an SQL query

The original answers to the question are good, but newer versions of mysql (MySQL 5.7.6 on) support geo queries, so you can now use built in functionality rather than doing complex queries.

You can now do something like:

select *, ST_Distance_Sphere( point ('input_longitude', 'input_latitude'), 
                              point(longitude, latitude)) * .000621371192 
          as `distance_in_miles` 
  from `TableName`
having `distance_in_miles` <= 'input_max_distance'
 order by `distance_in_miles` asc

The results are returned in meters. So if you want in KM simply use .001 instead of .000621371192 (which is for miles).

MySql docs are here

Django Rest Framework File Upload

If anyone interested in the easiest example with ModelViewset for Django Rest Framework.

The Model is,

class MyModel(models.Model):
    name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True)
    imageUrl = models.FileField(db_column='image_url', blank=True, null=True, upload_to='images/')

    class Meta:
        managed = True
        db_table = 'MyModel'

The Serializer,

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = "__all__"

And the View is,

class MyModelView(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Test in Postman,

enter image description here

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

I believe the problem with all the existing ideas is that they are probably unique, but not definitely unique (as pointed out in Dariusz Walczak's reply to loletech). I have a solution that actually is unique. It requires that your script have some sort of memory. For me this is a SQL database. You could also simply write to a file somewhere. There are two implementations:

First method: have TWO fields rather than 1 that provide uniqueness. The first field is an ID number that is not random but is unique (The first ID is 1, the second 2...). If you are using SQL, just define the ID field with the AUTO_INCREMENT property. The second field is not unique but is random. This can be generated with any of the other techniques people have already mentioned. Scott's idea was good, but md5 is convenient and probably good enough for most purposes:

$random_token = md5($_SERVER['HTTP_USER_AGENT'] . time());

Second method: Basically the same idea, but initially pick a maximum number of strings that will ever be generated. This could just be a really big number like a trillion. Then do the same thing, generate an ID, but zero pad it so that all IDs are the same number of digits. Then just concatenate the ID with the random string. It will be random enough for most purposes, but the ID section will ensure that it is also unique.

How to catch SQLServer timeout exceptions

Whats the value for the SqlException.ErrorCode property? Can you work with that?

When having timeouts, it may be worth checking the code for -2146232060.

I would set this up as a static const in your data code.

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Can I get Unix's pthread.h to compile in Windows?

As @Ninefingers mentioned, pthreads are unix-only. Posix only, really.

That said, Microsoft does have a library that duplicates pthreads:

Microsoft Windows Services for UNIX Version 3.5

Library Download

no target device found android studio 2.1.1

After i changed my target to usb. i had to create the file /etc/udev/rules.d/51-android.rules with vendor details .Click for Solution

Is there a label/goto in Python?

To answer the @ascobol's question using @bobince's suggestion from the comments:

for i in range(5000):
    for j in range(3000):
        if should_terminate_the_loop:
           break
    else: 
        continue # no break encountered
    break

The indent for the else block is correct. The code uses obscure else after a loop Python syntax. See Why does python use 'else' after for and while loops?

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

How does Python return multiple values from a function?

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

Place cursor at the end of text in EditText

For ViewModel, LiveData and Data binding

I needed this functionality for EditText with multiline support in my notes app. I wanted the cursor at the end of the text when the user navigates to the fragment that has note text.

The solution suggested by the djleop comes close. But the problem with this is that, if the user puts the cursor somewhere in the middle of the text for editing and starts typing, the cursor would jump to the end of text again. This happened because the LiveData would emit the new value and cursor would jump to the end of the text again resulting in user not able to edit the text somewhere in the middle.

To solve this, I use MediatorLiveData and assign it the length of String only once using a flag. This will cause the LiveData to read the value only once, that is, when the user navigates to the fragment. After that the user can place the cursor anywhere they want to edit the text there.

ViewModel

private var accessedPosition: Boolean = false

val cursorPosition = MediatorLiveData<Event<Int>>().apply {
    addSource(yourObject) { value ->
        if(!accessedPosition) {
            setValue(Event(yourObject.note.length))
            accessedPosition = true
        }
    }
}

Here, yourObject is another LiveData retrieved from the database that holds the String text that you are displaying in the EditText.

Then bind this MediatorLiveData to your EditText using binding adapter.

XML

Uses two-way data binding for displaying text as well as accepting the text input.

<!-- android:text must be placed before cursorPosition otherwise we'll get IndexOutOfBounds exception-->
<EditText
    android:text="@={viewModel.noteText}"
    cursorPosition="@{viewModel.cursorPosition}" />

Binding Adapter

@BindingAdapter("cursorPosition")
fun bindCursorPosition(editText: EditText, event: Event<Int>?) {
    event?.getContentIfNotHandled()?.let { editText.setSelection(it) }
}

Event class

The Event class here is like a SingleLiveEvent written by Jose Alcérreca from Google. I use it here to take care of screen rotation. Using the single Event will make sure that the cursor won't jump to the end of text when the user is editing the text somewhere in the middle and the screen rotates. It will maintain the same position when the screen rotates.

Here's the Event class:

open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peekContent(): T = content
}

This is the solution that works for me and provides good user experience. Hope it helps in your projects too.

How to check if a column exists in Pandas

To check if one or more columns all exist, you can use set.issubset, as in:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

As @brianpck points out in a comment, set([]) can alternatively be constructed with curly braces,

if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.

Or, you can use a list comprehension, as in:

if all([item in df.columns for item in ['A','C']]):

Scroll back to the top of scrollable div

For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function.

Example:

$('#elem').show();
$('#elem').scrollTop(0);

How to add /usr/local/bin in $PATH on Mac

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin

One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH should be double-quoted as "$PATH".

Get root view from current activity

Just incase Someone needs an easier way:

The following code gives a view of the whole activity:

View v1 = getWindow().getDecorView().getRootView();

To get a certian view in the activity,for example an imageView inside the activity, simply add the id of that view you want to get:

View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1);

Hope this helps somebody

Why is "cursor:pointer" effect in CSS not working

My problem was using cursor: 'pointer' mistakenly instead of cursor: pointer. So, make sure you are not adding single or double quotes around pointer.

How to install multiple python packages at once using pip

You can install packages listed in a text file called requirements file. For example, if you have a file called req.txt containing the following text:

Django==1.4
South==0.7.3

and you issue at the command line:

pip install -r req.txt

pip will install packages listed in the file at the specific revisions.

How to get first element in a list of tuples?

Those are tuples, not sets. You can do this:

l1 = [(1, u'abc'), (2, u'def')]
l2 = [(tup[0],) for tup in l1]
l2
>>> [(1,), (2,)]

How to correctly assign a new string value?

Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

But you can call functions to help achieve what you want.

The strncpy() function could be used here. For maximum safety I suggest following this pattern:

strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case

Also have a look at the strncat() and memcpy() functions.

Initialize a string variable in Python: "" or None?

Since both None and "" are false, you can do both. See 6.1. Truth Value Testing.

Edit

To answer the question in your edit: No, you can assign a different type.

>>> a = ""
>>> type(a)
<type 'str'>
>>> a = 1
>>> type(a)
<type 'int'>

How do you force a CIFS connection to unmount

Try umount -f /mnt/share. Works OK with NFS, never tried with cifs.

Also, take a look at autofs, it will mount the share only when accessed, and will unmount it afterworlds.

There is a good tutorial at www.howtoforge.net

How to filter a RecyclerView with a SearchView

I don't know why everyone is using 2 copies of the same list to solve this. This uses too much RAM...

Why not just hide the elements that are not found, and simply store their index in a Set to be able to restore them later? That's much less RAM especially if your objects are quite large.

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.SampleViewHolders>{
    private List<MyObject> myObjectsList; //holds the items of type MyObject
    private Set<Integer> foundObjects; //holds the indices of the found items

    public MyRecyclerViewAdapter(Context context, List<MyObject> myObjectsList)
    {
        this.myObjectsList = myObjectsList;
        this.foundObjects = new HashSet<>();
        //first, add all indices to the indices set
        for(int i = 0; i < this.myObjectsList.size(); i++)
        {
            this.foundObjects.add(i);
        }
    }

    @NonNull
    @Override
    public SampleViewHolders onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.my_layout_for_staggered_grid, null);
        MyRecyclerViewAdapter.SampleViewHolders rcv = new MyRecyclerViewAdapter.SampleViewHolders(layoutView);
        return rcv;
    }

    @Override
    public void onBindViewHolder(@NonNull SampleViewHolders holder, int position)
    {
        //look for object in O(1) in the indices set
        if(!foundObjects.contains(position))
        {
            //object not found => hide it.
            holder.hideLayout();
            return;
        }
        else
        {
            //object found => show it.
            holder.showLayout();
        }

        //holder.imgImageView.setImageResource(...)
        //holder.nameTextView.setText(...)
    }

    @Override
    public int getItemCount() {
        return myObjectsList.size();
    }

    public void findObject(String text)
    {
        //look for "text" in the objects list
        for(int i = 0; i < myObjectsList.size(); i++)
        {
            //if it's empty text, we want all objects, so just add it to the set.
            if(text.length() == 0)
            {
                foundObjects.add(i);
            }
            else
            {
                //otherwise check if it meets your search criteria and add it or remove it accordingly
                if (myObjectsList.get(i).getName().toLowerCase().contains(text.toLowerCase()))
                {
                    foundObjects.add(i);
                }
                else
                {
                    foundObjects.remove(i);
                }
            }
        }
        notifyDataSetChanged();
    }

    public class SampleViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener
    {
        public ImageView imgImageView;
        public TextView nameTextView;

        private final CardView layout;
        private final CardView.LayoutParams hiddenLayoutParams;
        private final CardView.LayoutParams shownLayoutParams;

        
        public SampleViewHolders(View itemView)
        {
            super(itemView);
            itemView.setOnClickListener(this);
            imgImageView = (ImageView) itemView.findViewById(R.id.some_image_view);
            nameTextView = (TextView) itemView.findViewById(R.id.display_name_textview);

            layout = itemView.findViewById(R.id.card_view); //card_view is the id of my androidx.cardview.widget.CardView in my xml layout
            //prepare hidden layout params with height = 0, and visible layout params for later - see hideLayout() and showLayout()
            hiddenLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            hiddenLayoutParams.height = 0;
            shownLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        @Override
        public void onClick(View view)
        {
            //implement...
        }

        private void hideLayout() {
            //hide the layout
            layout.setLayoutParams(hiddenLayoutParams);
        }

        private void showLayout() {
            //show the layout
            layout.setLayoutParams(shownLayoutParams);
        }
    }
}

And I simply have an EditText as my search box:

cardsSearchTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                myViewAdapter.findObject(editable.toString().toLowerCase());
            }
        });

Result:

Search example gif

Removing multiple classes (jQuery)

$("element").removeClass("class1 class2");

From removeClass(), the class parameter:

One or more CSS classes to remove from the elements, these are separated by spaces.

How to start Activity in adapter?

First Solution:

You can call start activity inside your adapter like this:

public class YourAdapter extends Adapter {
     private Context context;

     public YourAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

Second Solution:

You can call onClickListener of your button out of the YourAdapter class. Follow these steps:

Craete an interface like this:

public YourInterface{
         public void  yourMethod(args...);
}

Then inside your adapter:

    public YourAdapter extends BaseAdapter{
               private YourInterface listener;

           public YourAdapter (Context context, YourInterface listener){
                    this.listener = listener;
                    this.context = context;
           }

           public View getView(...){
                View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 listener.yourMethod(args);
             }
         });
}

And where you initiate yourAdapter will be like this:

YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
            startActivity(...);
        });

This link can be useful for you.

Secure hash and salt for PHP passwords

I would not store the password hashed in two different ways, because then the system is at least as weak as the weakest of the hash algorithms in use.

Spring profiles and testing

public class LoginTest extends BaseTest {
    @Test
    public void exampleTest( ){ 
        // Test
    }
}

Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }

MyActiveProfileResolver can contain any logic required to determine which profile to use:

public class MyActiveProfileResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        // This can contain any custom logic to determine which profiles to use
        return new String[] { "exampleProfile" };
    }
}

This sets the profile which is then used to resolve dependencies required by the test.

How to get post slug from post in WordPress?

You can retrieve it from the post object like so:

global $post;
$post->post_name;

What is the Simplest Way to Reverse an ArrayList?

Simple way is that you have "Collections" in Java. You just need to call it and use "reverse()" method of it.

Example usage:

ArrayList<Integer> yourArrayList = new ArrayList<>();
    yourArrayList.add(1);
    yourArrayList.add(2);
    yourArrayList.add(3);
    //yourArrayList is: 1,2,3

Collections.reverse(yourArrayList); 
    // Now, yourArrayList is: 3,2,1

For more question: @canerkaseler

How to specify HTTP error code?

You can use res.send('OMG :(', 404); just res.send(404);

Pandas create empty DataFrame with only column names

Are you looking for something like this?

    COLUMN_NAMES=['A','B','C','D','E','F','G']
    df = pd.DataFrame(columns=COLUMN_NAMES)
    df.columns

   Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')

How to install XNA game studio on Visual Studio 2012?

I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.

You need to remove the files extensionSdks.en-US.cache and extensions.en-US.cache from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions folder. These files are rebuilt the next time you launch

If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE directory (assuming you are on a 64 bit machine). The log file generated is located here:

%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml

Python constructor and default value

I would try:

self.wordList = list(wordList)

to force it to make a copy instead of referencing the same object.

Can't install laravel installer via composer

On centos 7 I have used:

yum install php-pecl-zip

because any other solution didn't work for me.

Using if-else in JSP

You may try this example:

_x000D_
_x000D_
<form>_x000D_
  <h1>Hello! I'm duke! What's you name?</h1>_x000D_
  <input type="text" name="user">_x000D_
  <br>_x000D_
  <br>_x000D_
  <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;_x000D_
  <input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
_x000D_
_x000D_

Upload artifacts to Nexus, without Maven

Using curl:

curl -v \
    -F "r=releases" \
    -F "g=com.acme.widgets" \
    -F "a=widget" \
    -F "v=0.1-1" \
    -F "p=tar.gz" \
    -F "file=@./widget-0.1-1.tar.gz" \
    -u myuser:mypassword \
    http://localhost:8081/nexus/service/local/artifact/maven/content

You can see what the parameters mean here: https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-

To make the permissions for this work, I created a new role in the admin GUI and I added two privileges to that role: Artifact Download and Artifact Upload. The standard "Repo: All Maven Repositories (Full Control)"-role is not enough. You won't find this in the REST API documentation that comes bundled with the Nexus server, so these parameters might change in the future.

On a Sonatype JIRA issue, it was mentioned that they "are going to overhaul the REST API (and the way it's documentation is generated) in an upcoming release, most likely later this year".

Function Pointers in Java

You can use reflection to do it.

Pass as parameter the object and the method name (as a string) and then invoke the method. For example:

Object methodCaller(Object theObject, String methodName) {
   return theObject.getClass().getMethod(methodName).invoke(theObject);
   // Catch the exceptions
}

And then use it as in:

String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");

Of course, check all exceptions and add the needed casts.

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

How can I access Google Sheet spreadsheets only with Javascript?

Jan 2018 UPDATE: When I answered this question last year, I neglected to mention a third way to access Google APIs with JavaScript, and that would be from Node.js apps using its client library, so I added it below.

It's Mar 2017, and most of the answers here are outdated -- the accepted answer now refers to a library that uses an older API version. A more current answer: you can access most Google APIs with JavaScript only. Google provides 3 ways to do this today:

  1. As mentioned in the answer by Dan Dascalescu, you can use Google Apps Script, the JavaScript-in-Google's-cloud solution. That is, non-Node server-side JS apps outside the browser that run on Google servers.
  2. You can also use the Google APIs Client Library for JavaScript to access the latest Google Sheets REST API on the client side.
  3. The 3rd way to access Google APIs with JavaScript is from Node.js apps using its client library. It works similarly to using the JavaScript (client) client library described just above, only you'll be accessing the same API from the server-side. Here's the Node.js Quickstart example for Sheets. You may find the Python-based videos above to be even more useful as they too access the API from the server-side.

When using the REST API, you need to manage & store your source code as well as perform authorization by rolling your own auth code (see samples above). Apps Script handles this on your behalf, managing the data (reducing the "pain" as mentioned by Ape-inago in their answer), and your code is stored on Google's servers. But your functionality is restricted to what services App Script provides whereas the REST API gives developers much broader access to the API. But hey, it's good to have choices, right? In summary, to answer the OP original question, instead of zero, developers have three ways of accessing Google Sheets using JavaScript.

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

WCF error - There was no endpoint listening at

Different case but may help someone,

In my case Window firewall was enabled on Server,

Two thinks can be done,

1) Disable windows firewall (your on risk but it will get thing work)

2) Add port in inbound rule.

Thanks .

Could not open input file: composer.phar

dont use php composer.phar self-update
First go to Your project directory
simply use composer.phar self-update
This works for me

How to change a TextView's style at runtime

i found textView.setTypeface(Typeface.DEFAULT_BOLD); to be the simplest method.

How to update the constant height constraint of a UIView programmatically?

Change HeightConstraint and WidthConstraint Without creating IBOutlet.

Note: Assign height or width constraint in Storyboard or XIB file. after fetching this Constraint using this extension.

You can use this extension to fetch a height and width Constraint:

extension UIView {

var heightConstraint: NSLayoutConstraint? {
    get {
        return constraints.first(where: {
            $0.firstAttribute == .height && $0.relation == .equal
        })
    }
    set { setNeedsLayout() }
}

var widthConstraint: NSLayoutConstraint? {
    get {
        return constraints.first(where: {
            $0.firstAttribute == .width && $0.relation == .equal
        })
    }
    set { setNeedsLayout() }
}

}

You can use:

yourView.heightConstraint?.constant = newValue 

Space between two divs

DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

Return single column from a multi-dimensional array

If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)

$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));

Most Pythonic way to provide global configuration variables in config.py?

please check out the IPython configuration system, implemented via traitlets for the type enforcement you are doing manually.

Cut and pasted here to comply with SO guidelines for not just dropping links as the content of links changes over time.

traitlets documentation

Here are the main requirements we wanted our configuration system to have:

Support for hierarchical configuration information.

Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override.

Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (Foo.Bar.Bam.name). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another. Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a 1 in a config file is the integer ‘1’, while a '1' is a string.

A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry.

Type checking and validation that doesn’t require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don’t always know everything that needs to be configured when a program starts.

To acheive this they basically define 3 object classes and their relations to each other:

1) Configuration - basically a ChainMap / basic dict with some enhancements for merging.

2) Configurable - base class to subclass all things you'd wish to configure.

3) Application - object that is instantiated to perform a specific application function, or your main application for single purpose software.

In their words:

Application: Application

An application is a process that does a specific job. The most obvious application is the ipython command line program. Each application reads one or more configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object.

Applications always have a log attribute that is a configured Logger. This allows centralized logging configuration per-application. Configurable: Configurable

A configurable is a regular Python class that serves as a base class for all main classes in an application. The Configurable base class is lightweight and only does one things.

This Configurable is a subclass of HasTraits that knows how to configure itself. Class level traits with the metadata config=True become values that can be configured from the command line and configuration files.

Developers create Configurable subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created.

Relay access denied on sending mail, Other domain outside of network

Set your SMTP auth to true if using the PHPmailer class:

$mail->SMTPAuth = true;

Remove first Item of the array (like popping from stack)

The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I had this issue trying to output Unicode characters to stdout, but with sys.stdout.write, rather than print (so that I could support output to a different file as well).

From BeautifulSoup's own documentation, I solved this with the codecs library:

import sys
import codecs

def main(fIn, fOut):
    soup = BeautifulSoup(fIn)
    # Do processing, with data including non-ASCII characters
    fOut.write(unicode(soup))

if __name__ == '__main__':
    with (sys.stdin) as fIn: # Don't think we need codecs.getreader here
        with codecs.getwriter('utf-8')(sys.stdout) as fOut:
            main(fIn, fOut)

jquery $.each() for objects

$.each() works for objects and arrays both:

var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };

$.each(data.programs, function (i) {
    $.each(data.programs[i], function (key, val) {
        alert(key + val);
    });
});

...and since you will get the current array element as second argument:

$.each(data.programs, function (i, currProgram) {
    $.each(currProgram, function (key, val) {
        alert(key + val);
    });
});

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

You can do this easily with the KoGrid plugin for KnockoutJS.

<script type="text/javascript">
    $(function () {
        window.viewModel = {
            myObsArray: ko.observableArray([
                { id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
                { id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
                { id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
                { id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
            ])
        };

        ko.applyBindings(viewModel);
    });
</script>

<div data-bind="koGrid: { data: myObsArray }">

Sample

Get host domain from URL?

The best way, and the right way to do it is using Uri.Authority field

Load and use Uri like so :

Uri NewUri;

if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
     Console.Writeline(NewUri.Authority);
}

Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com

Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com

Input : http://localhost/default.aspx?id=12345
Output : localhost

If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx

How do I call a non-static method from a static method in C#?

You just need to provide object reference . Please provide your class name in the position.

private static void data2()
{
    <classname> c1 = new <classname>();
    c1. data1();
}

Variable declaration in a header file

The key is to keep the declarations of the variable in the header file and source file the same.

I use this trick

------sample.c------
#define sample_c
#include sample.h

(rest of sample .c)

------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif

EXTERN int x;

Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.

When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

String to Dictionary in Python

Use ast.literal_eval to evaluate Python literals. However, what you have is JSON (note "true" for example), so use a JSON deserializer.

>>> import json
>>> s = """{"id":"123456789","name":"John Doe","first_name":"John","last_name":"Doe","link":"http:\/\/www.facebook.com\/jdoe","gender":"male","email":"jdoe\u0040gmail.com","timezone":-7,"locale":"en_US","verified":true,"updated_time":"2011-01-12T02:43:35+0000"}"""
>>> json.loads(s)
{u'first_name': u'John', u'last_name': u'Doe', u'verified': True, u'name': u'John Doe', u'locale': u'en_US', u'gender': u'male', u'email': u'[email protected]', u'link': u'http://www.facebook.com/jdoe', u'timezone': -7, u'updated_time': u'2011-01-12T02:43:35+0000', u'id': u'123456789'}

AttributeError: 'tuple' object has no attribute

class list_benefits(object):
    def __init__(self):
        self.s1 = "More organized code"
        self.s2 = "More readable code"
        self.s3 = "Easier code reuse"

def build_sentence():
        obj=list_benefits()
        print obj.s1 + " is a benefit of functions!"
        print obj.s2 + " is a benefit of functions!"
        print obj.s3 + " is a benefit of functions!"

print build_sentence()

I know it is late answer, maybe some other folk can benefit If you still want to call by "attributes", you could use class with default constructor, and create an instance of the class as mentioned in other answers

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

You get this exact error should you pass an old school .xls file into this API. Save the .xls as a .xlsx and then it will work.

How do you get the path to the Laravel Storage folder?

use this artisan command for create shortcut in public folder

php artisan storage:link

Than you will able to access posted img or file

Keyboard shortcuts with jQuery

    <script type="text/javascript">
        $(document).ready(function(){
            $("#test").keypress(function(e){
                if (e.which == 103) 
                {
                    alert('g'); 
                };
            });
        });
    </script>

    <input type="text" id="test" />

this site says 71 = g but the jQuery code above thought otherwise

Capital G = 71, lowercase is 103

When are static variables initialized?

static variable

  • It is a variable which belongs to the class and not to object(instance)
  • Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
  • These variables will be initialized first, before the initialization of any instance variables
  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

How to check if a std::thread is still running?

If you are willing to make use of C++11 std::async and std::future for running your tasks, then you can utilize the wait_for function of std::future to check if the thread is still running in a neat way like this:

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    /* Run some task on new thread. The launch policy std::launch::async
       makes sure that the task is run asynchronously on a new thread. */
    auto future = std::async(std::launch::async, [] {
        std::this_thread::sleep_for(3s);
        return 8;
    });

    // Use wait_for() with zero milliseconds to check thread status.
    auto status = future.wait_for(0ms);

    // Print status.
    if (status == std::future_status::ready) {
        std::cout << "Thread finished" << std::endl;
    } else {
        std::cout << "Thread still running" << std::endl;
    }

    auto result = future.get(); // Get result.
}

If you must use std::thread then you can use std::promise to get a future object:

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    // Create a promise and get its future.
    std::promise<bool> p;
    auto future = p.get_future();

    // Run some task on a new thread.
    std::thread t([&p] {
        std::this_thread::sleep_for(3s);
        p.set_value(true); // Is done atomically.
    });

    // Get thread status using wait_for as before.
    auto status = future.wait_for(0ms);

    // Print status.
    if (status == std::future_status::ready) {
        std::cout << "Thread finished" << std::endl;
    } else {
        std::cout << "Thread still running" << std::endl;
    }

    t.join(); // Join thread.
}

Both of these examples will output:

Thread still running

This is of course because the thread status is checked before the task is finished.

But then again, it might be simpler to just do it like others have already mentioned:

#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    std::atomic<bool> done(false); // Use an atomic flag.

    /* Run some task on a new thread.
       Make sure to set the done flag to true when finished. */
    std::thread t([&done] {
        std::this_thread::sleep_for(3s);
        done = true;
    });

    // Print status.
    if (done) {
        std::cout << "Thread finished" << std::endl;
    } else {
        std::cout << "Thread still running" << std::endl;
    }

    t.join(); // Join thread.
}

Edit:

There's also the std::packaged_task for use with std::thread for a cleaner solution than using std::promise:

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    // Create a packaged_task using some task and get its future.
    std::packaged_task<void()> task([] {
        std::this_thread::sleep_for(3s);
    });
    auto future = task.get_future();

    // Run task on new thread.
    std::thread t(std::move(task));

    // Get thread status using wait_for as before.
    auto status = future.wait_for(0ms);

    // Print status.
    if (status == std::future_status::ready) {
        // ...
    }

    t.join(); // Join thread.
}

Reduce git repository size

This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.

You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules directory. To make redundant submodule files gone away, see this question.

However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules, and do a, for example, git gc --aggressive --prune.

These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.

In git, what is the difference between merge --squash and rebase?

Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branchenter image description here

Merge Squash: retains the changes but omits the individual commits from history enter image description here

Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master

enter image description here

More on here

Removing leading zeroes from a field in a SQL statement

select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)

Finding all the subsets of a set

one simple way would be the following pseudo code:

Set getSubsets(Set theSet)
{
  SetOfSets resultSet = theSet, tempSet;


  for (int iteration=1; iteration < theSet.length(); iteration++)
    foreach element in resultSet
    {
      foreach other in resultSet
        if (element != other && !isSubset(element, other) && other.length() >= iteration)
          tempSet.append(union(element, other));
    }
    union(tempSet, resultSet)
    tempSet.clear()
  }

}

Well I'm not totaly sure this is right, but it looks ok.

Android ListView not refreshing after notifyDataSetChanged

In onResume() change this line

items = dbHelper.getItems(); //reload the items from database

to

items.addAll(dbHelper.getItems()); //reload the items from database

The problem is that you're never telling your adapter about the new items list. If you don't want to pass a new list to your adapter (as it seems you don't), then just use items.addAll after your clear(). This will ensure you are modifying the same list that the adapter has a reference to.

Accessing an array out of bounds gives no error, why?

If you change your program slightly:

#include <iostream>
using namespace std;
int main()
{
    int array[2];
    INT NOTHING;
    CHAR FOO[4];
    STRCPY(FOO, "BAR");
    array[0] = 1;
    array[1] = 2;
    array[3] = 3;
    array[4] = 4;
    cout << array[3] << endl;
    cout << array[4] << endl;
    COUT << FOO << ENDL;
    return 0;
}

(Changes in capitals -- put those in lower case if you're going to try this.)

You will see that the variable foo has been trashed. Your code will store values into the nonexistent array[3] and array[4], and be able to properly retrieve them, but the actual storage used will be from foo.

So you can "get away" with exceeding the bounds of the array in your original example, but at the cost of causing damage elsewhere -- damage which may prove to be very hard to diagnose.

As to why there is no automatic bounds checking -- a correctly written program does not need it. Once that has been done, there is no reason to do run-time bounds checking and doing so would just slow down the program. Best to get that all figured out during design and coding.

C++ is based on C, which was designed to be as close to assembly language as possible.

Get first and last day of month using threeten, LocalDate

YearMonth

For completeness, and more elegant in my opinion, see this use of YearMonth class.

YearMonth month = YearMonth.from(date);
LocalDate start = month.atDay(1);
LocalDate end   = month.atEndOfMonth();

For the first & last day of the current month, this becomes:

LocalDate start = YearMonth.now().atDay(1);
LocalDate end   = YearMonth.now().atEndOfMonth();

Get value from input (AngularJS)

If you want to get values in Javascript on frontend, you can use the native way to do it by using :

document.getElementsByName("movie")[0].value;

Where "movie" is the name of your input <input type="text" name="movie">

If you want to get it on angular.js controller, you can use;

$scope.movie

adding css file with jquery

Have you tried simply using the media attribute for you css reference?

<link rel="stylesheet" href="css/style2.css" media="print" type="text/css" />

Or set it to screen if you don't want the printed version to use the style:

<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />

This way you don't need to add it dynamically.

How to select a single column with Entity Framework?

You could use the LINQ select clause and reference the property that relates to your Name column.

"Stack overflow in line 0" on Internet Explorer

You can turn off the "Disable Script Debugging" option inside of Internet Explorer and start debugging with Visual Studio if you happen to have that around.

I've found that it is one of few ways to diagnose some of those IE specific issues.

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

What is a MIME type?

It is useful to think of MIME in the context of the client-server model. Clients and servers communicate over what is known as the HTTP protocol. In a http request or response, we can have a body. The Content-type or MIME type specifies what is the type of the body, like text/javascript or something else like audio, video, etc.

However, MIME types are not limited just to HTTP.

As the name suggests, MIME stands for Multipurpose Internet Mail Extensions. Originally, SMTP only supported ascii-encodings. However, there as a need for more. We could use MIME to slap a label on the content being transmitted or received.

CMake output/build directory

You should not rely on a hard coded build dir name in your script, so the line with ../Compile must be changed.

It's because it should be up to user where to compile.

Instead of that use one of predefined variables: http://www.cmake.org/Wiki/CMake_Useful_Variables (look for CMAKE_BINARY_DIR and CMAKE_CURRENT_BINARY_DIR)

Initializing a two dimensional std::vector

Let's say you want to initialize 2D vector, m*n, with initial value to be 0

we could do this

#include<iostream>
int main(){ 
    int m = 2, n = 5;

    vector<vector<int>> vec(m, vector<int> (n, 0));

    return 0;
}

ADB Shell Input Events

By adb shell input keyevent, either an event_code or a string will be sent to the device.

usage: input [text|keyevent]
  input text <string>
  input keyevent <event_code>

Some possible values for event_code are:

0 -->  "KEYCODE_UNKNOWN" 
1 -->  "KEYCODE_MENU" 
2 -->  "KEYCODE_SOFT_RIGHT" 
3 -->  "KEYCODE_HOME" 
4 -->  "KEYCODE_BACK" 
5 -->  "KEYCODE_CALL" 
6 -->  "KEYCODE_ENDCALL" 
7 -->  "KEYCODE_0" 
8 -->  "KEYCODE_1" 
9 -->  "KEYCODE_2" 
10 -->  "KEYCODE_3" 
11 -->  "KEYCODE_4" 
12 -->  "KEYCODE_5" 
13 -->  "KEYCODE_6" 
14 -->  "KEYCODE_7" 
15 -->  "KEYCODE_8" 
16 -->  "KEYCODE_9" 
17 -->  "KEYCODE_STAR" 
18 -->  "KEYCODE_POUND" 
19 -->  "KEYCODE_DPAD_UP" 
20 -->  "KEYCODE_DPAD_DOWN" 
21 -->  "KEYCODE_DPAD_LEFT" 
22 -->  "KEYCODE_DPAD_RIGHT" 
23 -->  "KEYCODE_DPAD_CENTER" 
24 -->  "KEYCODE_VOLUME_UP" 
25 -->  "KEYCODE_VOLUME_DOWN" 
26 -->  "KEYCODE_POWER" 
27 -->  "KEYCODE_CAMERA" 
28 -->  "KEYCODE_CLEAR" 
29 -->  "KEYCODE_A" 
30 -->  "KEYCODE_B" 
31 -->  "KEYCODE_C" 
32 -->  "KEYCODE_D" 
33 -->  "KEYCODE_E" 
34 -->  "KEYCODE_F" 
35 -->  "KEYCODE_G" 
36 -->  "KEYCODE_H" 
37 -->  "KEYCODE_I" 
38 -->  "KEYCODE_J" 
39 -->  "KEYCODE_K" 
40 -->  "KEYCODE_L" 
41 -->  "KEYCODE_M" 
42 -->  "KEYCODE_N" 
43 -->  "KEYCODE_O" 
44 -->  "KEYCODE_P" 
45 -->  "KEYCODE_Q" 
46 -->  "KEYCODE_R" 
47 -->  "KEYCODE_S" 
48 -->  "KEYCODE_T" 
49 -->  "KEYCODE_U" 
50 -->  "KEYCODE_V" 
51 -->  "KEYCODE_W" 
52 -->  "KEYCODE_X" 
53 -->  "KEYCODE_Y" 
54 -->  "KEYCODE_Z" 
55 -->  "KEYCODE_COMMA" 
56 -->  "KEYCODE_PERIOD" 
57 -->  "KEYCODE_ALT_LEFT" 
58 -->  "KEYCODE_ALT_RIGHT" 
59 -->  "KEYCODE_SHIFT_LEFT" 
60 -->  "KEYCODE_SHIFT_RIGHT" 
61 -->  "KEYCODE_TAB" 
62 -->  "KEYCODE_SPACE" 
63 -->  "KEYCODE_SYM" 
64 -->  "KEYCODE_EXPLORER" 
65 -->  "KEYCODE_ENVELOPE" 
66 -->  "KEYCODE_ENTER" 
67 -->  "KEYCODE_DEL" 
68 -->  "KEYCODE_GRAVE" 
69 -->  "KEYCODE_MINUS" 
70 -->  "KEYCODE_EQUALS" 
71 -->  "KEYCODE_LEFT_BRACKET" 
72 -->  "KEYCODE_RIGHT_BRACKET" 
73 -->  "KEYCODE_BACKSLASH" 
74 -->  "KEYCODE_SEMICOLON" 
75 -->  "KEYCODE_APOSTROPHE" 
76 -->  "KEYCODE_SLASH" 
77 -->  "KEYCODE_AT" 
78 -->  "KEYCODE_NUM" 
79 -->  "KEYCODE_HEADSETHOOK" 
80 -->  "KEYCODE_FOCUS" 
81 -->  "KEYCODE_PLUS" 
82 -->  "KEYCODE_MENU" 
83 -->  "KEYCODE_NOTIFICATION" 
84 -->  "KEYCODE_SEARCH" 
85 -->  "TAG_LAST_KEYCODE"

The sendevent utility sends touch or keyboard events, as well as other events for simulating the hardware events. Refer to this article for details: Android, low level shell click on screen.

Configure active profile in SpringBoot via Maven

You can run using the following command. Here I want to run using spring profile local:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"

Download file using libcurl in C/C++

The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.

This is more or less what it should look like (no libcurl available here to test)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

Updated: as suggested by @rsethc types.h and easy.h aren't present in current cURL versions anymore.

How to select a dropdown value in Selenium WebDriver using Java

Try this-

driver.findElement(By.name("period")).sendKeys("Last 52 Weeks");

dictionary update sequence element #0 has length 3; 2 is required

One of the fast ways to create a dict from equal-length tuples:

>>> t1 = (a,b,c,d)
>>> t2 = (1,2,3,4)
>>> dict(zip(t1, t2))
{'a':1, 'b':2, 'c':3, 'd':4, }

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

Deleting multiple columns based on column names in Pandas

I don't know what you mean by inefficient but if you mean in terms of typing it could be easier to just select the cols of interest and assign back to the df:

df = df[cols_of_interest]

Where cols_of_interest is a list of the columns you care about.

Or you can slice the columns and pass this to drop:

df.drop(df.ix[:,'Unnamed: 24':'Unnamed: 60'].head(0).columns, axis=1)

The call to head just selects 0 rows as we're only interested in the column names rather than data

update

Another method: It would be simpler to use the boolean mask from str.contains and invert it to mask the columns:

In [2]:
df = pd.DataFrame(columns=['a','Unnamed: 1', 'Unnamed: 1','foo'])
df

Out[2]:
Empty DataFrame
Columns: [a, Unnamed: 1, Unnamed: 1, foo]
Index: []

In [4]:
~df.columns.str.contains('Unnamed:')

Out[4]:
array([ True, False, False,  True], dtype=bool)

In [5]:
df[df.columns[~df.columns.str.contains('Unnamed:')]]

Out[5]:
Empty DataFrame
Columns: [a, foo]
Index: []

Remove duplicated rows

the general answer can be for example:

df <-  data.frame(rbind(c(2,9,6),c(4,6,7),c(4,6,7),c(4,6,7),c(2,9,6))))



new_df <- df[-which(duplicated(df)), ]

output:

      X1 X2 X3
    1  2  9  6
    2  4  6  7

Removing elements from an array in C

Interestingly array is randomly accessible by the index. And removing randomly an element may impact the indexes of other elements as well.

    int remove_element(int*from, int total, int index) {
            if((total - index - 1) > 0) {
                      memmove(from+i, from+i+1, sizeof(int)*(total-index-1));
            }
            return total-1; // return the new array size
    }

Note that memcpy will not work in this case because of the overlapping memory.

One of the efficient way (better than memory move) to remove one random element is swapping with the last element.

    int remove_element(int*from, int total, int index) {
            if(index != (total-1))
                    from[index] = from[total-1];
            return total; // **DO NOT DECREASE** the total here
    }

But the order is changed after the removal.

Again if the removal is done in loop operation then the reordering may impact processing. Memory move is one expensive alternative to keep the order while removing an array element. Another of the way to keep the order while in a loop is to defer the removal. It can be done by validity array of the same size.

    int remove_element(int*from, int total, int*is_valid, int index) {
            is_valid[index] = 0;
            return total-1; // return the number of elements
    }

It will create a sparse array. Finally, the sparse array can be made compact(that contains no two valid elements that contain invalid element between them) by doing some reordering.

    int sparse_to_compact(int*arr, int total, int*is_valid) {
            int i = 0;
            int last = total - 1;
            // trim the last invalid elements
            for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements from last

            // now we keep swapping the invalid with last valid element
            for(i=0; i < last; i++) {
                    if(is_valid[i])
                            continue;
                    arr[i] = arr[last]; // swap invalid with the last valid
                    last--;
                    for(; last >= 0 && !is_valid[last]; last--); // trim invalid elements
            }
            return last+1; // return the compact length of the array
    }

Android check null or empty string in Android

Incase all the answer given does not work, kindly try

String myString = null;

if(myString.trim().equalsIgnoreCase("null")){
    //do something
}

Merge, update, and pull Git branches without using checkouts

You can clone the repo and do the merge in the new repo. On the same filesystem, this will hardlink rather than copy most of the data. Finish by pulling the results into the original repo.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

You need to do one thing:

  • Add async before function.

_x000D_
_x000D_
const gulp = require('gulp');

gulp.task('message', async function() {
    console.log("Gulp is running...");
});
_x000D_
_x000D_
_x000D_

Initialization of all elements of an array to one default value in C++?

1) When you use an initializer, for a struct or an array like that, the unspecified values are essentially default constructed. In the case of a primitive type like ints, that means they will be zeroed. Note that this applies recursively: you could have an array of structs containing arrays and if you specify just the first field of the first struct, then all the rest will be initialized with zeros and default constructors.

2) The compiler will probably generate initializer code that is at least as good as you could do by hand. I tend to prefer to let the compiler do the initialization for me, when possible.

converting epoch time with milliseconds to datetime

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

Numpy: Divide each row by a vector element

As has been mentioned, slicing with None or with np.newaxes is a great way to do this. Another alternative is to use transposes and broadcasting, as in

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function. There really are a lot of ways to do this.

For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

How do you explicitly set a new property on `window` in TypeScript?

I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.

In order for my library to use declarations I had to use the d.ts extention for the file that declares the new properties of the global object.

So in the end, the file ended up with something like:

/path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts

Once created, don't forget to expose it in your public_api.ts.

That did it for me. Hope this helps.

CURL alternative in Python

import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

Your cURL call using urllib2 instead. Completely untested.

Re-render React component when prop changes

componentWillReceiveProps(nextProps) { // your code here}

I think that is the event you need. componentWillReceiveProps triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

Reloading .env variables without restarting server (Laravel 5, shared hosting)

A short solution:

use Dotenv;

with(new Dotenv(app()->environmentPath(), app()->environmentFile()))->overload();
with(new LoadConfiguration())->bootstrap(app());

In my case I needed to re-establish database connection after altering .env programmatically, but it didn't work , If you get into this trouble try this

app('db')->purge($connection->getName()); 

after reloading .env , that's because Laravel App could have accessed the default connection before and the \Illuminate\Database\DatabaseManager needs to re-read config parameters.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You can't return an XmlElement or an XmlNode, because those objects always and only exist within the context of an owning XmlDocument.

XML serialization is a little easier than returning an XElement, because all you have to do is mark properties with attributes and the serializer does all the XML generation for you. (Plus you get deserialization for free, assuming you have a parameterless constructor and, well, a bunch of other things.)

On the other hand, a) you have to create an XmlSerializer to do it, b) dealing with collection properties isn't quite the no-brainer you might like it to be, and c) XML serialization is pretty dumb; you're out of luck if you want to do anything fancy with the XML you're generating.

In a lot of cases, those issues don't matter one bit. I for one would rather mark my properties with attributes than write a method.

Javascript to Select Multiple options

This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:

var values = ["Red", "Green"],
    colors = document.getElementById("colors");

_.each(colors.options, function (option) {
    option.selected = ~_.indexOf(values, option.text);
});

If you're using jQuery, it could be even more terse:

var values = ["Red", "Green"];

$("#colors option").prop("selected", function () {
    return ~$.inArray(this.text, values);
});

If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:

var color, i, j,
    values = ["Red", "Green"],
    options = document.getElementById("colors").options;

for ( i = 0; i < values.length; i++ ) {
    for ( j = 0, color = values[i]; j < options.length; j++ ) {
        options[j].selected = options[j].selected || color === options[j].text;
    }
}

How to force Docker for a clean build of an image

In some extreme cases, your only way around recurring build failures is by running:

docker system prune

The command will ask you for your confirmation:

WARNING! This will remove:
    - all stopped containers
    - all volumes not used by at least one container
    - all networks not used by at least one container
    - all images without at least one container associated to them
Are you sure you want to continue? [y/N]

This is of course not a direct answer to the question, but might save some lives... It did save mine.

How to select all textareas and textboxes using jQuery?

names = [];
$('input[name=text], textarea').each(
    function(index){  
        var input = $(this);
        names.push( input.attr('name') );
        //input.attr('id');
    }
);

it select all textboxes and textarea in your DOM, where $.each function iterates to provide name of ecah element.

pip install access denied on Windows

Opening command prompt As Administrator just worked for me without using Python executable. Right click on command prompt shortcut and choose "Run as Administrator". Then run the following command.

pip install Django

Is there a way to know your current username in mysql?

You can also use : mysql> select user,host from mysql.user;

+---------------+-------------------------------+
| user          | host                          |
+---------------+-------------------------------+
| fkernel       | %                             |
| nagios        | %                             |
| readonly      | %                             |
| replicant     | %                             |
| reporting     | %                             |
| reporting_ro  | %                             |
| nagios        | xx.xx.xx.xx                 |
| haproxy_root  | xx.xx.xx.xx
| root          | 127.0.0.1                     |
| nagios        | localhost                     |
| root          | localhost                     |
+---------------+-------------------------------+

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Only tested on Android 4.1.1:

blur event is not a reliable event to test keyboard up and down because the user as the option to explicitly hide the keyboard which does not trigger a blur event on the field that caused the keyboard to show.

resize event however works like a charm if the keyboard comes up or down for any reason.

coffee:

$(window).bind "resize", (event) ->  alert "resize"

fires on anytime the keyboard is shown or hidden for any reason.

Note however on in the case of an android browser (rather than app) there is a retractable url bar which does not fire resize when it is retracted yet does change the available window size.

Format date and Subtract days using Moment.js

Try this:

var duration = moment.duration({'days' : 1});
moment().subtract(duration).format('DD-MM-YYYY');

This will give you 14-04-2015 - today is 15-04-2015

Alternatively if your momentjs version is less than 2.8.0, you can use:

startdate = moment().subtract('days', 1).format('DD-MM-YYYY');

Instead of this:

startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

128M == 134217728, the number you are seeing.

The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.

Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.

Difference between Convert.ToString() and .ToString()

ToString() can not handle null values and convert.ToString() can handle values which are null, so when you want your system to handle null value use convert.ToString().

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

What does %~dp0 mean, and how does it work?

Great example from Strawberry Perl's portable shell launcher:

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

set PATH=%drivep%\perl\site\bin;%drivep%\perl\bin;%drivep%\c\bin;%PATH%

not sure what the negative 1's doing there myself, but it works a treat!

How to convert hex strings to byte values in Java

String str = "Your string";

byte[] array = str.getBytes();

Segmentation fault on large array sizes

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

Is there a pretty print for PHP?

Here's another simple dump without all the overhead of print_r:

function pretty($arr, $level=0){
    $tabs = "";
    for($i=0;$i<$level; $i++){
        $tabs .= "    ";
    }
    foreach($arr as $key=>$val){
        if( is_array($val) ) {
            print ($tabs . $key . " : " . "\n");
            pretty($val, $level + 1);
        } else {
            if($val && $val !== 0){
                print ($tabs . $key . " : " . $val . "\n"); 
            }
        }
    }
}
// Example:
$item["A"] = array("a", "b", "c");
$item["B"] = array("a", "b", "c");
$item["C"] = array("a", "b", "c");

pretty($item);

// -------------
// yields
// -------------
// A : 
//     0 : a
//     1 : b
//     2 : c
// B : 
//     0 : a
//     1 : b
//     2 : c
// C : 
//     0 : a
//     1 : b
//     2 : c

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

When you are Extending Activity use following Code

ActionBar actionbar = getActionBar();
actionbar.setBackgroundDrawable(new ColorDrawable("color"));

When you are Extending AppCompatActivity use following Code

ActionBar actionbar = getSupportActionBar();
actionbar.setBackgroundDrawable(new ColorDrawable("color"));

jQuery animated number counter from zero to value

You can do it with animate function in jQuery.

$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
    duration: 8000,
    easing: 'linear',
    step: function () {
        $('.yourelement').html(Math.floor(this.countNum));
    },
    complete: function () {
        $('.code').html(this.countNum);
        //alert('finished');
   }
});

Demo

How to change MenuItem icon in ActionBar programmatically

You can't use findViewById() on menu items in onCreate() because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu() and then use it in your onClick().

private Menu menu;

In your onCreateOptionsMenu()

this.menu = menu;

In your button's onClick() method

menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));

Login to Microsoft SQL Server Error: 18456

Check out this blog article from the data platform team.

http://blogs.msdn.com/b/sql_protocols/archive/2006/02/21/536201.aspx

You really need to look at the state part of the error message to find the root cause of the issue.

2, 5 = Invalid userid
6 = Attempt to use a Windows login name with SQL Authentication
7 = Login disabled and password mismatch
8 = Password mismatch
9 = Invalid password
11, 12 = Valid login but server access failure
13 = SQL Server service paused
18 = Change password required

Afterwards, Google how to fix the issue.

Install / upgrade gradle on Mac OS X

Another alternative is to use sdkman. An advantage of sdkman over brew is that many versions of gradle are supported. (brew only supports the latest version and 2.14.) To install sdkman execute:

curl -s "https://get.sdkman.io" | bash

Then follow the instructions. Go here for more installation information. Once sdkman is installed use the command:

sdk install gradle

Or to install a specific version:

sdk install gradle 2.2

Or use to use a specific installed version:

sdk use gradle 2.2

To see which versions are installed and available:

sdk list gradle

For more information go here.

Return list using select new in LINQ

public List<Object> GetProjectForCombo()
{
   using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
   {
     var query = db.Project
     .Select<IEnumerable<something>,ProjectInfo>(p=>
                 return new ProjectInfo{Name=p.ProjectName, Id=p.ProjectId);       

     return query.ToList<Object>();
   }

}

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

Tracking changes in Windows registry

Regarding WMI and Registry:

There are three WMI event classes concerning registry:

  • RegistryTreeChangeEvent
  • RegistryKeyChangeEvent
  • RegistryValueChangeEvent

Registry Event Classes

But you need to be aware of these limitations:

  • With RegistryTreeChangeEvent and RegistryKeyChangeEvent there is no way of directly telling which values or keys actually changed. To do this, you would need to save the registry state before the event and compare it to the state after the event.

  • You can't use these classes with HKEY_CLASSES_ROOT or HKEY_CURRENT_USER hives. You can overcome this by creating a WMI class to represent the registry key to monitor:

Defining a Registry Class With Qualifiers

and use it with __InstanceOperationEvent derived classes.

So using WMI to monitor the Registry is possible, but less then perfect. The advantage is that it is possible to monitor the changes in 'real time'. Another advantage could be WMI permanent event subscription:

Receiving Events at All Times

a method to monitor the Registry 'at all times', ie. event if your application is not running.

How to find out if an installed Eclipse is 32 or 64 bit version?

Open eclipse.ini in the installation directory, and observe the line with text:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.0.200.v20090519 then it is 64 bit.

If it would be plugins/org.eclipse.equinox.launcher.win32.win32.x86_32_1.0.200.v20090519 then it is 32 bit.

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

You can directly set the content type like below:

res.writeHead(200, {'Content-Type': 'text/plain'});

For reference go through the nodejs Docs link.

What is the { get; set; } syntax in C#?

A property is a like a layer that separates the private variable from other members of a class. From outside world it feels like a property is just a field, a property can be accessed using .Property

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName => $"{FirstName} {LastName}";
}

public class Person
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName { get { return $"{FirstName} {LastName}"; } }
}

FullName is a Property. The one with arrow is a shortcut. From outside world, we can access FullName like this:

var person = new Person();
Console.WriteLine(person.FullName);

Callers do not care about how you implemented the FullName. But inside the class you can change FullName whatever you want.

Check out Microsoft Documentation for more detailed explanation:

https://docs.microsoft.com/en-us/dotnet/csharp/properties

if statement in ng-click

Here's a hack I discovered that might work for you, although its not pretty and I'd personally be embarrassed to use such a line of code:

ng-click="profileForm.$valid ? updateMyProfile() : alert('failed')"

Now, you must be thinking 'but I don't want it to alert("failed") if my profileForm isn't valid. Well that's the ugly part. For me, no matter what I put in the else clause of this ternary statement doesn't get executed ever.

Yet if its removed an error is thrown. So you can just stuff it with a pointless alert.
I told you it was ugly... but I don't even get any errors when I do something like this.
The proper way to do this is as Chen-Tsu mentioned, but to each their own.

How to add extension methods to Enums

You can create an extension for anything, even object(although that's not considered best-practice). Understand an extension method just as a public static method. You can use whatever parameter-type you like on methods.

public static class DurationExtensions
{
  public static int CalculateDistanceBetween(this Duration first, Duration last)
  {
    //Do something here
  }
}

C pointer to array/array of pointers disambiguation

The answer for the last two can also be deducted from the golden rule in C:

Declaration follows use.

int (*arr2)[8];

What happens if you dereference arr2? You get an array of 8 integers.

int *(arr3[8]);

What happens if you take an element from arr3? You get a pointer to an integer.

This also helps when dealing with pointers to functions. To take sigjuice's example:

float *(*x)(void )

What happens when you dereference x? You get a function that you can call with no arguments. What happens when you call it? It will return a pointer to a float.

Operator precedence is always tricky, though. However, using parentheses can actually also be confusing because declaration follows use. At least, to me, intuitively arr2 looks like an array of 8 pointers to ints, but it is actually the other way around. Just takes some getting used to. Reason enough to always add a comment to these declarations, if you ask me :)

edit: example

By the way, I just stumbled across the following situation: a function that has a static matrix and that uses pointer arithmetic to see if the row pointer is out of bounds. Example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM_ELEM(ar) (sizeof(ar) / sizeof((ar)[0]))

int *
put_off(const int newrow[2])
{
    static int mymatrix[3][2];
    static int (*rowp)[2] = mymatrix;
    int (* const border)[] = mymatrix + NUM_ELEM(mymatrix);

    memcpy(rowp, newrow, sizeof(*rowp));
    rowp += 1;
    if (rowp == border) {
        rowp = mymatrix;
    }

    return *rowp;
}

int
main(int argc, char *argv[])
{
    int i = 0;
    int row[2] = {0, 1};
    int *rout;

    for (i = 0; i &lt; 6; i++) {
        row[0] = i;
        row[1] += i;
        rout = put_off(row);
        printf("%d (%p): [%d, %d]\n", i, (void *) rout, rout[0], rout[1]);
    }

    return 0;
}

Output:

0 (0x804a02c): [0, 0]
1 (0x804a034): [0, 0]
2 (0x804a024): [0, 1]
3 (0x804a02c): [1, 2]
4 (0x804a034): [2, 4]
5 (0x804a024): [3, 7]

Note that the value of border never changes, so the compiler can optimize that away. This is different from what you might initially want to use: const int (*border)[3]: that declares border as a pointer to an array of 3 integers that will not change value as long as the variable exists. However, that pointer may be pointed to any other such array at any time. We want that kind of behaviour for the argument, instead (because this function does not change any of those integers). Declaration follows use.

(p.s.: feel free to improve this sample!)

AngularJS routing without the hash '#'

**

It is recommended to use the HTML 5 style (PathLocationStrategy) as location strategy in Angular

** Because

  1. It produces the clean and SEO Friendly URLs that are easier for users to understand and remember.
  2. You can take advantage of the server-side rendering, which will make our application load faster, by rendering the pages in the server first before delivering it the client.

Use Hashlocationstrtegy only if you have to support the older browsers.

Click here to know more

Problems using Maven and SSL behind proxy

You can import the SSL cert manually and just add it to the keystore.

For linux users,

Syntax:

keytool -trustcacerts -keystore /jre/lib/security/cacerts -storepass changeit -importcert -alias nexus -file

Example :

keytool -trustcacerts -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/security/cacerts -storepass changeit -importcert -alias nexus -file ~/Downloads/abc.com-ssl.crt

git pull fails "unable to resolve reference" "unable to update local ref"

If this error “unable to update local ref” is reoccurring, even after applying either the answer by Vojtech Vitek or Michel Krämer you may you may have a bad ref on your local AND master repository.

In this case you should apply both fix's without pulling or pushing in between ...

rm .git/refs/remotes/origin/master
git fetch
git gc --prune=now
git remote prune origin

A permanent resolution for me was only achieved after applying both fix's before push/pull.

Maven version with a property

I have two recommendation for you

  1. Use CI Friendly Revision for all your artifacts. You can add -Drevision=2.0.1 in .mvn/maven.config file. So basically you define your version only at one location.
  2. For all external dependency create a property in parent file. You can use Apache Camel Parent Pom as reference

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

Remove all whitespace from C# string with regex

Below is the code that would replace the white space from the file name into given URL and also we can remove the same by using string.empty instead of "~"

  if (!string.IsNullOrEmpty(url))
          {
           string origFileName = Path.GetFileName(url);
           string modiFileName = origFileName.Trim().Replace(" ", "~");
           url = url.Replace(origFileName , modiFileName );
          }
          return url;

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :

public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions> 
{
    public IServiceProvider ServiceProvider { get; set; }

    public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
        : base (options, logger, encoder, clock) 
    {
        ServiceProvider = serviceProvider;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync () 
    {
        var headers = Request.Headers;
        var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);

        if (string.IsNullOrEmpty (token)) {
            return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
        }           

        bool isValidToken = false; // check token here

        if (!isValidToken) {
            return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
        }

        var claims = new [] { new Claim ("token", token) };
        var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
        var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
        return Task.FromResult (AuthenticateResult.Success (ticket));
    }
}

Startup.cs :

#region Authentication
services.AddAuthentication (o => {
    o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion

And mycontroller.cs

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }

I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :

public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
    public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}

You should define static class SchemesNamesConst. Something like:

public static class SchemesNamesConst
{
    public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}

Disable validation of HTML5 form elements

If you mark a form element as required="" then novalidate="" does not help.

A way to circumvent the required validation is to disable the element.

Collision Detection between two images in Java

Use a rectangle to surround each player and enemy, the height and width of the rectangles should correspond to the object you're surrounding, imagine it being in a box only big enough to fit it.

Now, you move these rectangles the same as you do the objects, so they have a 'bounding box'

I'm not sure if Java has this, but it might have a method on the rectangle object called .intersects() so you'd do if(rectangle1.intersectS(rectangle2) to check to see if an object has collided with another.

Otherwise you can get the x and y co-ordinates of the boxes and using the height/width of them detect whether they've intersected yourself.

Anyway, you can use that to either do an event on intersection (make one explode, or whatever) or prevent the movement from being drawn. (revert to previous co-ordinates)

edit: here we go

boolean

intersects(Rectangle r) Determines whether or not this Rectangle and the specified Rectangle intersect.

So I would do (and don't paste this code, it most likely won't work, not done java for a long time and I didn't do graphics when I did use it.)

Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height);

Rectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height);

//detects when the two rectangles hit
if(rect1.intersects(rect2))
{

System.out.println("game over, g");
}

obviously you'd need to fit that in somewhere.

Difference between <? super T> and <? extends T> in Java

When to use extends and super

Wildcards are most useful in method parameters. They allow for the necessary flexibility in method interfaces.

People are often confused when to use extends and when to use super bounds. The rule of thumb is the get-put principle. If you get something from a parametrized container, use extends.

int totalFuel(List<? extends Vehicle> list) {
int total = 0;
for(Vehicle v : list) {
    total += v.getFuel();
}
return total;}

The method totalFuel gets Vehicles from the list, asks them about how much fuel they have, and computes the total. If you put objects into a parameterized container, use super.

int totalValue(Valuer<? super Vehicle> valuer) {
int total = 0;
for(Vehicle v : vehicles) {
    total += valuer.evaluate(v);
}
return total;}

The method totalValue puts Vehicles into the Valuer. It's useful to know that extends bound is much more common than super.

How to convert Strings to and from UTF8 byte arrays in Java

String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");

Java IOException "Too many open files"

On Linux and other UNIX / UNIX-like platforms, the OS places a limit on the number of open file descriptors that a process may have at any given time. In the old days, this limit used to be hardwired1, and relatively small. These days it is much larger (hundreds / thousands), and subject to a "soft" per-process configurable resource limit. (Look up the ulimit shell builtin ...)

Your Java application must be exceeding the per-process file descriptor limit.

You say that you have 19 files open, and that after a few hundred times you get an IOException saying "too many files open". Now this particular exception can ONLY happen when a new file descriptor is requested; i.e. when you are opening a file (or a pipe or a socket). You can verify this by printing the stacktrace for the IOException.

Unless your application is being run with a small resource limit (which seems unlikely), it follows that it must be repeatedly opening files / sockets / pipes, and failing to close them. Find out why that is happening and you should be able to figure out what to do about it.

FYI, the following pattern is a safe way to write to files that is guaranteed not to leak file descriptors.

Writer w = new FileWriter(...);
try {
    // write stuff to the file
} finally {
    try {
        w.close();
    } catch (IOException ex) {
        // Log error writing file and bail out.
    }
}

1 - Hardwired, as in compiled into the kernel. Changing the number of available fd slots required a recompilation ... and could result in less memory being available for other things. In the days when Unix commonly ran on 16-bit machines, these things really mattered.

UPDATE

The Java 7 way is more concise:

try (Writer w = new FileWriter(...)) {
    // write stuff to the file
} // the `w` resource is automatically closed 

UPDATE 2

Apparently you can also encounter a "too many files open" while attempting to run an external program. The basic cause is as described above. However, the reason that you encounter this in exec(...) is that the JVM is attempting to create "pipe" file descriptors that will be connected to the external application's standard input / output / error.

How do I install Eclipse Marketplace in Eclipse Classic?

With Eclipse 3.7 Indigo, I found the link at http://www.eclipse.org/mpc/ which told me the download location and plugin was http://download.eclipse.org/mpc/indigo/ Which made the "Eclipse Marketplace Client" available in my Software updates after I added that address as a repository. Didn't seem to be in the core list on a fresh install.

Moving Git repository content to another repository preserving history

I am not very sure if what i did was right, but it worked anyways. I renamed repo2 folder present inside repo1, and committed the changes. In my case it was just one repo which i wanted to merge , so this approach worked. Later on, some path changes were done.

db.collection is not a function when using MongoClient v3.0

MongoClient.connect(url (err, client) => {
    if(err) throw err;

    let database = client.db('databaseName');

    database.collection('name').find()
    .toArray((err, results) => {
        if(err) throw err;

        results.forEach((value)=>{
            console.log(value.name);
        });
    })
})

The only problem with your code is that you are accessing the object that's holding the database handler. You must access the database directly (see database variable above). This code will return your database in an array and then it loops through it and logs the name for everyone in the database.

Drop multiple columns in pandas

Try this

df.drop(df.iloc[:, 1:69], inplace=True, axis=1)

This works for me

biggest integer that can be stored in a double

You need to look at the size of the mantissa. An IEEE 754 64 bit floating point number (which has 52 bits, plus 1 implied) can exactly represent integers with an absolute value of less than or equal to 2^53.

What do .c and .h file extensions mean to C?

The .c is the source file and .h is the header file.

Maven fails to find local artifact

The local Maven repo tracks where artifacts originally came from using a file named "_maven.repositories" in the artifact directory. After removing it, the build worked. This answer fixed the problem for me.

Prevent form submission on Enter key press

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

This literally means that the mentioned class com.example.Bean doesn't have a public (non-static!) getter method for the mentioned property foo. Note that the field itself is irrelevant here!

The public getter method name must start with get, followed by the property name which is capitalized at only the first letter of the property name as in Foo.

public Foo getFoo() {
    return foo;
}

You thus need to make sure that there is a getter method matching exactly the property name, and that the method is public (non-static) and that the method does not take any arguments and that it returns non-void. If you have one and it still doesn't work, then chances are that you were busy editing code forth and back without firmly cleaning the build, rebuilding the code and redeploying/restarting the application. You need to make sure that you have done so.

For boolean (not Boolean!) properties, the getter method name must start with is instead of get.

public boolean isFoo() {
    return foo;
}

Regardless of the type, the presence of the foo field itself is thus not relevant. It can have a different name, or be completely absent, or even be static. All of below should still be accessible by ${bean.foo}.

public Foo getFoo() {
    return bar;
}
public Foo getFoo() {
    return new Foo("foo");
}
public Foo getFoo() {
    return FOO_CONSTANT;
}

You see, the field is not what counts, but the getter method itself. Note that the property name itself should not be capitalized in EL. In other words, ${bean.Foo} won't ever work, it should be ${bean.foo}.

See also:

How to call a function in shell Scripting?

#!/bin/bash  
# functiontest.sh a sample to call the function in the shell script  

choice="true"  
function process_install  
{  
  commands...
}  

function process_exit  
{
  commands...  
}  

function main  
{  
  if [[ "$choice" == "true" ]]; then  
      process_install
  elif [[ "$choice" == "false" ]]; then  
      process_exit  
  fi  
}  

main "$@"  

it will start from the main function

How to represent multiple conditions in a shell if statement?

In bash for string comparison, you can use the following technique.

if [ $var OP "val" ]; then
    echo "statements"
fi

Example:

var="something"
if [ $var != "otherthing" ] && [ $var != "everything" ] && [ $var != "allthings" ]; then
    echo "this will be printed"
else
    echo "this will not be printed"
fi

How to use mod operator in bash?

Try the following:

 for i in {1..600}; do echo wget http://example.com/search/link$(($i % 5)); done

The $(( )) syntax does an arithmetic evaluation of the contents.

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

How to find SQL Server running port?

This is the one that works for me:

SELECT DISTINCT 
    local_tcp_port 
FROM sys.dm_exec_connections 
WHERE local_tcp_port IS NOT NULL 

How to prevent Screen Capture in Android

I saw all of the answers which are appropriate only for a single activity but there is my solution which will block screenshot for all of the activities without adding any code to the activity. First of all make an Custom Application class and add a registerActivityLifecycleCallbacks.Then register it in your manifest.

MyApplicationContext.class

public class MyApplicationContext extends Application {
    private  Context context;
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        setupActivityListener();
    }

    private void setupActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);            }
            @Override
            public void onActivityStarted(Activity activity) {
            }
            @Override
            public void onActivityResumed(Activity activity) {

            }
            @Override
            public void onActivityPaused(Activity activity) {

            }
            @Override
            public void onActivityStopped(Activity activity) {
            }
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }



}

Manifest

 <application
        android:name=".MyApplicationContext"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Nesting CSS classes

No.

You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.

See also my article on CSS inheritance.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

I'm not absolutely sure I got your question correctly, but it seems you want something like this:

    Class c = null;
    try {
        c = Class.forName("com.path.to.ImplementationType");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    T interfaceType = null;
    try {
        interfaceType = (T) c.newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

Where T can be defined in method level or in class level, i.e. <T extends InterfaceType>

How to check if a character in a string is a digit or letter

You could do this by Regular Expression as follows you could use this code

EditText et = (EditText) findViewById(R.id.editText);
String NumberPattern = "[0-9]+";
String Number = et.getText().toString();

if (Number.matches(NumberPattern) && s.length() > 0)
{ 
    //code for number
}
else
{
    //code for incorrect number pattern
}

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

  1. Create SDK folder at \Android\Sdk
  2. Close any project which is already open in Android studio

Android Studio setup wizard will appear and perform the needed installation.

How to display data from database into textbox, and update it

The answer is .IsPostBack as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load

private void PopulateFields()
{
  using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
  {
    DataTable dt = new DataTable();
    con1.Open();
    SqlDataReader myReader = null;  
    SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);

    myReader = myCommand.ExecuteReader();

    while (myReader.Read())
    {
        TextBoxPassword.Text = (myReader["password"].ToString());
        TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
        DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
        DropDownListMonth.Text = (myReader["birth"].ToString());
        DropDownListYear.Text = (myReader["birth"].ToString());
        TextBoxAddress.Text = (myReader["address"].ToString());
        TextBoxCity.Text = (myReader["city"].ToString());
        DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
        TextBoxPostcode.Text = (myReader["postcode"].ToString());
        TextBoxEmail.Text = (myReader["email"].ToString());
        TextBoxCarno.Text = (myReader["carno"].ToString());
    }
    con1.Close();
  }//end using
}

Then call it in your Page_Load

protected void Page_Load(object sender, EventArgs e)
{

    if(!Page.IsPostBack)
    {
       PopulateFields();
    }
}

Fastest way to update 120 Million records

set rowcount 1000000
Update table set int_field = -1 where int_field<>-1

see how fast that takes, adjust and repeat as necessary

Want to show/hide div based on dropdown box selection

you have error in your code unexpected token.use:

  $('#purpose').on('change', function () {
   if (this.value == '1') {
    $("#business").show();
    } else {
    $("#business").hide();
   }

   });

Demo

Update: You can narrow down the code using .toggle()

 $('#purpose').on('change', function () {
   $("#business").toggle(this.value == '1');
 });

How to get sp_executesql result into a variable?

This worked for me:

DECLARE @SQL NVARCHAR(4000)

DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int
) 

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

Passing array in GET for a REST call

Instead of using http GET, use http POST. And JSON. Or XML

This is how your request stream to the server would look like.

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

{users: [user:{id:id1}, user:{id:id2}]}

Or in XML,

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

<users><user id='id1'/><user id='id2'/></users>

You could certainly continue using GET as you have proposed, as it is certainly simpler.

/appointments?users=1d1,1d2

Which means you would have to keep your data structures very simple.

However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.

Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.

JQuery

If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.

How to get SLF4J "Hello World" working with log4j?

Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.

  • Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    
  • Configure log4j.properties

    log4j.rootLogger=TRACE, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
    
  • Java example

    public class Slf4jExample {
        public static void main(String[] args) {
    
            Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
    
            final String message = "Hello logging!";
            logger.trace(message);
            logger.debug(message);
            logger.info(message);
            logger.warn(message);
            logger.error(message);
        }
    }
    

Getting current device language in iOS?

If you're looking for preferred language code ("en", "de", "es" ...), and localized preferred language name (for current locale), here's a simple extension in Swift:

extension Locale {
    static var preferredLanguageIdentifier: String {
        let id = Locale.preferredLanguages.first!
        let comps = Locale.components(fromIdentifier: id)
        return comps.values.first!
    }

    static var preferredLanguageLocalizedString: String {
        let id = Locale.preferredLanguages.first!
        return Locale.current.localizedString(forLanguageCode: id)!
    }
}

Get content of a DIV using JavaScript

function add_more() {

var text_count = document.getElementById('text_count').value;
var div_cmp = document.getElementById('div_cmp');
var values = div_cmp.innnerHTML;
var count = parseInt(text_count);
divContent = '';

for (i = 1; i <= count; i++) {

    var cmp_text = document.getElementById('cmp_name_' + i).value;
    var cmp_textarea = document.getElementById('cmp_remark_' + i).value;
    divContent += '<div id="div_cmp_' + i + '">' +
        '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + i + '" value="' + cmp_text + '" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + i + '">' + cmp_textarea + '</textarea>' +
        '</div>';
}

var newCount = count + 1;

if (document.getElementById('div_cmp_' + newCount) == null) {
    var newText = '<div id="div_cmp_' + newCount + '">' +
        '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '"  ></textarea>' +
        '</div>';
    //content = div_cmp.innerHTML;
    div_cmp.innerHTML = divContent + newText;
} else {
    document.getElementById('div_cmp_' + newCount).innerHTML = '<input type="text" align="top" name="cmp_name[]" id="cmp_name_' + newCount + '" value="" >' +
        '<textarea rows="1" cols="20" name="cmp_remark[]" id="cmp_remark_' + newCount + '"  ></textarea>';
}

document.getElementById('text_count').value = newCount;

}

apache redirect from non www to www

Redirect domain.tld to www.

The following lines can be added either in Apache directives or in .htaccess file:

RewriteEngine on    
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  • Other sudomains are still working.
  • No need to adjust the lines. just copy/paste them at the right place.

Don't forget to apply the apache changes if you modify the vhost.

(based on the default Drupal7 .htaccess but should work in many cases)

How to retrieve the last autoincremented ID from a SQLite table?

One other option is to look at the system table sqlite_sequence. Your sqlite database will have that table automatically if you created any table with autoincrement primary key. This table is for sqlite to keep track of the autoincrement field so that it won't repeat the primary key even after you delete some rows or after some insert failed (read more about this here http://www.sqlite.org/autoinc.html).

So with this table there is the added benefit that you can find out your newly inserted item's primary key even after you inserted something else (in other tables, of course!). After making sure that your insert is successful (otherwise you will get a false number), you simply need to do:

select seq from sqlite_sequence where name="table_name"

"date(): It is not safe to rely on the system's timezone settings..."

In your connection page put a code like this date_default_timezone_set("Africa/Johannesburg"); based on your current location.

How to set Sqlite3 to be case insensitive when string comparing?

SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

Lambda expression to convert array/List of String to array/List of Integers

I didn't find it in the previous answers, so, with Java 8 and streams:

Convert String[] to Integer[]:

Arrays.stream(stringArray).map(Integer::valueOf).toArray(Integer[]::new)

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

My httpd.conf is empty

It's empty by default. You'll find a bunch of settings in /etc/apache2/apache2.conf.

In there it does this:

# Include all the user configurations:
Include httpd.conf

How do I split a string into an array of characters?

Old question but I should warn:

Do NOT use .split('')

You'll get weird results with non-BMP (non-Basic-Multilingual-Plane) character sets.

Reason is that methods like .split() and .charCodeAt() only respect the characters with a code point below 65536; bec. higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters.

''.length     // —> 6
''.split('')  // —> ["?", "?", "?", "?", "?", "?"]

''.length      // —> 2
''.split('')   // —> ["?", "?"]

Use ES2015 (ES6) features where possible:

Using the spread operator:

let arr = [...str];

Or Array.from

let arr = Array.from(str);

Or split with the new u RegExp flag:

let arr = str.split(/(?!$)/u);

Examples:

[...'']        // —> ["", "", ""]
[...'']     // —> ["", "", ""]

For ES5, options are limited:

I came up with this function that internally uses MDN example to get the correct code point of each character.

function stringToArray() {
  var i = 0,
    arr = [],
    codePoint;
  while (!isNaN(codePoint = knownCharCodeAt(str, i))) {
    arr.push(String.fromCodePoint(codePoint));
    i++;
  }
  return arr;
}

This requires knownCharCodeAt() function and for some browsers; a String.fromCodePoint() polyfill.

if (!String.fromCodePoint) {
// ES6 Unicode Shims 0.1 , © 2012 Steven Levithan , MIT License
    String.fromCodePoint = function fromCodePoint () {
        var chars = [], point, offset, units, i;
        for (i = 0; i < arguments.length; ++i) {
            point = arguments[i];
            offset = point - 0x10000;
            units = point > 0xFFFF ? [0xD800 + (offset >> 10), 0xDC00 + (offset & 0x3FF)] : [point];
            chars.push(String.fromCharCode.apply(null, units));
        }
        return chars.join("");
    }
}

Examples:

stringToArray('')     // —> ["", "", ""]
stringToArray('')  // —> ["", "", ""]

Note: str[index] (ES5) and str.charAt(index) will also return weird results with non-BMP charsets. e.g. ''.charAt(0) returns "?".

UPDATE: Read this nice article about JS and unicode.

The project description file (.project) for my project is missing

I created a new workspace and imported old projects. I just didn’t open this workspace for a long time, I don’t know why this problem happened

Logout button php

Instead of a button, put a link and navigate it to another page

<a href="logout.php">Logout</a>

Then in logout.php page, use

session_start();
session_destroy();
header('Location: login.php');
exit;

return query based on date

Just been implementing something similar in Mongo v3.2.3 using Node v0.12.7 and v4.4.4 and used:

{ $gte: new Date(dateVar).toISOString() }

I'm passing in an ISODate (e.g. 2016-04-22T00:00:00Z) and this works for a .find() query with or without the toISOString function. But when using in an .aggregate() $match query it doesn't like the toISOString function!

Class type check in TypeScript

TypeScript have a way of validating the type of a variable in runtime. You can add a validating function that returns a type predicate. So you can call this function inside an if statement, and be sure that all the code inside that block is safe to use as the type you think it is.

Example from the TypeScript docs:

function isFish(pet: Fish | Bird): pet is Fish {
   return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
  pet.swim();
}
else {
  pet.fly();
}

See more at: https://www.typescriptlang.org/docs/handbook/advanced-types.html

Visual Studio 2015 is very slow

Try uninstalling either Node.js Tools for Visual Studio (NTVS) or the commercial add-on called ReSharper from JetBrains. Using both NTVS and Resharper causes memory leaks in Visual Studio 2015.

NTVS = Node Tools for Visual Studio