Programs & Examples On #Shortcut

A route more direct than the one ordinarily taken. A method or means of doing something more directly and quickly than and often not so thoroughly as by ordinary procedure.

How do I create a shortcut via command-line in Windows?

I would like to propose different solution which wasn't mentioned here which is using .URL files:

set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%

Notes:

  • By default .url files are intended to open web pages but they are working fine for any properly constructed URI
  • Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
  • IconFile and IconIndex are optional
  • For reference you can check An Unofficial Guide to the URL File Format of Edward Blake

Code snippet or shortcut to create a constructor in Visual Studio

As mentioned by many, "ctor" and double TAB works in Visual Studio 2017, but it only creates the constructor with none of the attributes.

To auto-generate with attributes (if there are any), just click on an empty line below them and press Ctrl + .. It'll display a small pop-up from which you can select the "Generate Constructor..." option.

Is there a short cut for going back to the beginning of a file by vi editor?

To go end of the file: press ESC

1) type capital G (Capital G)

2) press shift + g (small g)

To go top of the file there are the following ways: press ESC

1) press 1G (Capital G)

2) press gg (small g) or 1gg

3) You can jump to the particular line number,e.g wanted to go 1 line number, press 1 + G

How do I call a function twice or more times consecutively?

from itertools import repeat, starmap

results = list(starmap(do, repeat((), 3)))

See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:

for _ in starmap(do, repeat((), 3)): pass

but that's getting ugly.

2D array values C++

One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.

Another alternative is to represent a 2D array as an std::vector<std::vector<int> >. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

How to update gradle in android studio?

For those who still have this problem (for example to switch from 2.8.0 to 2.10.0), move to the file gradle-wrapper.properties and set distributionUrl like that.

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

I changed 2.8.0 to 2.10.0 and don't forget to Sync after

How to automatically generate getters and setters in Android Studio

You can use AndroidAccessors Plugin of Android Studio to generate getter and setter without m as prefix to methods

Ex: mId; Will generate getId() and setId() instead of getmId() and setmId()

plugin screenshot

Collapse all methods in Visual Studio Code

  • Ctrl + K + 0: fold all levels (namespace, class, method, and block)
  • Ctrl + K + 1: namspace
  • Ctrl + K + 2: class
  • Ctrl + K + 3: methods
  • Ctrl + K + 4: blocks
  • Ctrl + K + [ or Ctrl + k + ]: current cursor block
  • Ctrl + K + j: UnFold

Shortcut to create properties in Visual Studio?

You could type "prop" and then press tab twice. That will generate the following.

public TYPE Type { get; set; }

Then you change "TYPE" and "Type":

public string myString {get; set;}

You can also get the full property typing "propfull" and then tab twice. That would generate the field and the full property.

private int myVar;

public int MyProperty
{
    get { return myVar;}
    set { myVar = value;}
}

window.close() doesn't work - Scripts may close only the windows that were opened by it

You can't close a current window or any window or page that is opened using '_self' But you can do this

var customWindow = window.open('', '_blank', '');
    customWindow.close();

Eclipse comment/uncomment shortcut?

For single line comment you can use Ctrl + / and for multiple line comment you can use Ctrl + Shift + / after selecting the lines you want to comment in java editor.

On Mac/OS X you can use ? + / to comment out single lines or selected blocks.

Printing the correct number of decimal points with cout

You have to set the 'float mode' to fixed.

float num = 15.839;

// this will output 15.84
std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl;

List all devices, partitions and volumes in Powershell

On Windows Powershell:

Get-PSDrive 
[System.IO.DriveInfo]::getdrives()
wmic diskdrive
wmic volume

Also the utility dskwipe: http://smithii.com/dskwipe

dskwipe.exe -l

New og:image size for Facebook share?

UPDATE: The image size Must be larger than (600 x 315px)

The image size can be any size because Faceboook re-size the image width & height.

The default height is 208px & width is 398px for a post permalink:

www.facebook.com/{username}/posts/{post_id}

But for a timeline view:

www.facebook.com/{username}

width is 377px & height is 197px

I hope this will help you!

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

How to convert byte array to string and vice versa?

Heres a few methods that convert an array of bytes to a string. I've tested them they work well.

public String getStringFromByteArray(byte[] settingsData) {

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(settingsData);
    Reader reader = new BufferedReader(new InputStreamReader(byteArrayInputStream));
    StringBuilder sb = new StringBuilder();
    int byteChar;

    try {
        while((byteChar = reader.read()) != -1) {
            sb.append((char) byteChar);
        }
    }
    catch(IOException e) {
        e.printStackTrace();
    }

    return sb.toString();

}

public String getStringFromByteArray(byte[] settingsData) {

    StringBuilder sb = new StringBuilder();
    for(byte willBeChar: settingsData) {
        sb.append((char) willBeChar);
    }

    return sb.toString();

}

angular.service vs angular.factory

All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider(), value(), and constant().

The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation.

To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are:

enter image description here

For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from:

http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

angular2 manually firing click event on particular element

Günter Zöchbauer's answer is the right one. Just consider adding the following line:

showImageBrowseDlg() {
    // from http://stackoverflow.com/a/32010791/217408
    let event = new MouseEvent('click', {bubbles: true});
    event.stopPropagation();
    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);
  }

In my case I would get a "caught RangeError: Maximum call stack size exceeded" error if not. (I have a div card firing on click and the input file inside)

Getting MAC Address

Sometimes we have more than one net interface.

A simple method to find out the mac address of a specific interface, is:

def getmac(interface):

  try:
    mac = open('/sys/class/net/'+interface+'/address').readline()
  except:
    mac = "00:00:00:00:00:00"

  return mac[0:17]

to call the method is simple

myMAC = getmac("wlan0")

How to import spring-config.xml of one project into spring-config.xml of another project?

For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:

<import resource="classpath*:/spring-config.xml" />

How to Convert JSON object to Custom C# object?

Performance-wise, I found the ServiceStack's serializer a bit faster than then others. It's JsonSerializer class in ServiceStack.Text namespace.

https://github.com/ServiceStack/ServiceStack.Text

ServiceStack is available through NuGet package: https://www.nuget.org/packages/ServiceStack/

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

How to find keys of a hash?

For production code requiring a large compatibility with client browsers I still suggest Ivan Nevostruev's answer above with shim to ensure Object.keys in older browsers. However, it's possible to get the exact functionality requested using ECMA's new defineProperty feature.

As of ECMAScript 5 - Object.defineProperty

As of ECMA5 you can use Object.defineProperty() to define non-enumerable properties. The current compatibility still has much to be desired, but this should eventually become usable in all browsers. (Specifically note the current incompatibility with IE8!)

Object.defineProperty(Object.prototype, 'keys', {
  value: function keys() {
    var keys = [];
    for(var i in this) if (this.hasOwnProperty(i)) {
      keys.push(i);
    }
    return keys;
  },
  enumerable: false
});

var o = {
    'a': 1,
    'b': 2
}

for (var k in o) {
    console.log(k, o[k])
}

console.log(o.keys())

# OUTPUT
# > a 1
# > b 2
# > ["a", "b"]

However, since ECMA5 already added Object.keys you might as well use:

Object.defineProperty(Object.prototype, 'keys', {
  value: function keys() {
    return Object.keys(this);
  },
  enumerable: false
});

Original answer

Object.prototype.keys = function ()
{
  var keys = [];
  for(var i in this) if (this.hasOwnProperty(i))
  {
    keys.push(i);
  }
  return keys;
}

Edit: Since this answer has been around for a while I'll leave the above untouched. Anyone reading this should also read Ivan Nevostruev's answer below.

There's no way of making prototype functions non-enumerable which leads to them always turning up in for-in loops that don't use hasOwnProperty. I still think this answer would be ideal if extending the prototype of Object wasn't so messy.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I hope this will help somebody, I solved the problem like this

There was a problem because the database was not open. Command startup opens the database.

This you can solve with command alter database open in some case with alter database open resetlogs

$ sqlplus / sysdba

SQL> startup
ORACLE instance started.

Total System Global Area 1073741824 bytes
Fixed Size          8628936 bytes
Variable Size         624952632 bytes
Database Buffers      436207616 bytes
Redo Buffers            3952640 bytes
Database mounted.
Database opened.

SQL> conn user/pass123
Connected.

Is it possible to read the value of a annotation in java?

Yes, if your Column annotation has the runtime retention

@Retention(RetentionPolicy.RUNTIME)
@interface Column {
    ....
}

you can do something like this

for (Field f: MyClass.class.getFields()) {
   Column column = f.getAnnotation(Column.class);
   if (column != null)
       System.out.println(column.columnName());
}

UPDATE : To get private fields use

Myclass.class.getDeclaredFields()

The first day of the current month in php using date_modify as DateTime object

Ugly, (and doesn't use your method call above) but works:

echo 'First day of the month: ' . date('m/d/y h:i a',(strtotime('this month',strtotime(date('m/01/y')))));   

Property '...' has no initializer and is not definitely assigned in the constructor

Go to your tsconfig.json file and change "noImplicitReturns": false then add "strictPropertyInitialization": false to your tsconfig.json file under "compilerOptions" property. Here is what my tsconfig.json file looks like

tsconfig.json

{
  ...
  "compilerOptions": {
        ....
        "noImplicitReturns": false,
        ....
        "strictPropertyInitialization": false
  },
  "angularCompilerOptions": {
     ......
  }  
}

Hope this will help !! Good Luck

How to find a parent with a known class in jQuery?

<div id="412412412" class="input-group date">
     <div class="input-group-prepend">
          <button class="btn btn-danger" type="button">Button Click</button>
          <input type="text" class="form-control" value="">
      </div>
</div>

In my situation, i use this code:

$(this).parent().closest('.date').attr('id')

Hope this help someone.

Getting number of days in a month

  int month = Convert.ToInt32(ddlMonth.SelectedValue);/*Store month Value From page*/
  int year = Convert.ToInt32(txtYear.Value);/*Store Year Value From page*/
  int days = System.DateTime.DaysInMonth(year, month); /*this will store no. of days for month, year that we store*/

ImportError: No module named site on Windows

I up voted slckin's answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing

set

revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.

How do you get the process ID of a program in Unix or Linux using Python?

The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.

import os

program_pid = 0
program_name = "notepad.exe"

task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
    try:
        if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
            program_pid = int(line[29:34])
            break
    except:
        pass

print(program_pid)

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

How can I force a hard reload in Chrome for Android

In chrome,simply tick "Desktop site" and then remove tick!!

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

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

You can use a regular expression to test for a match and capture the first two digits:

import re

for i in range(1000):
    match = re.match(r'(1[56])', str(i))

    if match:
        print(i, 'begins with', match.group(1))

The regular expression (1[56]) matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.

Output:

15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16

Show loading gif after clicking form submit using jQuery

What about an onclick function:

    <form id="form">
    <input type="text" name="firstInput">
    <button type="button" name="namebutton" 
           onClick="$('#gif').css('visibility', 'visible');
                    $('#form').submit();">
    </form>

Of course you can put this in a function and then trigger it with an onClick

SyntaxError: Unexpected token o in JSON at position 1

the first parameters of function JSON.parse should be a String, and your data is a JavaScript object, so it will convert to a String [object object], you should use JSON.stringify before pass the data

JSON.parse(JSON.stringify(userData))

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

Adding a tooltip to an input box

Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.

_x000D_
_x000D_
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
    display: inline-block;    _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
    margin-left:9px;_x000D_
    width : 320px;_x000D_
    visibility: hidden;_x000D_
    background-color: #FFF;_x000D_
    border-radius:4px;_x000D_
    border: 1px solid #aeaeae;_x000D_
    position: absolute;_x000D_
    z-index: 1;_x000D_
    padding: 5px;_x000D_
    margin-top : -15px; _x000D_
    opacity: 0;_x000D_
    transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
    content: " ";_x000D_
    position: absolute;_x000D_
    top: 5%;_x000D_
    right: 100%;  _x000D_
    margin-top: -5px;_x000D_
    border-width: 5px;_x000D_
    border-style: solid;_x000D_
    border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
  <input type="text" />_x000D_
  <span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS: Hover one element, effect for multiple elements?

This worked for me in Firefox and Chrome and IE8...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
    <head>
        <style type="text/css">
        div.section:hover div.image, div.section:hover div.layer {
            border: solid 1px red;
        }
        </style>
    </head>
    <body>
        <div class="section">
            <div class="image"><img src="myImage.jpg" /></div>
            <div class="layer">Lorem Ipsum</div>
        </div>
    </body>
</html>

... you may want to test this with IE6 as well (I'm not sure if it'll work there).

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:

http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).

You want to deserialize into a single RootObject.

Can anyone explain me StandardScaler?

This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.

Make file echo displaying "$PATH" string

In the manual for GNU make, they talk about this specific example when describing the value function:

The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.

The syntax of the value function is:

 $(value variable)

Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)

The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:

 FOO = $PATH

 all:
         @echo $(FOO)
         @echo $(value FOO)

The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.

Does an HTTP Status code of 0 have any meaning?

Yes, some how the ajax call aborted. The cause may be following.

  1. Before completion of ajax request, user navigated to other page.
  2. Ajax request have timeout.
  3. Server is not able to return any response.

How to get file creation date/time in Bash/Debian?

ls -i file #output is for me 68551981
debugfs -R 'stat <68551981>' /dev/sda3 # /dev/sda3 is the disk on which the file exists

#results - crtime value
[root@loft9156 ~]# debugfs -R 'stat <68551981>' /dev/sda3
debugfs 1.41.12 (17-May-2010)
Inode: 68551981   Type: regular    Mode:  0644   Flags: 0x80000
Generation: 769802755    Version: 0x00000000:00000001
User:     0   Group:     0   Size: 38973440
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 76128
Fragment:  Address: 0    Number: 0    Size: 0
 ctime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
 atime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013
 mtime: 0x526931d7:1697cce0 -- Thu Oct 24 16:42:31 2013
**crtime: 0x52691f4d:7694eda4 -- Thu Oct 24 15:23:25 2013**
Size of extra inode fields: 28
EXTENTS:
(0-511): 352633728-352634239, (512-1023): 352634368-352634879, (1024-2047): 288392192-288393215, (2048-4095): 355803136-355805183, (4096-6143): 357941248-357943295, (6144
-9514): 357961728-357965098

How do I install PIL/Pillow for Python 3.6?

For python version 2.x you can simply use

  • pip install pillow

But for python version 3.X you need to specify

  • (sudo) pip3 install pillow

when you enter pip in bash hit tab and you will see what options you have

How do I avoid the specification of the username and password at every git push?

Saving Indefinitely

You can use the git-credential-store via

git config credential.helper store

which stores your password unencrypted in the file system:

Using this helper will store your passwords unencrypted on disk, protected only by filesystem permissions. If this is not an acceptable security tradeoff, try git-credential-cache, or find a helper that integrates with secure storage provided by your operating system.

With a Timeout

Use the git-credential-cache which by default stores the password for 15 minutes.

git config credential.helper cache

to set a different timeout, use --timeout (here 5 minutes)

git config credential.helper 'cache --timeout=300'

Secure Saving Indefinitely (OS X and Windows)

  • If you’re using a Mac, Git comes with an “osxkeychain” mode, which caches credentials in the secure keychain that’s attached to your system account. This method stores the credentials on disk, and they never expire, but they’re encrypted with the same system that stores HTTPS certificates and Safari auto-fills. Running the following on the command line will enable this feature: git config --global credential.helper osxkeychain. You'll need to store the credentials in the Keychain using the Keychain app as well.
  • If you’re using Windows, you can install a helper called “Git Credential Manager for Windows.” This is similar to the “osxkeychain” helper described above, but uses the Windows Credential Store to control sensitive information. It can be found at https://github.com/Microsoft/Git-Credential-Manager-for-Windows. [emphases mine]

Best way to use PHP to encrypt and decrypt passwords?

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

To Encrypt:

$iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
    MCRYPT_DEV_URANDOM
);

$encrypted = base64_encode(
    $iv .
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        $string,
        MCRYPT_MODE_CBC,
        $iv
    )
);

To Decrypt:

$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

$decrypted = rtrim(
    mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
        MCRYPT_MODE_CBC,
        $iv
    ),
    "\0"
);

Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.

See also:

Also, don't just use a "password" for an encryption key. Encryption keys are random strings.


Demo at 3v4l.org:

echo 'Encrypted:' . "\n";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="

echo "\n";

echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "

Why does Oracle not find oci.dll?

If you are using TOAD, you will need to download the 32-bit version of the Oracle Client Tools.

Since the Client Tools are different on a per-processor architecture basis, you probably need to install versions.

Should we pass a shared_ptr by reference or by value?

Not knowing time cost of shared_copy copy operation where atomic increment and decrement is in, I suffered from much higher CPU usage problem. I never expected atomic increment and decrement may take so much cost.

Following my test result, int32 atomic increment and decrement takes 2 or 40 times than non-atomic increment and decrement. I got it on 3GHz Core i7 with Windows 8.1. The former result comes out when no contention occurs, the latter when high possibility of contention occurs. I keep in mind that atomic operations are at last hardware based lock. Lock is lock. Bad to performance when contention occurs.

Experiencing this, I always use byref(const shared_ptr&) than byval(shared_ptr).

How do you find the current user in a Windows environment?

%USERNAME% is the correct answer in batch and other in Windows environments.

Another option is to use %USERPROFILE% to get the user's path, like C:\Users\username.

How to add include and lib paths to configure/make cycle?

Set LDFLAGS and CFLAGS when you run make:

$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make

If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib

What is stdClass in PHP?

Please bear in mind that 2 empty stdClasses are not strictly equal. This is very important when writing mockery expectations.

php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >

Bower: ENOGIT Git is not installed or not in the PATH

I solved the problem by install Git Bash from Download Git Bash.

Setting this option 3 when installing the software as shown bellow.

Setting Path variable

Finally select the project folder by right click using Bash as shown below.

enter image description here

and type

npm install

. It works for me.

How to make layout with View fill the remaining space?

use a Relativelayout to wrap LinearLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:round="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text="&lt;"/>
    <TextView
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:layout_weight = "1"/>
    <Button
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:text="&gt;"/>

</LinearLayout>

</RelativeLayout>`

Javascript call() & apply() vs bind()?

I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.

Checkbox Check Event Listener

Short answer: Use the change event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.

Single checkbox

Using querySelector.

_x000D_
_x000D_
var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Single checkbox with jQuery

_x000D_
_x000D_
$('input[name=checkbox]').change(function() {
  if ($(this).is(':checked')) {
    console.log("Checkbox is checked..")
  } else {
    console.log("Checkbox is not checked..")
  }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Multiple checkboxes

Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll instead of querySelector. Then use Array.filter and Array.map to extract checked values.

_x000D_
_x000D_
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []

/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/

// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function() {
    enabledSettings = 
      Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
      .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
      .map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
      
    console.log(enabledSettings)
  })
});
_x000D_
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

Multiple checkboxes with jQuery

_x000D_
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];

// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
  enabledSettings = checkboxes
    .filter(":checked") // Filter out unchecked boxes.
    .map(function() { // Extract values using jQuery map.
      return this.value;
    }) 
    .get() // Get array.
    
  console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

Java get last element of a collection

To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be

import java.util.List;

public static final <A> A getLastElement(List<A> list) {
    return list != null ? getElement(list, list.size() - 1) : null;
}

public static final <A> A getFirstElement(List<A> list) {
    return list != null ? getElement(list, 0) : null;
}   

private static final <A> A getElement(List<A> list, int pointer) {
    A res = null;
    if (list.size() > 0) {
        res = list.get(pointer);            
    }
    return res;
}

The convention adopted is that the first/last element of an empty list is null...

Delete a single record from Entity Framework?

I am using entity framework with LINQ. Following code was helpful for me;

1- For multiple records

 using (var dbContext = new Chat_ServerEntities())
 {
     var allRec= dbContext.myEntities;
     dbContext.myEntities.RemoveRange(allRec);
     dbContext.SaveChanges();
 }

2- For Single record

 using (var dbContext = new Chat_ServerEntities())
 {
     var singleRec = dbContext.ChatUserConnections.FirstOrDefault( x => x.ID ==1);// object your want to delete
     dbContext.ChatUserConnections.Remove(singleRec);
     dbContext.SaveChanges();
 }

Spring Data JPA Update @Query not updating?

I was able to get this to work. I will describe my application and the integration test here.

The Example Application

The example application has two classes and one interface that are relevant to this problem:

  1. The application context configuration class
  2. The entity class
  3. The repository interface

These classes and the repository interface are described in the following.

The source code of the PersistenceContext class looks as follows:

import com.jolbox.bonecp.BoneCPDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "net.petrikainulainen.spring.datajpa.todo.repository")
@PropertySource("classpath:application.properties")
public class PersistenceContext {

    protected static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    protected static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    protected static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";

    private static final String PROPERTY_PACKAGES_TO_SCAN = "net.petrikainulainen.spring.datajpa.todo.model";

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        BoneCPDataSource dataSource = new BoneCPDataSource();

        dataSource.setDriverClass(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setJdbcUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));

        return dataSource;
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);

        Properties jpaProperties = new Properties();
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
        jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }
}

Let's assume that we have a simple entity called Todo which source code looks as follows:

@Entity
@Table(name="todos")
public class Todo {

    public static final int MAX_LENGTH_DESCRIPTION = 500;
    public static final int MAX_LENGTH_TITLE = 100;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "description", nullable = true, length = MAX_LENGTH_DESCRIPTION)
    private String description;

    @Column(name = "title", nullable = false, length = MAX_LENGTH_TITLE)
    private String title;

    @Version
    private long version;
}

Our repository interface has a single method called updateTitle() which updates the title of a todo entry. The source code of the TodoRepository interface looks as follows:

import net.petrikainulainen.spring.datajpa.todo.model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface TodoRepository extends JpaRepository<Todo, Long> {

    @Modifying
    @Query("Update Todo t SET t.title=:title WHERE t.id=:id")
    public void updateTitle(@Param("id") Long id, @Param("title") String title);
}

The updateTitle() method is not annotated with the @Transactional annotation because I think that it is best to use a service layer as a transaction boundary.

The Integration Test

The Integration Test uses DbUnit, Spring Test and Spring-Test-DBUnit. It has three components which are relevant to this problem:

  1. The DbUnit dataset which is used to initialize the database into a known state before the test is executed.
  2. The DbUnit dataset which is used to verify that the title of the entity is updated.
  3. The integration test.

These components are described with more details in the following.

The name of the DbUnit dataset file which is used to initialize the database to known state is toDoData.xml and its content looks as follows:

<dataset>
    <todos id="1" description="Lorem ipsum" title="Foo" version="0"/>
    <todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>

The name of the DbUnit dataset which is used to verify that the title of the todo entry is updated is called toDoData-update.xml and its content looks as follows (for some reason the version of the todo entry was not updated but the title was. Any ideas why?):

<dataset>
    <todos id="1" description="Lorem ipsum" title="FooBar" version="0"/>
    <todos id="2" description="Lorem ipsum" title="Bar" version="0"/>
</dataset>

The source code of the actual integration test looks as follows (Remember to annotate the test method with the @Transactional annotation):

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersistenceContext.class})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class })
@DatabaseSetup("todoData.xml")
public class ITTodoRepositoryTest {

    @Autowired
    private TodoRepository repository;

    @Test
    @Transactional
    @ExpectedDatabase("toDoData-update.xml")
    public void updateTitle_ShouldUpdateTitle() {
        repository.updateTitle(1L, "FooBar");
    }
}

After I run the integration test, the test passes and the title of the todo entry is updated. The only problem which I am having is that the version field is not updated. Any ideas why?

I undestand that this description is a bit vague. If you want to get more information about writing integration tests for Spring Data JPA repositories, you can read my blog post about it.

What are the recommendations for html <base> tag?

Well, wait a minute. I don't think the base tag deserves this bad reputation.

The nice thing about the base tag is that it enables you to do complex URL rewrites with less hassle.

Here's an example. You decide to move http://example.com/product/category/thisproduct to http://example.com/product/thisproduct. You change your .htaccess file to rewrite the first URL to the second URL.

With the base tag in place, you do your .htaccess rewrite and that's it. No problem. But without the base tag, all of your relative links will break.

URL rewrites are often necessary, because tweaking them can help your site's architecture and search engine visibility. True, you'll need workarounds for the "#" and '' problems that folks mentioned. But the base tag deserves a place in the toolkit.

How do I find the caller of a method using stacktrace or reflection?

I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.

I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).

It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.

python tuple to dict

If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,

d = dict()
for x,y in t:
    if(d.has_key(y)):
        d[y].append(x)
    else:
        d[y] = [x]

Most efficient way to concatenate strings in JavaScript?

I have no comment on the concatenation itself, but I'd like to point out that @Jakub Hampl's suggestion:

For building strings in the DOM, in some cases it might be better to iteratively add to the DOM, rather then add a huge string at once.

is wrong, because it's based on a flawed test. That test never actually appends into the DOM.

This fixed test shows that creating the string all at once before rendering it is much, MUCH faster. It's not even a contest.

(Sorry this is a separate answer, but I don't have enough rep to comment on answers yet.)

convert an enum to another type of enum

Just cast one to int and then cast it to the other enum (considering that you want the mapping done based on value):

Gender2 gender2 = (Gender2)((int)gender1);

Determine distance from the top of a div to top of window with javascript

You can use .offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled:

var scrollTop     = $(window).scrollTop(),
    elementOffset = $('#my-element').offset().top,
    distance      = (elementOffset - scrollTop);

The distance variable now holds the distance from the top of the #my-element element and the top-fold.

Here is a demo: http://jsfiddle.net/Rxs2m/

Note that negative values mean that the element is above the top-fold.

Android: checkbox listener

you may also go for a simple View.OnClickListener:

satView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(((CompoundButton) view).isChecked()){
            System.out.println("Checked");
        } else {
            System.out.println("Un-Checked");
        }
    }
});

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

How to center a table of the screen (vertically and horizontally)

One way to center any element of unknown height and width both horizontally and vertically:

table {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

See Example

Alternatively, use a flex container:

.parent-element {
    display: flex;
    justify-content: center;
    align-items: center;
}

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

How to do a batch insert in MySQL

From the MySQL manual

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

How to set time zone in codeigniter?

add it in your index.php file, and it will work on all over your site

if ( function_exists( 'date_default_timezone_set' ) ) {
    date_default_timezone_set('Asia/Kolkata');
}

Python naming conventions for modules

foo module in python would be the equivalent to a Foo class file in Java

or

foobar module in python would be the equivalent to a FooBar class file in Java

Unable to create Android Virtual Device

There is a new possible error for this one related to the latest Android Wear technology. I was trying to get an emulator started for the wear SDK in preparation for next week. The API level only supports it in the latest build of 4.4.2 KitKat.

So if you are using something such as the wearable, it starts the default off still in Eclipse as 2.3.3 Gingerbread. Be sure that your target matches the lowest possible supported target. For the wearables its the latest 19 KitKat.

SQLite in Android How to update a specific row

you can try this...

db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

ng-repeat finish event

There is no need of creating a directive especially just to have a ng-repeat complete event.

ng-init does the magic for you.

  <div ng-repeat="thing in things" ng-init="$last && finished()">

the $last makes sure, that finished only gets fired, when the last element has been rendered to the DOM.

Do not forget to create $scope.finished event.

Happy Coding!!

EDIT: 23 Oct 2016

In case you also want to call the finished function when there is no item in the array then you may use the following workaround

<div style="display:none" ng-init="things.length < 1 && finished()"></div>
//or
<div ng-if="things.length > 0" ng-init="finished()"></div>

Just add the above line on the top of the ng-repeat element. It will check if the array is not having any value and call the function accordingly.

E.g.

<div ng-if="things.length > 0" ng-init="finished()"></div>
<div ng-repeat="thing in things" ng-init="$last && finished()">

How do I get the SharedPreferences from a PreferenceActivity in Android?

if you have a checkbox and you would like to fetch it's value ie true / false in any java file--

Use--

Context mContext;
boolean checkFlag;

checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`

How to convert a single char into an int

By this way You can convert char to int and int to char easily:

int charToInt(char c)
{
   int arr[]={0,1,2,3,4,5,6,7,8,9};
   return arr[c-'0'];
}

html vertical align the text inside input type button

I've given up trying to align my text on buttons! Now, if I need it, I'm using <a> tags, like so:

<a href="javascript:void();" style="display:block;font-size:1em;padding:5px;cursor:default;" onclick="document.getElementById('form').submit();">Submit</a>

So, if the document's font size is 12px, my "button" will have 22px height. And the text will be vertically align. That in theory, because, in some casses, an unequal padding of "6px 5px 4px 5px" will do the job done.

Although, is a hack, this technique is pretty good for solving compatibility issues in older browsers too, like IE6!

Finding first and last index of some value in a list in Python

s.index(x[, i[, j]])

index of the first occurrence of x in s (at or after index i and before index j)

Delete certain lines in a txt file via a batch file

If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}" should do the trick.

Location of ini/config files in linux/unix?

For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc to a structure below ~/.config. For example, Qt 4 uses ~/.config/<vendor>/<programname> with the default settings of QSettings. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config, XFCE does use ~/.config).

Python's equivalent of && (logical-and) in an if-statement

I'm getting an error in the IF conditional. What am I doing wrong?

There reason that you get a SyntaxError is that there is no && operator in Python. Likewise || and ! are not valid Python operators.

Some of the operators you may know from other languages have a different name in Python. The logical operators && and || are actually called and and or. Likewise the logical negation operator ! is called not.

So you could just write:

if len(a) % 2 == 0 and len(b) % 2 == 0:

or even:

if not (len(a) % 2 or len(b) % 2):

Some additional information (that might come in handy):

I summarized the operator "equivalents" in this table:

+------------------------------+---------------------+
|  Operator (other languages)  |  Operator (Python)  |
+==============================+=====================+
|              &&              |         and         |
+------------------------------+---------------------+
|              ||              |         or          |
+------------------------------+---------------------+
|              !               |         not         |
+------------------------------+---------------------+

See also Python documentation: 6.11. Boolean operations.

Besides the logical operators Python also has bitwise/binary operators:

+--------------------+--------------------+
|  Logical operator  |  Bitwise operator  |
+====================+====================+
|        and         |         &          |
+--------------------+--------------------+
|         or         |         |          |
+--------------------+--------------------+

There is no bitwise negation in Python (just the bitwise inverse operator ~ - but that is not equivalent to not).

See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.

The logical operators (like in many other languages) have the advantage that these are short-circuited. That means if the first operand already defines the result, then the second operator isn't evaluated at all.

To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually evaluated because of the print statements:

>>> def print_and_return(value):
...     print(value)
...     return value

>>> res = print_and_return(False) and print_and_return(True)
False

As you can see only one print statement is executed, so Python really didn't even look at the right operand.

This is not the case for the binary operators. Those always evaluate both operands:

>>> res = print_and_return(False) & print_and_return(True);
False
True

But if the first operand isn't enough then, of course, the second operator is evaluated:

>>> res = print_and_return(True) and print_and_return(False);
True
False

To summarize this here is another Table:

+-----------------+-------------------------+
|   Expression    |  Right side evaluated?  |
+=================+=========================+
| `True` and ...  |           Yes           |
+-----------------+-------------------------+
| `False` and ... |           No            |
+-----------------+-------------------------+
|  `True` or ...  |           No            |
+-----------------+-------------------------+
| `False` or ...  |           Yes           |
+-----------------+-------------------------+

The True and False represent what bool(left-hand-side) returns, they don't have to be True or False, they just need to return True or False when bool is called on them (1).

So in Pseudo-Code(!) the and and or functions work like these:

def and(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return evaluate(expr2)
    else:
        return left

def or(expr1, expr2):
    left = evaluate(expr1)
    if bool(left):
        return left
    else:
        return evaluate(expr2)

Note that this is pseudo-code not Python code. In Python you cannot create functions called and or or because these are keywords. Also you should never use "evaluate" or if bool(...).

Customizing the behavior of your own classes

This implicit bool call can be used to customize how your classes behave with and, or and not.

To show how this can be customized I use this class which again prints something to track what is happening:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        print('__bool__ called on {!r}'.format(self))
        return bool(self.value)

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

So let's see what happens with that class in combination with these operators:

>>> if Test(True) and Test(False):
...     pass
__bool__ called on Test(True)
__bool__ called on Test(False)

>>> if Test(False) or Test(False):
...     pass
__bool__ called on Test(False)
__bool__ called on Test(False)

>>> if not Test(True):
...     pass
__bool__ called on Test(True)

If you don't have a __bool__ method then Python also checks if the object has a __len__ method and if it returns a value greater than zero. That might be useful to know in case you create a sequence container.

See also 4.1. Truth Value Testing.

NumPy arrays and subclasses

Probably a bit beyond the scope of the original question but in case you're dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool call will raise the dreaded ValueError:

>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

In these cases you can use the logical and function from NumPy which performs an element-wise and (or or):

>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False,  True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False,  True,  True])

If you're dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:

>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False,  True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False,  True,  True])

(1)

That the bool call on the operands has to return True or False isn't completely correct. It's just the first operand that needs to return a boolean in it's __bool__ method:

class Test(object):
    def __init__(self, value):
        self.value = value

    def __bool__(self):
        return self.value

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return "{self.__class__.__name__}({self.value})".format(self=self)

>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)

That's because and actually returns the first operand if the first operand evaluates to False and if it evaluates to True then it returns the second operand:

>>> x1
Test(10)
>>> x2
Test(False)

Similarly for or but just the other way around:

>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)

However if you use them in an if statement the if will also implicitly call bool on the result. So these finer points may not be relevant for you.

How to run functions in parallel?

If you are a windows user and using python 3, then this post will help you to do parallel programming in python.when you run a usual multiprocessing library's pool programming, you will get an error regarding the main function in your program. This is because the fact that windows has no fork() functionality. The below post is giving a solution to the mentioned problem .

http://python.6.x6.nabble.com/Multiprocessing-Pool-woes-td5047050.html

Since I was using the python 3, I changed the program a little like this:

from types import FunctionType
import marshal

def _applicable(*args, **kwargs):
  name = kwargs['__pw_name']
  code = marshal.loads(kwargs['__pw_code'])
  gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])
  defs = marshal.loads(kwargs['__pw_defs'])
  clsr = marshal.loads(kwargs['__pw_clsr'])
  fdct = marshal.loads(kwargs['__pw_fdct'])
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  del kwargs['__pw_name']
  del kwargs['__pw_code']
  del kwargs['__pw_defs']
  del kwargs['__pw_clsr']
  del kwargs['__pw_fdct']
  return func(*args, **kwargs)

def make_applicable(f, *args, **kwargs):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  kwargs['__pw_name'] = f.__name__  # edited
  kwargs['__pw_code'] = marshal.dumps(f.__code__)   # edited
  kwargs['__pw_defs'] = marshal.dumps(f.__defaults__)  # edited
  kwargs['__pw_clsr'] = marshal.dumps(f.__closure__)  # edited
  kwargs['__pw_fdct'] = marshal.dumps(f.__dict__)   # edited
  return _applicable, args, kwargs

def _mappable(x):
  x,name,code,defs,clsr,fdct = x
  code = marshal.loads(code)
  gbls = globals() #gbls = marshal.loads(gbls)
  defs = marshal.loads(defs)
  clsr = marshal.loads(clsr)
  fdct = marshal.loads(fdct)
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  return func(x)

def make_mappable(f, iterable):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  name = f.__name__    # edited
  code = marshal.dumps(f.__code__)   # edited
  defs = marshal.dumps(f.__defaults__)  # edited
  clsr = marshal.dumps(f.__closure__)  # edited
  fdct = marshal.dumps(f.__dict__)  # edited
  return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)

After this function , the above problem code is also changed a little like this:

from multiprocessing import Pool
from poolable import make_applicable, make_mappable

def cube(x):
  return x**3

if __name__ == "__main__":
  pool    = Pool(processes=2)
  results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]
  print([result.get(timeout=10) for result in results])

And I got the output as :

[1, 8, 27, 64, 125, 216]

I am thinking that this post may be useful for some of the windows users.

How to make a local variable (inside a function) global

If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:

class StatefulFunction( object ):
    def __init__( self ):
        self.public_value = 'foo'

    def __call__( self ):
        return self.public_value


>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I update my Hibernate JPA to 2.1 and It works.

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

Difference between View and ViewGroup in Android

In simple words View is the UI element which we interact with when we use an app,like button,edit text and image etc.View is the child class of Android.view.View While View group is the container which contains all these views inside it in addition to several othe viewgroups like linear or Frame Layout etc. Example if we design & take the root element as Linear layout now our main layout is linear layout inside it we can take another view group (i.e another Linear layout) & many other views like buttons or textview etc.

The ResourceConfig instance does not contain any root resource classes

I ran across this problem with JBOSS EAP 6.1. I was able to deploy my code through eclipse to the JBOSS server but once I attempted to deploy the file as a WAR file to JBOSS I started getting this error.

The solution was configuring the web.xml to work properly with JBOSS by allowing the two to work together.

The following two lines were commented out in web.xml to allow JBOSS to do it's own configurations

<!--  
    <init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>com.your.package</param-value>
</init-param> -->

And then add the following context params after

<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>resteasy.scan.resources</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>resteasy.scan.providers</param-name>
    <param-value>false</param-value>
</context-param>

Thymeleaf: Concatenation - Could not parse as expression

Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:

th:text="${'static_content - ' + you_variable}"

CSS file not refreshing in browser

The fix is called "hard refresh" http://en.wikipedia.org/wiki/Wikipedia:Bypass_your_cache

In most Windows and Linux browsers: Hold down Ctrl and press F5.

In Apple Safari: Hold down ? Shift and click the Reload toolbar button.

In Chrome and Firefox for Mac: Hold down both ? Cmd+? Shift and press R.

Remove last character of a StringBuilder?

Another alternative

for(String serverId : serverIds) {
   sb.append(",");
   sb.append(serverId); 
}
sb.deleteCharAt(0);

Can I display the value of an enum with printf()?

The correct answer to this has already been given: no, you can't give the name of an enum, only it's value.

Nevertheless, just for fun, this will give you an enum and a lookup-table all in one and give you a means of printing it by name:

main.c:

#include "Enum.h"

CreateEnum(
        EnumerationName,
        ENUMValue1,
        ENUMValue2,
        ENUMValue3);

int main(void)
{
    int i;
    EnumerationName EnumInstance = ENUMValue1;

    /* Prints "ENUMValue1" */
    PrintEnumValue(EnumerationName, EnumInstance);

    /* Prints:
     * ENUMValue1
     * ENUMValue2
     * ENUMValue3
     */
    for (i=0;i<3;i++)
    {
        PrintEnumValue(EnumerationName, i);
    }
    return 0;
}

Enum.h:

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

#ifdef NDEBUG
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name;
#define PrintEnumValue(name,value)
#else
#define CreateEnum(name,...) \
    typedef enum \
    { \
        __VA_ARGS__ \
    } name; \
    const char Lookup##name[] = \
        #__VA_ARGS__;
#define PrintEnumValue(name, value) print_enum_value(Lookup##name, value)
void print_enum_value(const char *lookup, int value);
#endif

Enum.c

#include "Enum.h"

#ifndef NDEBUG
void print_enum_value(const char *lookup, int value)
{
    char *lookup_copy;
    int lookup_length;
    char *pch;

    lookup_length = strlen(lookup);
    lookup_copy = malloc((1+lookup_length)*sizeof(char));
    strcpy(lookup_copy, lookup);

    pch = strtok(lookup_copy," ,");
    while (pch != NULL)
    {
        if (value == 0)
        {
            printf("%s\n",pch);
            break;
        }
        else
        {
            pch = strtok(NULL, " ,.-");
            value--;
        }
    }

    free(lookup_copy);
}
#endif

Disclaimer: don't do this.

Encode html entities in javascript

replaceHtmlEntities(text) {
  var tagsToReplace = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
  };
  var newtext = text;
  for (var tag in tagsToReplace) {
    if (Reflect.apply({}.hasOwnProperty, this, [tagsToReplace, tag])) {
      var regex = new RegExp(tag, 'g');
      newtext = newtext.replace(regex, tagsToReplace[tag]);
    }
  }
  return newtext;
}

How to use Git?

You might want to start with an introduction to version control. This guide is specific to subversion, but the core concepts can be applied to most version control systems. After you have the basics, you can delve into the git guide.

How to get substring from string in c#?

You could do this manually or using IndexOf method.

Manually:

int index = 43;
string piece = myString.Substring(index);

Using IndexOf you can see where the fullstop is:

int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);

Cannot find R.layout.activity_main

The stupid mistake I made to cause this error was to have the wrong package string in my AndroidManifest.xml file. I'd left the string set in the tutorial, but had used my own when setting up the project.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="COM.YOU.YOURAPPNAME"
android:versionCode="1"
android:versionName="1.0" >

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

Spring Data JpaRepository

The Spring Data JpaRepository defines the following two methods:

  • getOne, which returns an entity proxy that is suitable for setting a @ManyToOne or @OneToOne parent association when persisting a child entity.
  • findById, which returns the entity POJO after running the SELECT statement that loads the entity from the associated table

However, in your case, you didn't call either getOne or findById:

Person person = personRepository.findOne(1L);

So, I assume the findOne method is a method you defined in the PersonRepository. However, the findOne method is not very useful in your case. Since you need to fetch the Person along with is roles collection, it's better to use a findOneWithRoles method instead.

Custom Spring Data methods

You can define a PersonRepositoryCustom interface, as follows:

public interface PersonRepository
    extends JpaRepository<Person, Long>, PersonRepositoryCustom { 

}

public interface PersonRepositoryCustom {
    Person findOneWithRoles(Long id);
}

And define its implementation like this:

public class PersonRepositoryImpl implements PersonRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Person findOneWithRoles(Long id)() {
        return entityManager.createQuery("""
            select p 
            from Person p
            left join fetch p.roles
            where p.id = :id 
            """, Person.class)
        .setParameter("id", id)
        .getSingleResult();
    }
}

That's it!

What is the difference between __init__ and __call__?

__call__ allows to return arbitrary values, while __init__ being an constructor returns the instance of class implicitly. As other answers properly pointed out, __init__ is called just once, while it's possible to call __call__ multiple times, in case the initialized instance is assigned to intermediate variable.

>>> class Test:
...     def __init__(self):
...         return 'Hello'
... 
>>> Test()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: __init__() should return None, not 'str'
>>> class Test2:
...     def __call__(self):
...         return 'Hello'
... 
>>> Test2()()
'Hello'
>>> 
>>> Test2()()
'Hello'
>>> 

Skipping Iterations in Python

for i in iterator:
    try:
        # Do something.
        pass
    except:
        # Continue to next iteration.
        continue

Include jQuery in the JavaScript Console

Modern browsers (tested on Chrome, Firefox, Safari) implement some helper functions using the dollar sign $ that are very similar to jQuery (if the website doesn't define something using window.$).

Those utilities are quite useful for selecting elements in the DOM and modifying them.

Docs: Chrome, Firefox

In Javascript, how to conditionally add a member to an object?

Wrap into an object

Something like this is a bit cleaner

 const obj = {
   X: 'dataX',
   Y: 'dataY',
   //...
 }

 const list = {
   A: true && 'dataA',
   B: false && 'dataB',
   C: 'A' != 'B' && 'dataC',
   D: 2000 < 100 && 'dataD',
   // E: conditionE && 'dataE',
   // F: conditionF && 'dataF',
   //...
 }

 Object.keys(list).map(prop => list[prop] ? obj[prop] = list[prop] : null)

Wrap into an array

Or if you want to use Jamie Hill's method and have a very long list of conditions then you must write ... syntax multiple times. To make it a bit cleaner, you can just wrap them into an array, then use reduce() to return them as a single object.

const obj = {
  X: 'dataX',
  Y: 'dataY',
  //...

...[
  true && { A: 'dataA'},
  false && { B: 'dataB'},
  'A' != 'B' && { C: 'dataC'},
  2000 < 100 && { D: 'dataD'},
  // conditionE && { E: 'dataE'},
  // conditionF && { F: 'dataF'},
  //...

 ].reduce(( v1, v2 ) => ({ ...v1, ...v2 }))
}

Or using map() function

const obj = {
  X: 'dataX',
  Y: 'dataY',
  //...
}

const array = [
  true && { A: 'dataA'},
  false &&  { B: 'dataB'},
  'A' != 'B' && { C: 'dataC'},
  2000 < 100 && { D: 'dataD'},
  // conditionE && { E: 'dataE'},
  // conditionF && { F: 'dataF'},
  //...

 ].map(val => Object.assign(obj, val))

Port 443 in use by "Unable to open process" with PID 4

I had the same problem and solved by doing following.

Go to Task Manager, click on services tab, order by pid's than if you find the related process, kill it otherwise, right click and click on show details, the process should be shown now. order by pid's than kill the related process.

Where am I? - Get country

First, get the LocationManager. Then, call LocationManager.getLastKnownPosition. Then create a GeoCoder and call GeoCoder.getFromLocation. Do this is in a separate thread!! This will give you a list of Address objects. Call Address.getCountryName and you got it.

Keep in mind that the last known position can be a bit stale, so if the user just crossed the border, you may not know about it for a while.

What is the curl error 52 "empty reply from server"?

It happens when you are trying to access secure Website like Https.

I hope you missed 's'

Try Changing URL to curl -sS -u "username:password" https://www.example.com/backup.php

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

Not able to pip install pickle in python 3.6

You can pip install pickle by running command pip install pickle-mixin. Proceed to import it using import pickle. This can be then used normally.

How to validate an OAuth 2.0 access token for a resource server?

OAuth v2 specs indicates:

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

Find element in List<> that contains a value

I would use .Equals() for comparison instead of ==.

Like so:

MyClass item = MyList.Find(item => item.name.Equals("foo"));

Particularly because it gives you options like StringComparison, which is awesome. Example:

MyClass item = MyList.Find(item => item.name.Equals("foo", StringComparison.InvariantCultureIgnoreCase);

This enables your code to ignore special characters, upper and lower case. There are more options.

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

Creating NSData from NSString in Swift

Convert String to Data

extension String {
    func toData() -> Data {
        return Data(self.utf8)
    }
}

Convert Data to String

extension Data {
      func toString() -> String {
          return String(decoding: self, as: UTF8.self)
      }
   }

$ is not a function - jQuery error

There are quite lots of answer based on situation.

1) Try to replace '$' with "jQuery"

2) Check that code you are executed are always below the main jquery script.

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){

});
</script>

3) Pass $ into the function and add "jQuery" as a main function like below.

<script type="text/javascript">
jQuery(document).ready(function($){

});
</script>

How do I run a shell script without using "sh" or "bash" commands?

In this example the file will be called myShell

First of all we will need to make this file we can just start off by typing the following:

sudo nano myShell

Notice we didn't put the .sh extension? That's because when we run it from the terminal we will only need to type myShell in order to run our command!

Now, in nano the top line MUST be #!/bin/bash then you may leave a new line before continuing.

For demonstration I will add a basic Hello World! response

So, I type the following:

echo Hello World!

After that my example should look like this:

#!/bin/bash
echo Hello World!

Now save the file and then run this command:

chmod +x myShell

Now we have made the file executable we can move it to /usr/bin/ by using the following command:

sudo cp myShell /usr/bin/

Congrats! Our command is now done! In the terminal we can type myShell and it should say Hello World!

redirect while passing arguments

I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".

To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P

So maybe:

def super_cool_logic():
    # execute common code here

@app.route("/foo")
def do_foo():
    # do some logic here
    super_cool_logic()
    return render_template("foo.html")

@app.route("/baz")
def do_baz():
    if some_condition:
        return render_template("baz.html")
    else:
        super_cool_logic()
        return render_template("foo.html", messages={"main":"Condition failed on page baz"})

I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)

How to sort ArrayList<Long> in decreasing order?

Using List.sort() and Comparator.comparingLong()

numberList.sort(Comparator.comparingLong(x -> -x));

Build error: "The process cannot access the file because it is being used by another process"

When I ended the process .Net Core Host, everything built fine. I didn't have to close Visual Studio or do change anything else.

Move layouts up when soft keyboard is shown?

Here is full manifest code

<activity
        android:name=".activities.MainActivity"
        android:windowSoftInputMode="adjustResize"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Uncaught SyntaxError: Unexpected token u in JSON at position 0

I had this issue for 2 days, let me show you how I fixed it.

This was how the code looked when I was getting the error:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.response);
    console.log(data)
}

This is what I changed to get the result I wanted:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.responseText);
    console.log(data)
}

So all I really did was change this.response to this.responseText.

How to create a box when mouse over text in pure CSS?

You can write like this:

CSS

span{
    background: none repeat scroll 0 0 #F8F8F8;
    border: 5px solid #DFDFDF;
    color: #717171;
    font-size: 13px;
    height: 30px;
    letter-spacing: 1px;
    line-height: 30px;
    margin: 0 auto;
    position: relative;
    text-align: center;
    text-transform: uppercase;
    top: -80px;
    left:-30px;
    display:none;
    padding:0 20px;

}
span:after{
    content:'';
    position:absolute;
    bottom:-10px;
    width:10px;
    height:10px;
    border-bottom:5px solid #dfdfdf;
    border-right:5px solid #dfdfdf;
    background:#f8f8f8;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
}
p{
    margin:100px;
    float:left;
    position:relative;
    cursor:pointer;
}

p:hover span{
    display:block;
}

HTML

<p>Hover here<span>some text here ?</span></p>

Check this http://jsfiddle.net/UNs9J/1/

how to set select element as readonly ('disabled' doesnt pass select value on server)

You can simulate a readonly select box using the CSS pointer-events property:

select[readonly]
{
    pointer-events: none;
}

The HTML tabindex property will also prevent it from being selected by keyboard tabbing:

<select tabindex="-1">

_x000D_
_x000D_
select[readonly]_x000D_
{_x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
  background: #fafafa;_x000D_
  border: 1px solid #ccc;_x000D_
  color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
  display:block;_x000D_
  width: 20rem;_x000D_
  padding: 0.5rem;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
  <input type="text" value="this is a normal text box">_x000D_
  <input type="text" readonly value="this is a readonly text box">_x000D_
  <select readonly tabindex="-1">_x000D_
    <option>This is a readonly select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
  <select>_x000D_
    <option>This is a normal select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

git is not installed or not in the PATH

Install git and tortoise git for windows and make sure it is on your path, (the installer for Tortoise Git includes options for the command line tools and ensuring that it is on the path - select them).

You will need to close and re-open any existing command line sessions for the changes to take effect.

Then you should be able to run npm install successfully or move on to the next problem!

Is it possible in Java to catch two exceptions in the same catch block?

For Java < 7 you can use if-else along with Exception:

try {
    // common logic to handle both exceptions
} catch (Exception ex) {
    if (ex instanceof Exception1 || ex instanceof Exception2) {

    }
    else {
        throw ex;
        // or if you don't want to have to declare Exception use
        // throw new RuntimeException(ex);
    }
}

Edited and replaced Throwable with Exception.

Looping through rows in a DataView

You can iterate DefaultView as the following code by Indexer:

DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow oRow = dt.DefaultView[i].Row;
    // Do your stuff with oRow
    // ...
}

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

Use this to convert String to Blob. Where connection is the connection to db object.

    String strContent = s;
    byte[] byteConent = strContent.getBytes();
    Blob blob = connection.createBlob();//Where connection is the connection to db object. 
    blob.setBytes(1, byteContent);

How to implement a custom AlertDialog View

Custom AlertDialog

This full example includes passing data back to the Activity.

enter image description here

Create a custom layout

A layout with an EditText is used for this simple example, but you can replace it with anything you like.

custom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:paddingLeft="20dp"
              android:paddingRight="20dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Use the dialog in code

The key parts are

  • using setView to assign the custom layout to the AlertDialog.Builder
  • sending any data back to the activity when a dialog button is clicked.

This is the full code from the example project shown in the image above:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void showAlertDialogButtonClicked(View view) {

        // create an alert builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Name");

        // set the custom layout
        final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
        builder.setView(customLayout);

        // add a button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // send data from the AlertDialog to the Activity
                EditText editText = customLayout.findViewById(R.id.editText);
                sendDialogDataToActivity(editText.getText().toString());
            }
        });

        // create and show the alert dialog
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    // do something with the data coming from the AlertDialog
    private void sendDialogDataToActivity(String data) {
        Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
    }
}

Notes

  • If you find yourself using this in multiple places, then consider making a DialogFragment subclass as is described in the documentation.

See also

How to embed matplotlib in pyqt - for Dummies

For those looking for a dynamic solution to embed Matplotlib in PyQt5 (even plot data using drag and drop). In PyQt5 you need to use super on the main window class to accept the drops. The dropevent function can be used to get the filename and rest is simple:

def dropEvent(self,e):
        """
        This function will enable the drop file directly on to the 
        main window. The file location will be stored in the self.filename
        """
        if e.mimeData().hasUrls:
            e.setDropAction(QtCore.Qt.CopyAction)
            e.accept()
            for url in e.mimeData().urls():
                if op_sys == 'Darwin':
                    fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
                else:
                    fname = str(url.toLocalFile())
            self.filename = fname
            print("GOT ADDRESS:",self.filename)
            self.readData()
        else:
            e.ignore() # just like above functions  

For starters the reference complete code gives this output: enter image description here

Windows equivalent of linux cksum command

Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/

Can the Android layout folder contain subfolders?

The answer is no.

I would like to draw your attention towards this book Pro Android 2 that states:

It is also worth noting a few constraints regarding resources. First, Android supports only a linear list of files within the predefined folders under res. For example, it does not support nested folders under the layout folder (or the other folders under res).

Second, there are some similarities between the assets folder and the raw folder under res. Both folders can contain raw files, but the files within raw are considered resources and the files within assets are not.

Note that because the contents of the assets folder are not considered resources, you can put an arbitrary hierarchy of folders and files within it.

HTML5 tag for horizontal line break

I am answering this old question just because it still shows up in google queries and I think one optimal answer is missing. Try this code: use ::before or ::after

See Align <hr> to the left in an HTML5-compliant way

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

Updating setuptools has worked out fine for me.

sudo pip install --upgrade setuptools

What is the Python equivalent of Matlab's tic and toc functions?

The absolute best analog of tic and toc would be to simply define them in python.

def tic():
    #Homemade version of matlab tic and toc functions
    import time
    global startTime_for_tictoc
    startTime_for_tictoc = time.time()

def toc():
    import time
    if 'startTime_for_tictoc' in globals():
        print "Elapsed time is " + str(time.time() - startTime_for_tictoc) + " seconds."
    else:
        print "Toc: start time not set"

Then you can use them as:

tic()
# do stuff
toc()

How to get the previous URL in JavaScript?

If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:

window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")

Then, in your new route, you can do the following to retrieve the previous URL:

window.history.state.prevUrl // your previous url

No shadow by default on Toolbar?

I ended up setting my own drop shadow for the toolbar, thought it might helpful for anyone looking for it:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="top"
              android:orientation="vertical">

    <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
                                       android:layout_width="match_parent"
                                       android:layout_height="wrap_content"
                                       android:background="@color/color_alizarin"
                                       android:titleTextAppearance="@color/White"
                                       app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <FrameLayout android:layout_width="match_parent"
                 android:layout_height="match_parent">

        <!-- **** Place Your Content Here **** -->

        <View android:layout_width="match_parent"
              android:layout_height="5dp"
              android:background="@drawable/toolbar_dropshadow"/>

    </FrameLayout>

</LinearLayout>

@drawable/toolbar_dropshadow:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
       android:shape="rectangle">

    <gradient android:startColor="@android:color/transparent"
              android:endColor="#88333333"
              android:angle="90"/>

</shape>

@color/color_alizarin

<color name="color_alizarin">#e74c3c</color>

enter image description here

Issue pushing new code in Github

?? EASY: All you need is a forced push. Because you might have created readme.md file on Github and you haven't pulled it yet.

git push -f origin master

And here's a GIF.

git push -f origin master

?? BEWARE: Using force can change the history for other folks on the same project. Basically, if you don't care about a file being deleted for everyone, just go ahead. Especially if you're the only dev on the project.

ImportError: No module named PytQt5

After getting the help from @Blender, @ekhumoro and @Dan, I understand the Linux and Python more than before. Thank you. I got the an idea by @ekhumoro, it is I didn't install PyQt5 correctly. So I delete PyQt5 folder and download again. And redo everything from very start.

After redoing, I got the error as my last update at my question. So, when I search at stack, I got the following solution from here

sudo ln -s /usr/include/python2.7 /usr/local/include/python2.7

And then, I did "sudo make" and "sudo make install" step by step. After "sudo make install", I got the following error. But I ignored it and I created a simple design with qt designer. And I converted it into python file by pyuic5. Everything are going well.

install -m 755 -p /home/thura/PyQt/pyuic5 /usr/bin/
strip /usr/bin/pyuic5
strip:/usr/bin/pyuic5: File format not recognized
make: [install_pyuic5] Error 1 (ignored)

Entity Framework Query for inner join

You could use a navigation property if its available. It produces an inner join in the SQL.

from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

simple HTTP server in Java using only Java SE API

Once upon a time I was looking for something similar - a lightweight yet fully functional HTTP server that I could easily embed and customize. I found two types of potential solutions:

  • Full servers that are not all that lightweight or simple (for an extreme definition of lightweight.)
  • Truly lightweight servers that aren't quite HTTP servers, but glorified ServerSocket examples that are not even remotely RFC-compliant and don't support commonly needed basic functionality.

So... I set out to write JLHTTP - The Java Lightweight HTTP Server.

You can embed it in any project as a single (if rather long) source file, or as a ~50K jar (~35K stripped) with no dependencies. It strives to be RFC-compliant and includes extensive documentation and many useful features while keeping bloat to a minimum.

Features include: virtual hosts, file serving from disk, mime type mappings via standard mime.types file, directory index generation, welcome files, support for all HTTP methods, conditional ETags and If-* header support, chunked transfer encoding, gzip/deflate compression, basic HTTPS (as provided by the JVM), partial content (download continuation), multipart/form-data handling for file uploads, multiple context handlers via API or annotations, parameter parsing (query string or x-www-form-urlencoded body), etc.

I hope others find it useful :-)

How to read single Excel cell value

Please try this. Maybe this could help you. It works for me.

string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//_row,_column your column & row number 
//eg: string sValue = (sheet.Cells[i + 9, 12] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//sValue has your value

JQUERY: Uncaught Error: Syntax error, unrecognized expression

Try using:

console.log($("#"+d));

This will remove the extra quotes you were using.

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

C# Error "The type initializer for ... threw an exception

This problem can occur if a class tries to get value of a non-existent key in web.config.

For example, the class has a static variable ClientID

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

but the web.config doesn't contain the 'GoogleCalendarApplicationClientID' key, then the error will be thrown on any static function call or any class instance creation

UICollectionView - dynamic cell height?

We can maintain dynamic height for collection view cell without xib(only using storyboard).

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout*)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

        NSAttributedString* labelString = [[NSAttributedString alloc] initWithString:@"Your long string goes here" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]}];
        CGRect cellRect = [labelString boundingRectWithSize:CGSizeMake(cellWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        return CGSizeMake(cellWidth, cellRect.size.height);
}

Make sure that numberOfLines in IB should be 0.

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

Capturing Groups From a Grep RegEx

str="1w 2d 1h"
regex="([0-9])w ([0-9])d ([0-9])h"
if [[ $str =~ $regex ]]
then
    week="${BASH_REMATCH[1]}"
    day="${BASH_REMATCH[2]}"
    hour="${BASH_REMATCH[3]}"
    echo $week --- $day ---- $hour
fi

output: 1 --- 2 ---- 1

Conditional Count on a field

Try this:

SELECT Count(Student_ID) as 'StudentCount' 
FROM CourseSemOne
where Student_ID=3 
Having Count(Student_ID) < 6 and Count(Student_ID) > 0;

How to use callback with useState hook in react

With React16.x, if you want to invoke a callback function on state change using useState hook, you can use the useEffect hook attached to the state change.

import React, { useEffect } from 'react';

useEffect(() => {
  props.getChildChange(name); // using camelCase for variable name is recommended.
}, [name]); // this will call getChildChange when ever name changes.

Display a jpg image on a JPanel

You could also use

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

Is it safe to delete the "InetPub" folder?

If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.

Change IIS7 Inetpub path

  • Open %windir%\system32\inetsrv\config\applicationhost.config and search for

%SystemDrive%\inetpub\wwwroot

  • Change the path.

How to make remote REST call inside Node.js? any CURL?

var http = require('http');
var url = process.argv[2];

http.get(url, function(response) {
  var finalData = "";

  response.on("data", function (data) {
    finalData += data.toString();
  });

  response.on("end", function() {
    console.log(finalData.length);
    console.log(finalData.toString());
  });

});

How to add directory to classpath in an application run profile in IntelliJ IDEA?

Set "VM options" like: "-cp $Classpath$;your_classpath"

VM options

H2 database error: Database may be already in use: "Locked by another process"

I had the same problem. in Intellj, when i want to use h2 database when my program was running i got the same error. For solve this problem i changed the connection url from

spring.datasource.url=jdbc:h2:file:~/ipinbarbot

to:

spring.datasource.url=jdbc:h2:~/ipinbarbot;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE

And then my problem gone away. now i can connect to "ipinbarbot" database when my program is. If you use Hibernate, also don't forget to have:

spring.jpa.hibernate.ddl-auto = update

goodluck

The shortest possible output from git log containing author and date

All aforementioned suggestions use %s placeholder for subject. I'll recommend to use %B because %s formatting preserves new lines and multiple lines commit message appears squashed.

git log --pretty=format:"%h%x09%an%x09%ai%x09%B"

Get Line Number of certain phrase in file Python

lookup = 'the dog barked'

with open(filename) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print 'found at line:', num

How to install sshpass on mac?

Following worked for me

curl -O -L  https://sourceforge.net/projects/sshpass/files/sshpass/1.06/sshpass-1.06.tar.gz && tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06/
./configure
sudo make install

Accessing private member variables from prototype-defined functions

You need to change 3 things in your code:

  1. Replace var privateField = "hello" with this.privateField = "hello".
  2. In the prototype replace privateField with this.privateField.
  3. In the non-prototype also replace privateField with this.privateField.

The final code would be the following:

TestClass = function(){
    this.privateField = "hello";
    this.nonProtoHello = function(){alert(this.privateField)};
}

TestClass.prototype.prototypeHello = function(){alert(this.privateField)};

var t = new TestClass();

t.prototypeHello()

Using 'make' on OS X

Have you installed the Apple developer tools? What happens if you type gcc -v ?

It look as if you do not have downloaded the development stuff. You can get it for free (after registration) from http://developer.apple.com/

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

Rendering raw html with reactjs

I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:

<script dangerouslySetInnerHTML={{ __html: `</script>
   <link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>

What do "branch", "tag" and "trunk" mean in Subversion repositories?

In addition to what Nick has said you can find out more at Streamed Lines: Branching Patterns for Parallel Software Development

enter image description here

In this figure main is the trunk, rel1-maint is a branch and 1.0 is a tag.

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

Getting files by creation date in .NET

@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"

I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally

GetFiles  done 437834 in00:00:20.4812480
process files  done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2)  done 437834 in00:00:20.7412646

Why use def main()?

Without the main sentinel, the code would be executed even if the script were imported as a module.

React-Native: Module AppRegistry is not a registered callable module

Hopefully this can save someone a headache. I got this error after upgrading my react-native version. Confusingly it only appeared on the android side of things.

My file structure includes an index.ios.js and an index.android.js. Both contain the code:

AppRegistry.registerComponent('App', () => App);

What I had to do was, in android/app/src/main/java/com/{projectName}/MainApplication.java, change index to index.android:

@Override
protected String getJSMainModuleName() {
    return "index.android"; // was "index"
}

Then in app/build/build.gradle, change the entryFile from index.js to index.android.js

project.ext.react = [
    entryFile: "index.android.js" // was index.js"
]

Search for one value in any column of any table inside a database

All third=party tools mentioned below are 100% free.

I’ve used ApexSQL Search with good success for searching both objects and data in tables. It comes with several other features such as relationship diagrams and such…

I was a bit slow on large (40GB TFS Database) databases though…

enter image description here

Apart from this there is also SSMS Tools pack that offers a lot of other features that are quite useful even though these are not directly related to searching text.

Removing time from a Date object?

What you want is impossible.

A Date object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date object directly with System.out.println(date), it will always be formatted in a default format that includes the time. There is nothing you can do to change that.

Instead of somehow trying to use class Date for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat to format the date in whatever format you want.

The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.

Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate class would be what you'd use.

Converting binary to decimal integer output

I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

def __degree(number):
    power = 1

    while number % (10**power) != number:
        power += 1

    return power

def __getDigits(number):
    digits = []
    degree = __degree(number)

    for x in range(0, degree):
        digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
    return digits

def binaryToDecimal(number):
    list = __getDigits(number)
    decimalValue = 0
    for x in range(0, len(list)):
        if (list[x] is 1):
            decimalValue += 2**(len(list) - x - 1)
    return decimalValue

Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

binaryNum = int(input("Enter a binary number: "))

print(binaryToDecimal(binaryNum))

This prints out the correct result. Cheers!

MySQL query String contains

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

Wget output document and headers to STDOUT

This will not work:

wget -q -S -O - google.com 1>wget.txt 2>&1

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

wget -q -S -O - google.com 2>&1 1>wget.txt

Kotlin's List missing "add", "remove", Map missing "put", etc?

Agree with all above answers of using MutableList but you can also add/remove from List and get a new list as below.

val newListWithElement = existingList + listOf(element)
val newListMinusElement = existingList - listOf(element)

Or

val newListWithElement = existingList.plus(element)
val newListMinusElement = existingList.minus(element)

How to make a rest post call from ReactJS code?

I think this way also a normal way. But sorry, I can't describe in English ((

_x000D_
_x000D_
    submitHandler = e => {_x000D_
    e.preventDefault()_x000D_
    console.log(this.state)_x000D_
    fetch('http://localhost:5000/questions',{_x000D_
        method: 'POST',_x000D_
        headers: {_x000D_
            Accept: 'application/json',_x000D_
                    'Content-Type': 'application/json',_x000D_
        },_x000D_
        body: JSON.stringify(this.state)_x000D_
    }).then(response => {_x000D_
            console.log(response)_x000D_
        })_x000D_
        .catch(error =>{_x000D_
            console.log(error)_x000D_
        })_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

https://googlechrome.github.io/samples/fetch-api/fetch-post.html

fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })

How can I force division to be floating point? Division keeps rounding down to 0?

Just making any of the parameters for division in floating-point format also produces the output in floating-point.

Example:

>>> 4.0/3
1.3333333333333333

or,

>>> 4 / 3.0
1.3333333333333333

or,

>>> 4 / float(3)
1.3333333333333333

or,

>>> float(4) / 3
1.3333333333333333

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

Just found a quick and simple solution to discover type of a variable.

ES6

export const isType = (type, val) => val.constructor.name.toLowerCase() === type.toLowerCase();

ES5

function isType(type, val) {
  return val.constructor.name.toLowerCase() === type.toLowerCase();
}

Examples:

isType('array', [])
true
isType('array', {})
false
isType('string', '')
true
isType('string', 1)
false
isType('number', '')
false
isType('number', 1)
true
isType('boolean', 1)
false
isType('boolean', true)
true

EDIT

Improvment to prevent 'undefined' and 'null' values:

ES6

export const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());

ES5

function isType(type, val) {
  return !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
}

psycopg2: insert multiple rows with one query

Another nice and efficient approach - is to pass rows for insertion as 1 argument, which is array of json objects.

E.g. you passing argument:

[ {id: 18, score: 1}, { id: 19, score: 5} ]

It is array, which may contain any amount of objects inside. Then your SQL looks like:

INSERT INTO links (parent_id, child_id, score) 
SELECT 123, (r->>'id')::int, (r->>'score')::int 
FROM unnest($1::json[]) as r 

Notice: Your postgress must be new enough, to support json

How to access the last value in a vector?

Package data.table includes last function

library(data.table)
last(c(1:10))
# [1] 10

Does VBA have Dictionary Structure?

An additional dictionary example that is useful for containing frequency of occurence.

Outside of loop:

Dim dict As New Scripting.dictionary
Dim MyVar as String

Within a loop:

'dictionary
If dict.Exists(MyVar) Then
    dict.Item(MyVar) = dict.Item(MyVar) + 1 'increment
Else
    dict.Item(MyVar) = 1 'set as 1st occurence
End If

To check on frequency:

Dim i As Integer
For i = 0 To dict.Count - 1 ' lower index 0 (instead of 1)
    Debug.Print dict.Items(i) & " " & dict.Keys(i)
Next i

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )

How do I load a file from resource folder?

To read the files from src/resources folder then try this :

DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));

public static File getFileHandle(String fileName){
       return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}

in case of non static reference:

return new File(getClass().getClassLoader().getResource(fileName).getFile());

Want to show/hide div based on dropdown box selection

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box It's working well in my case

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("select").change(function(){_x000D_
        $(this).find("option:selected").each(function(){_x000D_
            var optionValue = $(this).attr("value");_x000D_
            if(optionValue){_x000D_
                $(".box").not("." + optionValue).hide();_x000D_
                $("." + optionValue).show();_x000D_
            } else{_x000D_
                $(".box").hide();_x000D_
            }_x000D_
        });_x000D_
    }).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
    .box{_x000D_
        color: #fff;_x000D_
        padding: 50px;_x000D_
        display: none;_x000D_
        margin-top: 10px;_x000D_
    }_x000D_
    .red{ background: #ff0000; }_x000D_
    .green{ background: #228B22; }_x000D_
    .blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div>_x000D_
        <select>_x000D_
            <option>Choose Color</option>_x000D_
            <option value="red">Red</option>_x000D_
            <option value="green">Green</option>_x000D_
            <option value="blue">Blue</option>_x000D_
        </select>_x000D_
    </div>_x000D_
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to update Ruby to 1.9.x on Mac?

I'll disagree with The Tin Man here. I regard rbenv as preferable to RVM. rbenv doesn't interfere drastically with your shell the way RVM does, and it lets you add separate Ruby installations in ordinary folders that you can examine directly. It allows you to compile Ruby yourself. Good outline of the differences here: https://github.com/sstephenson/rbenv/wiki/Why-rbenv%3F

I provide instructions for compiling Ruby 1.9 for rbenv here. Further, more detailed information here. I have used this technique with easy success on Snow Leopard, Lion, and Mountain Lion.

How to read a PEM RSA private key from .NET

Check http://msdn.microsoft.com/en-us/library/dd203099.aspx

under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;


public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
    try{ 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 
    } 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
    try{ 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 
    } 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
    else 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 
} 

JavaScript or jQuery browser back button click detector

In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2) {
    //Do your code here
}

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

PHP class not found but it's included

It 'happened to me! The problem is that somehow you include a file with the same file name of the class thus invalidating the same class!

Check the path of inclusion and these checks files with the same name!

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...

Should URL be case sensitive?

Depends on the hosting os. Sites that are hosted on Windows tend to be case insensitive as the underlying file system is case insensitive. Sites hosted on Unix type systems tend to be case sensitive as their underlying file systems are typically case sensitive. The host name part of the URL is always case insensitive, it's the rest of the path that varies.

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

error: function returns address of local variable

char b = "blah"; 

should be:

char *b = "blah"; 

Query an XDocument for elements by name at any depth

This my variant of the solution based on LINQ and the Descendants method of the XDocument class

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        XDocument xml = XDocument.Parse(@"
        <root>
          <child id='1'/>
          <child id='2'>
            <subChild id='3'>
                <extChild id='5' />
                <extChild id='6' />
            </subChild>
            <subChild id='4'>
                <extChild id='7' />
            </subChild>
          </child>
        </root>");

        xml.Descendants().Where(p => p.Name.LocalName == "extChild")
                         .ToList()
                         .ForEach(e => Console.WriteLine(e));

        Console.ReadLine();
    }
}

Results:

For more details on the Desendants method take a look here.

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

Multiple conditions in ngClass - Angular 4

I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.

So inside an *ngFor:

<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>

And inside the component:

section = 'allwork';

shouldShrink(cat1, cat2) {
    return this.section === cat1 || this.section === cat2 ? false : true;
}

Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.

Is this very likely to create a memory leak in Tomcat?

Sometimes this has to do with configuration changes. When we upgraded from Tomncat 6.0.14 to 6.0.26, we had seen something similar. here is the solution http://www.skill-guru.com/blog/2010/08/22/tomcat-6-0-26-shutdown-reports-a-web-application-created-a-threadlocal-threadlocal-has-been-forcibly-removed/

Difference between Select Unique and Select Distinct

SELECT UNIQUE is old syntax supported by Oracle's flavor of SQL. It is synonymous with SELECT DISTINCT.

Use SELECT DISTINCT because this is standard SQL, and SELECT UNIQUE is non-standard, and in database brands other than Oracle, SELECT UNIQUE may not be recognized at all.

Create a temporary table in MySQL with an index from a select

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement

Example :

CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;

smtp configuration for php mail

php's email() function hands the email over to a underlying mail transfer agent which is usually postfix on linux systems

so the preferred method on linux is to configure your postfix to use a relayhost, which is done by a line of

relayhost = smtp.example.com

in /etc/postfix/main.cf

however in the OP's scenario I somehow suspect that it's a job that his hosting team should have done

Sequelize OR condition object

For Sequelize 4

Query

SELECT * FROM Student WHERE LastName='Doe' 
AND (FirstName = "John" or FirstName = "Jane") AND Age BETWEEN 18 AND 24 

Syntax with Operators

const Op = require('Sequelize').Op;

var r = await to (Student.findAll(
{
  where: {
    LastName: "Doe",
    FirstName: {
      [Op.or]: ["John", "Jane"]
    },
    Age: {
      // [Op.gt]: 18
      [Op.between]: [18, 24]
    }
  }
}
));

Notes

  • For better security Sequelize recommends dropping alias operators $ (e.g $and, $or ...)
  • Unless you have {freezeTableName: true} set in the table model then Sequelize will query against the plural form of its name ( Student -> Students )

Change some value inside the List<T>

I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:

 foreach (var mc in list.Where(x => x.Name == "height"))  
     mc.Value = 30;

Clear terminal in Python

A perhaps cheesy way to clear the screen, but one that will work on any platform I know of, is as follows:

for i in xrange(0,100):
    print ""

Valid to use <a> (anchor tag) without href attribute?

It is valid. You can, for example, use it to show modals (or similar things that respond to data-toggle and data-target attributes).

Something like:

<a role="button" data-toggle="modal" data-target=".bs-example-modal-sm" aria-hidden="true"><i class="fa fa-phone"></i></a>

Here I use the font-awesome icon, which is better as a a tag rather than a button, to show a modal. Also, setting role="button" makes the pointer change to an action type. Without either href or role="button", the cursor pointer does not change.

Getting Keyboard Input

You can use Scanner class

Import first :

import java.util.Scanner;

Then you use like this.

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

Side note : If you are using nextInt() with nextLine() you probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine() then is not gonna to be executed with desired behaviour. Read more in how to solve it in this previous question Skipping nextLine using nextInt.

How to see indexes for a database or table in MySQL?

we can directly see the indexes on to the table if we know the index name with below :

select * from all_indexes where index_name= 'your index'

Windows-1252 to UTF-8 encoding

If you want to rename multiple files in a single command - let's say you want to convert all *.txt files - here is the command:

find . -name "*.txt" -exec iconv -f WINDOWS-1252 -t UTF-8 {} -o {}.ren \; -a -exec mv {}.ren {} \;

How do I download a package from apt-get without installing it?

Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).

apt-get install -d -o=dir::cache=/tmp whateveryouwant

Class constructor type in typescript?

How can I declare a class type, so that I ensure the object is a constructor of a general class?

A Constructor type could be defined as:

 type AConstructorTypeOf<T> = new (...args:any[]) => T;

 class A { ... }

 function factory(Ctor: AConstructorTypeOf<A>){
   return new Ctor();
 }

const aInstance = factory(A);

Onchange open URL via select - jQuery

Try this code its working Firefox, Chrome, IE

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="" selected>---Select---</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>
<option value="https://www.google.com">Google</option>