Programs & Examples On #Web slice

Use querystring variables in MVC controller

Davids, I had the exact same problem as you. MVC is not intuitive and it seems when they designed it the kiddos didn't understand the purpose or importance of an intuitive querystring system for MVC.

Querystrings are not set in the routes at all (RouteConfig). They are add-on "extra" parameters to Actions in the Controller. This is very confusing as the Action parameters are designed to process BOTH paths AND Querystrings. If you added parameters and they did not work, add a second one for the querystring as so:

This would be your action in your Controller class that catches the ID (which is actually just a path set in your RouteConfig file as a typical default path in MVC):

public ActionResult Hello(int id)

But to catch querystrings an additional parameter in your Controller needs to be the added (which is NOT set in your RouteConfig file, by the way):

public ActionResult Hello(int id, string start, string end)

This now listens for "/Hello?start=&end=" or "/Hello/?start=&end=" or "/Hello/45?start=&end=" assuming the "id" is set to optional in the RouteConfig.cs file.

If you wanted to create a "custom route" in the RouteConfig file that has no "id" path, you could leave off the "id" or other parameter after the action in that file. In that case your parameters in your Action method in the controller would process just querystrings.

I found this extremely confusing myself so you are not alone! They should have designed a simple way to add querystring routes for both specific named strings, any querystring name, and any number of querystrings in the RouteConfig file configuration design. By not doing that it leaves the whole use of querystrings in MVC web applications as questionable, which is pretty bizarre since querystrings have been a stable part of the World Wide Web since the mid-1990's. :(

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

check if a string matches an IP address pattern in python?

If you use Python3, you can use ipaddress module http://docs.python.org/py3k/library/ipaddress.html. Example:

>>> import ipaddress

>>> ipv6 = "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
>>> ipv4 = "192.168.2.10"
>>> ipv4invalid = "266.255.9.10"
>>> str = "Tay Tay"

>>> ipaddress.ip_address(ipv6)
IPv6Address('2001:db8:a0b:12f0::1')

>>> ipaddress.ip_address(ipv4)
IPv4Address('192.168.2.10')

>>> ipaddress.ip_address(ipv4invalid)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
    address)
ValueError: '266.255.9.10' does not appear to be an IPv4 or IPv6 address

>>> ipaddress.ip_address(str)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'Tay Tay' does not appear to be an IPv4 or IPv6 address

Purge Kafka Topic

Temporarily update the retention time on the topic to one second:

kafka-topics.sh --zookeeper <zkhost>:2181 --alter --topic <topic name> --config retention.ms=1000

And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics

kafka-configs.sh --zookeeper <zkhost>:2181 --entity-type topics --alter --entity-name <topic name> --add-config retention.ms=1000

then wait for the purge to take effect (about one minute). Once purged, restore the previous retention.ms value.

Get user info via Google API

I'm using PHP and solved this by using version 1.1.4 of google-api-php-client

Assuming the following code is used to redirect a user to the Google authentication page:

 $client = new Google_Client();
 $client->setAuthConfigFile('/path/to/config/file/here');
 $client->setRedirectUri('https://redirect/url/here');
 $client->setAccessType('offline'); //optional
 $client->setScopes(['profile']); //or email
 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 exit();

Assuming a valid authentication code is returned to the redirect_url, the following will generate a token from the authentication code as well as provide basic profile information:

 //assuming a successful authentication code is return
 $authentication_code = 'code-returned-by-google';
 $client = new Google_Client();
 //.... configure $client object code goes here
 $client->authenticate($authentication_code);
 $token_data = $client->getAccessToken();

 //get user email address
 $google_oauth =new Google_Service_Oauth2($client);
 $google_account_email = $google_oauth->userinfo->get()->email;
 //$google_oauth->userinfo->get()->familyName;
 //$google_oauth->userinfo->get()->givenName;
 //$google_oauth->userinfo->get()->name;
 //$google_oauth->userinfo->get()->gender;
 //$google_oauth->userinfo->get()->picture; //profile picture

However, location is not returned. New YouTube accounts don't have YouTube specific usernames

find filenames NOT ending in specific extensions on Unix?

Linux/OS X:

Starting from the current directory, recursively find all files ending in .dll or .exe

find . -type f | grep -P "\.dll$|\.exe$"

Starting from the current directory, recursively find all files that DON'T end in .dll or .exe

find . -type f | grep -vP "\.dll$|\.exe$"

Notes:

(1) The P option in grep indicates that we are using the Perl style to write our regular expressions to be used in conjunction with the grep command. For the purpose of excecuting the grep command in conjunction with regular expressions, I find that the Perl style is the most powerful style around.

(2) The v option in grep instructs the shell to exclude any file that satisfies the regular expression

(3) The $ character at the end of say ".dll$" is a delimiter control character that tells the shell that the filename string ends with ".dll"

How to inspect Javascript Objects

How about alert(JSON.stringify(object)) with a modern browser?

In case of TypeError: Converting circular structure to JSON, here are more options: How to serialize DOM node to JSON even if there are circular references?

The documentation: JSON.stringify() provides info on formatting or prettifying the output.

How can I add shadow to the widget in flutter?

Add box shadow to container in flutter

  Container(
      margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
      height: double.infinity,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10)
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 5,
            blurRadius: 7,
            offset: Offset(0, 3), // changes position of shadow
          ),
        ],
      ),
  )

Here is my output enter image description here

How to apply a CSS filter to a background image

You can create a div over the image you want to apply the filter and use backdrop-filter to its CSS class. Check out this link

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Is there a System.Web.WebPages.Razor.dll in the bin folder of your web app? What is its version? (Explorer right click, properties) I'm guessing it's not 3.0.0.0. Just get the nuget packages for v3.0.0.0, perhaps by copying the packages folder from your colleague. Or install it manually: http://www.nuget.org/packages/Microsoft.AspNet.Mvc/3.0.20105.1

EDIT: if you copy stuff from your colleague, also copy the relevant version numbers into packages.config. This is what tells nuget which versions to put into the packages folder.

Access parent URL from iframe

The following line will work: document.location.ancestorOrigins[0] this one returns the ancestor domain name.

Django optional url parameters

Django > 2.0 version:

The approach is essentially identical with the one given in Yuji 'Tomita' Tomita's Answer. Affected, however, is the syntax:

# URLconf
...

urlpatterns = [
    path(
        'project_config/<product>/',
        views.get_product, 
        name='project_config'
    ),
    path(
        'project_config/<product>/<project_id>/',
        views.get_product,
        name='project_config'
    ),
]


# View (in views.py)
def get_product(request, product, project_id='None'):
    # Output the appropriate product
    ...

Using path() you can also pass extra arguments to a view with the optional argument kwargs that is of type dict. In this case your view would not need a default for the attribute project_id:

    ...
    path(
        'project_config/<product>/',
        views.get_product,
        kwargs={'project_id': None},
        name='project_config'
    ),
    ...

For how this is done in the most recent Django version, see the official docs about URL dispatching.

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

underscore.js is using the following

toString = Object.prototype.toString;

_.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

_.isObject = function(obj) {
    return obj === Object(obj);
  };

_.isFunction = function(obj) {
    return toString.call(obj) == '[object Function]';
  };

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

List of IP addresses/hostnames from local network in Python

I have done following code to get the IP of MAC known device. This can be modified accordingly to obtain all IPs with some string manipulation. Hope this will help you.

#running windows cmd line  statement and put output into a string
cmd_out = os.popen("arp -a").read()
line_arr = cmd_out.split('\n')
line_count = len(line_arr)


#search in all lines for ip
for i in range(0, line_count):
    y = line_arr[i]
    z = y.find(mac_address)

    #if mac address is found then get the ip using regex matching
    if z > 0:
        ip_out= re.search('[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+', y, re.M | re.I)

How to set a header for a HTTP GET request, and trigger file download?

I'm adding another option. The answers above were very useful for me, but I wanted to use jQuery instead of ic-ajax (it seems to have a dependency with Ember when I tried to install through bower). Keep in mind that this solution only works on modern browsers.

In order to implement this on jQuery I used jQuery BinaryTransport. This is a nice plugin to read AJAX responses in binary format.

Then you can do this to download the file and send the headers:

$.ajax({
    url: url,
    type: 'GET',
    dataType: 'binary',
    headers: headers,
    processData: false,
    success: function(blob) {
        var windowUrl = window.URL || window.webkitURL;
        var url = windowUrl.createObjectURL(blob);
        anchor.prop('href', url);
        anchor.prop('download', fileName);
        anchor.get(0).click();
        windowUrl.revokeObjectURL(url);
    }
});

The vars in the above script mean:

  • url: the URL of the file
  • headers: a Javascript object with the headers to send
  • fileName: the filename the user will see when downloading the file
  • anchor: it is a DOM element that is needed to simulate the download that must be wrapped with jQuery in this case. For example $('a.download-link').

Start index for iterating Python list

stdlib will hook you up son!

deque.rotate():

#!/usr/local/bin/python2.7

from collections import deque

a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
a.rotate(3)
deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])

How do I create and store md5 passwords in mysql

just get the hash by following line and store it into the database:

$encryptedValue = md5("YOUR STRING");

How do I open the "front camera" on the Android platform?

To open the back camera:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

To open the front camera:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT)  // Tested on API 24 Android version 7.0(Samsung S6)
     }
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
         cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
     }
     else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)  // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).

How do I check form validity with angularjs?

When you put <form> tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form> will satisfy:

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.

So to check form validity, you can check value of $scope.yourformname.$valid property of scope.

More information you can get at Developer's Guide section about forms.

Eclipse C++ : "Program "g++" not found in PATH"

First Install MinGW or other C/C++ compiler as it's required by Eclipse C++.

Use https://sourceforge.net/projects/mingw-w64/ as unbelievably the download.cnet.com's version has malware attached.

Back to Eclipse.

Now in all those path settings that the Eclipse Help manual talks about INSTEAD of typing the path, Select Variables and

**MINGW_HOME** 

and do so for all instances which would ask for the compiler's path.

First would be to click Preferences of the whatever project and C/C++ General then Paths and Symbols and add the

**MINGW_HOME** to those paths of for the compiler.

Next simply add the home directory to the Build Variables under the C++/C Build

Build Variables Screen Capture

find index of an int in a list

It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:

int index = 0; int i = accounts[index];

How to calculate 1st and 3rd quartiles?

try that way:

dfo = sorted(df.time_diff)

n=len(dfo)

Q1=int((n+3)/4)  
Q3=int((3*n+1)/4)  


print("Q1 position: ", Q1, "Q1 position: " ,Q3)

print("Q1 value: ", dfo[Q1], "Q1 value: ", dfo[Q3])

Remove a folder from git tracking

if file is committed and pushed to github then you should run

git rm --fileName

git ls-files to make sure that the file is removed or untracked

git commit -m "UntrackChanges"

git push

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

Using @angular/forms when you use a <form> tag it automatically creates a FormGroup.

For every contained ngModel tagged <input> it will create a FormControl and add it into the FormGroup created above; this FormControl will be named into the FormGroup using attribute name.

Example:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

Said this, the answer to your question follows.

When you mark it as standalone: true this will not happen (it will not be added to the FormGroup).

Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474

Remote desktop connection protocol error 0x112f

If the server accessible with RPC (basically, if you can access a shared folder on it), you could free some memory and thus let the RDP service work properly. The following windows native commands can be used:

To get the list of memory consuming tasks:

tasklist /S <remote_server> /V /FI "MEMUSAGE gt 10000"

To kill a task by its name:

taskkill /S <remote_server> /IM <process_image_name> /F

To show the list of desktop sessions:

qwinsta.exe /SERVER:<remote_server>

To close an old abandoned desktop session:

logoff <session_id> /SERVER:<remote_server> 

After some memory is freed, the RDP should start working.

Response Buffer Limit Exceeded

If you are looking for the reason and don't want to fight the system settings, these are two major situations I faced:

  1. You may have an infinite loop without next or recordest.movenext
  2. Your text data is very large but you think it is not! The common reason for this situation is to copy-paste an Image from Microsoft word directly into the editor and so the server translates the image to data objects and saves it in your text field. This can easily occupies the database resources and causes buffer problem when you call the data again.

Frequency table for a single variable

The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.

If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True

Here is an example:

import pandas as pd
import numpy as np

my_series = pd.Series([1,2,2,3,3,3])

print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

Notice here that the item returned is a pandas.Series

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

what is the unsigned datatype?

According to C17 6.7.2 §2:

Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers

— void
— char
— signed char
— unsigned char
— short, signed short, short int, or signed short int
— unsigned short, or unsigned short int
— int, signed, or signed int
— unsigned, or unsigned int
— long, signed long, long int, or signed long int
— unsigned long, or unsigned long int
— long long, signed long long, long long int, or signed long long int
— unsigned long long, or unsigned long long int
— float
— double
— long double
— _Bool
— float _Complex
— double _Complex
— long double _Complex
— atomic type specifier
— struct or union specifier
— enum specifier
— typedef name

So in case of unsigned int we can either write unsigned or unsigned int, or if we are feeling crazy, int unsigned. The latter since the standard is stupid enough to allow "...may occur in any order, possibly intermixed". This is a known flaw of the language.

Proper C code uses unsigned int.

check android application is in foreground or not?

@user370305's answer is error prone and discouraged by Android OS Developers (check https://groups.google.com/forum/#!msg/android-developers/zH-2bovZSLg/L2YM8Z1N-HwJ)

There is a much more simpler approach:

On a BaseActivity that all Activities extend:

protected static boolean isVisible = false;

@Override
public void onResume() {
   super.onResume();
   setVisible(true);
}

@Override
public void onPause() {
    super.onPause();
    setVisible(false);
}

Whenever you need to check if any of your application activities is in foreground just check isVisible();

To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Take the content of a list and append it to another list

That seems fairly reasonable for what you're trying to do.

A slightly shorter version which leans on Python to do more of the heavy lifting might be:

for logs in mydir:

    for line in mylog:
        #...if the conditions are met
        list1.append(line)

    if any(True for line in list1 if "string" in line):
        list2.extend(list1)
    del list1

    ....

The (True for line in list1 if "string" in line) iterates over list and emits True whenever a match is found. any() uses short-circuit evaluation to return True as soon as the first True element is found. list2.extend() appends the contents of list1 to the end.

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

CodeIgniter -> Get current URL relative to base url

Running Latest Code Igniter 3.10

$this->load->helper('uri'); // or you can autoload it in config

print base_url($this->uri->uri_string());

bower proxy configuration

create .bowerrc file in you home directory and adding this to the file worked for me

{

 "directory": "bower_components",
 "proxy": "http://youProxy:yourPort",
  "https-proxy":"http://yourProxy:yourPort"
}

What's the difference between faking, mocking, and stubbing?

Stub - an object that provides predefined answers to method calls.

Mock - an object on which you set expectations.

Fake - an object with limited capabilities (for the purposes of testing), e.g. a fake web service.

Test Double is the general term for stubs, mocks and fakes. But informally, you'll often hear people simply call them mocks.

Unioning two tables with different number of columns

Add extra columns as null for the table having less columns like

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

CreateProcess: No such file or directory

I had a very long path, and there's a file in there somewhere (not gcc.exe) but another file, that gcc.exe is accessing from the path..

So when I cleared the path, it worked

C:\MinGW>cd bin


C:\MinGW\bin>where gcc.exe
C:\MinGW\bin\gcc.exe
C:\Perl64\site\bin\gcc.exe

^^ So running gcc from there will definitely run the ming gcc.exe

C:\MinGW\bin>type file6.c
#include<stdio.h>
void main()
{
int num1,num2;
scanf("%2d %4d",&num1,&num2);
printf("a=%d b=%d",num1,num2);
scanf("%d",&num1);
//flushall();
printf("c=%d",num1);
}

Compiling it I got this error

C:\MinGW\bin>gcc file6.c
gcc: error: CreateProcess: No such file or directory

My PATH was huge

C:\MinGW\bin>path
PATH=C:\Windows\system32;C:\Windows;C:\Windows\system32\wbem;C:\P......

C:\MinGW\bin>path | grep -io "ming"

It didn't have ming there.

C:\MinGW\bin>echo MING | grep -io "ming" MING

(and yeah that grep works..the path didn't have ming there)

Clearing my path completely, led it to work!

C:\MinGW\bin>set PATH=

C:\MinGW\bin>gcc file6.c

C:\MinGW\bin>

So, it's not clear yet precisely what it was in the PATH that led to the clash. What directory, what file.

Update-

The above seems to be correct to me but to add, it's also not a simple case of something earlier in the path clashing.. because normally the current directory takes precedence. And it does here in so far as gcc --version shows it's running the ming one and not one of the ones in a conflicting directory. So there's something funny going on that, if the conflicting directory is in the path) , one has to either do .\gcc or add . to the start of the path or add c:\MinGW\bin before any conflicting directories in the path. this is the case even when you're in C:\MinGW\bin and that's strange. And when it gives an error, it is still running Ming's gcc but (For some reason) looking at the conflicting directory too, as I see from process monitor. There may be more of an answer here http://wiki.codeblocks.org/index.php?title=Installing_MinGW_with_Vista in the link mentioned in the very upvoted answer here

That's Ming32 bit..

Looking at Ming 64bit, probably has te same issue, but I see, interestingly, it comes with a bat file that (sensibly) actually puts the bin directory at the tart of the path. And it looks like that is a standard way of running Ming gcc properly.

The code::blocks IDE (sensibly) also puts the bin directory at the start of the path. If you run a C program that shows environment variables then you see that.

Load local JSON file into variable

The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.

You can load it using var fs = require('fs');

Asynchronous

fs.readFile('./content.json', (err, data) => {
    if (err)
      console.log(err);
    else {
      var json = JSON.parse(data);
    //your code using json object
    }
})

Synchronous

var json = JSON.parse(fs.readFileSync('./content.json').toString());

What is the most efficient way to create HTML elements using jQuery?

Actually, if you're doing $('<div>'), jQuery will also use document.createElement().

(Just take a look at line 117).

There is some function-call overhead, but unless performance is critical (you're creating hundreds [thousands] of elements), there isn't much reason to revert to plain DOM.

Just creating elements for a new webpage is probably a case in which you'll best stick to the jQuery way of doing things.

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

How to Find And Replace Text In A File With C#

Read all file content. Make a replacement with String.Replace. Write content back to file.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

Node.js Port 3000 already in use but it actually isn't?

I've seen the same thing and tried all the suggestions above without success. Here are steps that resolve it for me: - turn off wifi - npm start (this should work) - turn on wifi

I'm not exactly sure what the root issue is but that resolved it for me.

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

Get the name of an object's type

Update

To be precise, I think OP asked for a function that retrieves the constructor name for a particular object. In terms of Javascript, object does not have a type but is a type of and in itself. However, different objects can have different constructors.

Object.prototype.getConstructorName = function () {
   var str = (this.prototype ? this.prototype.constructor : this.constructor).toString();
   var cname = str.match(/function\s(\w*)/)[1];
   var aliases = ["", "anonymous", "Anonymous"];
   return aliases.indexOf(cname) > -1 ? "Function" : cname;
}

new Array().getConstructorName();  // returns "Array"
(function () {})().getConstructorName(); // returns "Function"

 


Note: the below example is deprecated.

A blog post linked by Christian Sciberras contains a good example on how to do it. Namely, by extending the Object prototype:

if (!Object.prototype.getClassName) {
    Object.prototype.getClassName = function () {
        return Object.prototype.toString.call(this).match(/^\[object\s(.*)\]$/)[1];
    }
}

var test = [1,2,3,4,5];

alert(test.getClassName()); // returns Array

Using TortoiseSVN via the command line

There is a confusion that is causing a lot of TortoiseSVN users to use the wrong command line tools when they actually were looking for svn.exe command line client.

What should I do or can't TortoiseSVN be used from the command line?

svn.exe

If you want to run Subversion commands from the command prompt, you should run the svn.exe command line client. TortoiseSVN 1.6.x and older versions did not include SVN command-line tools, but modern versions do.

If you want to get SVN command line tools without having to install TortoiseSVN, check the SVN binary distributions page or simply download the latest version from VisualSVN downloads page.

If you have SVN command line tools installed on your system, but still get the error 'svn' is not recognized as an internal or external command, you should check %PATH% environment variable. %PATH% must include the path to SVN tools directory e.g. C:\Program Files (x86)\VisualSVN\bin.

TortoiseProc.exe

Apart from svn.exe, TortoiseSVN comes with TortoiseProc.exe that can be called from command prompt. In most cases, you do not need to use this tool, because it should be only used for GUI automation. TortoiseProc.exe is not a replacement for SVN command-line client.

What's causing my java.net.SocketException: Connection reset?

This error happens on your side and NOT the other side. If the other side reset the connection, then the exception message should say:

java.net.SocketException reset by peer

The cause is the connection inside HttpClient is stale. Check stale connection for SSL does not fix this error. Solution: dump your client and recreate.

How to display activity indicator in middle of the iphone screen?

Try this way

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
    activityIndicator.center = super_view.center;
    [super_view addSubview: activityIndicator];

[activityIndicator startAnimating];

run program in Python shell

If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:

python -i test.py

That will run the script and then drop you into a Python interpreter.

hexadecimal string to byte array in python

You can use the Codecs module in the Python Standard Library, i.e.

import codecs

codecs.decode(hexstring, 'hex_codec')

How do I convert a calendar week into a date in Excel?

If your week number is in A1 and the year is in A2, following snippet could give you dates of full week

=$A$1*7+DATE($B$1,1,-4) through =$A$1*7+DATE($B$1,1,2)

Of course complete the series from -4 to 2 and you'll have dates starting Sunday through Saturday.

Hope this helps.

Can't update: no tracked branch

Assume you have a local branch "Branch-200" (or other name) and server repository contains "origin/Branch-1". If you have local "Branch-1" not linked with "origin/Branch-1", rename it to "Branch-200".

In Android Studio checkout to "origin/Branch-1" creating a new local branch "Branch-1", then merge with you local branch "Branch-200".

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

The DLL you're looking for that contains that namespace is

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

Note that unit testing cannot be used in Visual Studio Express.

How to run functions in parallel?

There's no way to guarantee that two functions will execute in sync with each other which seems to be what you want to do.

The best you can do is to split up the function into several steps, then wait for both to finish at critical synchronization points using Process.join like @aix's answer mentions.

This is better than time.sleep(10) because you can't guarantee exact timings. With explicitly waiting, you're saying that the functions must be done executing that step before moving to the next, instead of assuming it will be done within 10ms which isn't guaranteed based on what else is going on on the machine.

How can I make IntelliJ IDEA update my dependencies from Maven?

Apart from checking 'Import Maven projects automatically', make sure that settings.xml file from File > Settings > Maven > User Settings file exist, If doesn't exist then override and provide your settings.xml file path.

Iterating C++ vector from the end to the beginning

Starting with c++20, you can use a std::ranges::reverse_view and a range-based for-loop:

#include<ranges>
#include<vector>
#include<iostream>

using namespace std::ranges;

std::vector<int> const vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for(auto& i :  views::reverse(vec)) {
    std::cout << i << ",";
}

Or even

for(auto& i :  vec | views::reverse)

Unfortunately, at the time of writing (Jan 2020) no major compiler implements the ranges library, but you can resort to Eric Niebler's ranges-v3:

#include <iostream>
#include <vector>
#include "range/v3/all.hpp"

int main() {

    using namespace ranges;

    std::vector<int> const vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    for(auto& i :  views::reverse(vec)) {
        std::cout << i << ",";
    }

    return 0;
}

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

If you want to generate a file in the Windows, then, please follow the below steps:

  1. Go to a directory where you want to save the generated file
  2. Open the command prompt on that directory
  3. Run this fsutil file createnew [filename].[extension] [# of bytes] command. For example fsutil file createnew test.pdf 999999999
  4. 95.3 MB File will be generated

Update: The generated file will not be a valid pdf file. It just holds the given size.

Creating composite primary key in SQL Server

How about this:

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID) 

How to autosize a textarea using Prototype?

@memical had an awesome solution for setting the height of the textarea on pageload with jQuery, but for my application I wanted to be able to increase the height of the textarea as the user added more content. I built off memical's solution with the following:

$(document).ready(function() {
    var $textarea = $("p.body textarea");
    $textarea.css("height", ($textarea.attr("scrollHeight") + 20));
    $textarea.keyup(function(){
        var current_height = $textarea.css("height").replace("px", "")*1;
        if (current_height + 5 <= $textarea.attr("scrollHeight")) {
            $textarea.css("height", ($textarea.attr("scrollHeight") + 20));
        }
    });
});

It's not very smooth but it's also not a client-facing application, so smoothness doesn't really matter. (Had this been client-facing, I probably would have just used an auto-resize jQuery plugin.)

How to set 777 permission on a particular folder?

  1. Right click the folder, click on Properties.
  2. Click on the Security tab
  3. Add the name Everyone to the user list.

Calling Oracle stored procedure from C#?

Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.

using (OracleConnection connection = new OracleConnection("ConnectionString"))
    using (OracleCommand command = new OracleCommand("ProcName", connection))             
    {
          command.CommandType = CommandType.StoredProcedure;
          command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
          command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
          command.Parameters["return_out"].Direction = ParameterDirection.Output;
          command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
          command.Parameters["return_out2"].Direction = ParameterDirection.Output;
          connection.Open();
          command.ExecuteNonQuery();
          string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
          string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
    }

How to use TLS 1.2 in Java 6

I also got a similar error when forced to use TLS1.2 for java 6. And I handled it thanks to this library:

  1. Clone Source Code: https://github.com/tobszarny/ssl-provider-jvm16

  2. Add Main Class:

    public static void main(String[] args) throws Exception {
        try {
            String apiUrl = "https://domain/api/query?test=123";
    
            URL myurl = new URL(apiUrl);
            HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
            con.setSSLSocketFactory(new TSLSocketConnectionFactory());
            int responseCode = con.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

Reading content from URL with Node.js

A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)

function httpGet(url) {
  return new Promise((resolve, reject) => {
    const http = require('http'),
      https = require('https');

    let client = http;

    if (url.toString().indexOf("https") === 0) {
      client = https;
    }

    client.get(url, (resp) => {
      let chunks = [];

      // A chunk of data has been recieved.
      resp.on('data', (chunk) => {
        chunks.push(chunk);
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {
        resolve(Buffer.concat(chunks));
      });

    }).on("error", (err) => {
      reject(err);
    });
  });
}

(async(url) => {
  var buf = await httpGet(url);
  console.log(buf.toString('utf-8'));
})('https://httpbin.org/headers');

HTML5 - mp4 video does not play in IE9

If it's still not working here's what may certainly be a solution: encode the mp4 with compression format H.264. If you encode it with format mpeg4 or divx or else it will not work on IE9 and may as well crash Google Chrome. To do that, I use Any Video Converter freeware. But it could be done with any good video tool out there.

I've been trying all solutions listed here and tried other workaround for days but the problem lied in the way I created my mp4. IE9 does not decode other format than H.264.

Hope this helps, Jimmy

Python: maximum recursion depth exceeded while calling a Python object

Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).

This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.

As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.

N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.

How to resize superview to fit all subviews with autolayout?

This can be done for a normal subview inside a larger UIView, but it doesn't work automatically for headerViews. The height of a headerView is determined by what's returned by tableView:heightForHeaderInSection: so you have to calculate the height based on the height of the UILabel plus space for the UIButton and any padding you need. You need to do something like this:

-(CGFloat)tableView:(UITableView *)tableView 
          heightForHeaderInSection:(NSInteger)section {
    NSString *s = self.headeString[indexPath.section];
    CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17] 
                constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
                    lineBreakMode:NSLineBreakByWordWrapping];
    return size.height + 60;
}

Here headerString is whatever string you want to populate the UILabel, and the 281 number is the width of the UILabel (as setup in Interface Builder)

Delete with "Join" in Oracle sql Query

Based on the answer I linked to in my comment above, this should work:

delete from
(
select pf.* From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

or

delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf 
where pf.id>=200 
And pf.rowid in 
  (
     Select PRODUCTFILTERS.rowid from PRODUCTFILTERS 
     inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID 
     And PRODUCTS.NAME= 'Mark'
  )
); 

How to use regex in XPath "contains" function

If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()

Does this work for you?

String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

How do I delete unpushed git commits?

Don't delete it: for just one commit git cherry-pick is enough.

But if you had several commits on the wrong branch, that is where git rebase --onto shines:

Suppose you have this:

 x--x--x--x <-- master
           \
            -y--y--m--m <- y branch, with commits which should have been on master

, then you can mark master and move it where you would want to be:

 git checkout master
 git branch tmp
 git checkout y
 git branch -f master

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- y branch, master branch

, reset y branch where it should have been:

 git checkout y
 git reset --hard HEAD~2 # ~1 in your case, 
                         # or ~n, n = number of commits to cancel

 x--x--x--x <-- tmp
           \
            -y--y--m--m <- master branch
                ^
                |
                -- y branch

, and finally move your commits (reapply them, making actually new commits)

 git rebase --onto tmp y master
 git branch -D tmp


 x--x--x--x--m'--m' <-- master
           \
            -y--y <- y branch

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

script to map network drive

Tomalak's answer worked great for me (+1)

I only needed to make alter it slightly for my purposes, and I didn't need a password - it's for corporate domain:

Option Explicit
Dim l: l = "Z:"
Dim s: s = "\\10.10.10.1\share"
Dim Network: Set Network = CreateObject("WScript.Network")
Dim CheckDrive: Set CheckDrive = Network.EnumNetworkDrives()
Dim DriveExists: DriveExists = False
Dim i

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then
    DriveExists = True
  End If
Next

If DriveExists = False Then
  Network.MapNetworkDrive l, s, False
Else
  MsgBox l + " Drive already mapped"
End If

Or if you want to disconnect the drive:

For i = 0 to CheckDrive.Count - 1
  If CheckDrive.Item(i) = l Then 
    WshNetwork.RemoveNetworkDrive CheckDrive.Item(i)
  End If
Next

How to simulate key presses or a click with JavaScript?

Or even shorter, with only standard modern Javascript:

var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));

The new MouseEvent constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:

first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));

React "after render" code?

I had weird situation when i need to print react component which receives big amount of data and paint in on canvas. I've tried all mentioned approaches, non of them worked reliably for me, with requestAnimationFrame inside setTimeout i get empty canvas in 20% of the time, so i did the following:

nRequest = n => range(0,n).reduce(
(acc,val) => () => requestAnimationFrame(acc), () => requestAnimationFrame(this.save)
);

Basically i made a chain of requestAnimationFrame's, not sure is this good idea or not but this works in 100% of the cases for me so far (i'm using 30 as a value for n variable).

window.onload vs $(document).ready()

One thing to remember (or should I say recall) is that you cannot stack onloads like you can with ready. In other words, jQuery magic allows multiple readys on the same page, but you can't do that with onload.

The last onload will overrule any previous onloads.

A nice way to deal with that is with a function apparently written by one Simon Willison and described in Using Multiple JavaScript Onload Functions.

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

// Example use:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* More code to run on page load */
});

Should I use encodeURI or encodeURIComponent for encoding URLs?

It depends on what you are actually wanting to do.

encodeURI assumes that the input is a complete URI that might have some characters which need encoding in it.

encodeURIComponent will encode everything with special meaning, so you use it for components of URIs such as

var world = "A string with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(world);

PowerShell To Set Folder Permissions

Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:

$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl

OnClick in Excel VBA

Clearly, there is no perfect answer. However, if you want to allow the user to

  1. select certain cells
  2. allow them to change those cells, and
  3. trap each click,even repeated clicks on the same cell,

then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.

One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.

If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'prevent Select event triggering again when we extend the selection below
  Application.EnableEvents = False
  Target.Resize(1, 2).Select
  Application.EnableEvents = True
End Sub

Javascript - validation, numbers only

The simplest solution.

Thanks to my partner that gave me this answer.

You can set an onkeypress event on the input textbox like this:

onkeypress="validate(event)"

and then use regular expressions like this:

function validate(evt){
     evt.value = evt.value.replace(/[^0-9]/g,"");
}

It will scan and remove any letter or sign different from number in the field.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

Angular 2 - Redirect to an external URL and open in a new tab

I want to share with you one more solution if you have absolute part in the URL

SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}

HTML:

<button (click)="onNavigate()">Google</button>

TypeScript:

onNavigate()
{
    let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
    window.open(link, "_blank");
}

and url will be opened in new tab.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

We had the same issue when we had a typo in the mybatis mapping file like

        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.

Why can't I display a pound (£) symbol in HTML?

Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.

Make sure your data is in the right encoding and everything will work fine.

Android: Storing username and password?

The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.

I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.

Get final URL after curl is redirected

This would work:

 curl -I somesite.com | perl -n -e '/^Location: (.*)$/ && print "$1\n"'

Passing data into "router-outlet" child components

<router-outlet [node]="..."></router-outlet> 

is just invalid. The component added by the router is added as sibling to <router-outlet> and does not replace it.

See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

@Injectable() 
export class NodeService {
  private node:Subject<Node> = new BehaviorSubject<Node>([]);

  get node$(){
    return this.node.asObservable().filter(node => !!node);
  }

  addNode(data:Node) {
    this.node.next(data);
  }
}
@Component({
    selector : 'node-display',
    providers: [NodeService],
    template : `
        <router-outlet></router-outlet>
    `
})
export class NodeDisplayComponent implements OnInit {
    constructor(private nodeService:NodeService) {}
    node: Node;
    ngOnInit(): void {
        this.nodeService.getNode(path)
            .subscribe(
                node => {
                    this.nodeService.addNode(node);
                },
                err => {
                    console.log(err);
                }
            );
    }
}
export class ChildDisplay implements OnInit{
    constructor(nodeService:NodeService) {
      nodeService.node$.subscribe(n => this.node = n);
    }
}

Is Visual Studio Community a 30 day trial?

For VS2019 I was able to signup with my github account:

enter image description here enter image description here enter image description here enter image description here

Then it will send password to your email and you will be able to sign.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Have you tried using the stream_context_set_option() method ?

$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);

In addition, try file_get_contents() for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.

How do I compute derivative using Numpy?

Assuming you want to use numpy, you can numerically compute the derivative of a function at any point using the Rigorous definition:

def d_fun(x):
    h = 1e-5 #in theory h is an infinitesimal
    return (fun(x+h)-fun(x))/h

You can also use the Symmetric derivative for better results:

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Using your example, the full code should look something like:

def fun(x):
    return x**2 + 1

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Now, you can numerically find the derivative at x=5:

In [1]: d_fun(5)
Out[1]: 9.999999999621423

Dependency injection with Jersey 2.0

Dependency required for jersey restful service and Tomcat is the server. where ${jersey.version} is 2.29.1

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0.SP1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>${jersey.version}</version>
    </dependency>

The basic code will be as follows:

@RequestScoped
@Path("test")
public class RESTEndpoint {

   @GET
   public String getMessage() {

Add row to query result using select

In SQL Server, you would say:

Select name from users
UNION [ALL]
SELECT 'JASON'

In Oracle, you would say

Select name from user
UNION [ALL]
Select 'JASON' from DUAL

How to print the array?

It looks like you have a typo on your array, it should read:

int my_array[3][3] = {...

You don't have the _ or the {.

Also my_array[3][3] is an invalid location. Since computers begin counting at 0, you are accessing position 4. (Arrays are weird like that).

If you want just the last element:

printf("%d\n", my_array[2][2]);

If you want the entire array:

for(int i = 0; i < my_array.length; i++) {
  for(int j = 0; j < my_array[i].length; j++)
    printf("%d ", my_array[i][j]);
  printf("\n");
}

Redirect using AngularJS

Assuming you're not using html5 routing, try $location.path("route"). This will redirect your browser to #/route which might be what you want.

How can I implement prepend and append with regular JavaScript?

If you want to insert a raw HTML string no matter how complex, you can use: insertAdjacentHTML, with appropriate first argument:

'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.

Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.

An example of usage:

document.getElementById("foo").insertAdjacentHTML("beforeBegin",
          "<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");

DEMO

Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

How to Validate Google reCaptcha on Form Submit

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 

how to open a jar file in Eclipse

use java decompiler. http://jd.benow.ca/. you can open the jar files.

Thanks, Manirathinam.

How to get the insert ID in JDBC?

Instead of a comment, I just want to answer post.


Interface java.sql.PreparedStatement

  1. columnIndexes « You can use prepareStatement function that accepts columnIndexes and SQL statement. Where columnIndexes allowed constant flags are Statement.RETURN_GENERATED_KEYS1 or Statement.NO_GENERATED_KEYS[2], SQL statement that may contain one or more '?' IN parameter placeholders.

    SYNTAX «

    Connection.prepareStatement(String sql, int autoGeneratedKeys)
    Connection.prepareStatement(String sql, int[] columnIndexes)
    

    Example:

    PreparedStatement pstmt = 
        conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
    

  1. columnNames « List out the columnNames like 'id', 'uniqueID', .... in the target table that contain the auto-generated keys that should be returned. The driver will ignore them if the SQL statement is not an INSERT statement.

    SYNTAX «

    Connection.prepareStatement(String sql, String[] columnNames)
    

    Example:

    String columnNames[] = new String[] { "id" };
    PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
    

Full Example:

public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
    String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";

    String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
            //"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
    int primkey = 0 ;
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);

        String columnNames[] = new String[] { "id" };

        PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
        pstmt.setString(1, UserName );
        pstmt.setString(2, Language );
        pstmt.setString(3, Message );

        if (pstmt.executeUpdate() > 0) {
            // Retrieves any auto-generated keys created as a result of executing this Statement object
            java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
            if ( generatedKeys.next() ) {
                primkey = generatedKeys.getInt(1);
            }
        }
        System.out.println("Record updated with id = "+primkey);
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

.mp4 file not playing in chrome

I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).

I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.

Maybe the problem is not in the format but in the JavaScript implementation of the play/ pause methods. May I suggest visiting the following link where Google developer explains it in a good way?

Additionally, you could choose to use the newer webp format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.

On that note: I've created a small script that easily converts all standard formats to webp. You can easily configure it to fit your needs. Here's the Github repo of the same projects.

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID = obj.id;         console.log(sID);     })).then(function () {         $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) {             console.log(stats);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

Proper use of 'yield return'

And what about this?

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList();
    }
}

I guess this is much cleaner. I do not have VS2008 at hand to check, though. In any case, if Products implements IEnumerable (as it seems to - it is used in a foreach statement), I'd return it directly.

Get selected item value from Bootstrap DropDown with specific ID

The selector would be #demolist.dropdown-menu li a note no space between id and class. However i would suggest a more generic approach:

<div class="input-group">                                            
    <input type="TextBox" Class="form-control datebox"></input>
    <div class="input-group-btn">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
        <li><a href="#">C</a></li>
    </ul>
</div>


$(document).on('click', '.dropdown-menu li a', function() {
    $(this).parent().parent().parent().find('.datebox').val($(this).html());
}); 

by using a class rather than id, and using parent().find(), you can have as many of these on a page as you like, with no duplicated js

I want to multiply two columns in a pandas DataFrame and add the result into a new column

If we're willing to sacrifice the succinctness of Hayden's solution, one could also do something like this:

In [22]: orders_df['C'] = orders_df.Action.apply(
               lambda x: (1 if x == 'Sell' else -1))

In [23]: orders_df   # New column C represents the sign of the transaction
Out[23]:
   Prices  Amount Action  C
0       3      57   Sell  1
1      89      42   Sell  1
2      45      70    Buy -1
3       6      43   Sell  1
4      60      47   Sell  1
5      19      16    Buy -1
6      56      89   Sell  1
7       3      28    Buy -1
8      56      69   Sell  1
9      90      49    Buy -1

Now we have eliminated the need for the if statement. Using DataFrame.apply(), we also do away with the for loop. As Hayden noted, vectorized operations are always faster.

In [24]: orders_df['Value'] = orders_df.Prices * orders_df.Amount * orders_df.C

In [25]: orders_df   # The resulting dataframe
Out[25]:
   Prices  Amount Action  C  Value
0       3      57   Sell  1    171
1      89      42   Sell  1   3738
2      45      70    Buy -1  -3150
3       6      43   Sell  1    258
4      60      47   Sell  1   2820
5      19      16    Buy -1   -304
6      56      89   Sell  1   4984
7       3      28    Buy -1    -84
8      56      69   Sell  1   3864
9      90      49    Buy -1  -4410

This solution takes two lines of code instead of one, but is a bit easier to read. I suspect that the computational costs are similar as well.

Append text with .bat

You need to use ECHO. Also, put the quotes around the entire file path if it contains spaces.

One other note, use > to overwrite a file if it exists or create if it does not exist. Use >> to append to an existing file or create if it does not exist.

Overwrite the file with a blank line:

ECHO.>"C:\My folder\Myfile.log"

Append a blank line to a file:

ECHO.>>"C:\My folder\Myfile.log"

Append text to a file:

ECHO Some text>>"C:\My folder\Myfile.log"

Append a variable to a file:

ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try this one in model class

    [Required(ErrorMessage = "Enter full name.")]
    [RegularExpression("([A-Za-z])+( [A-Za-z]+)", ErrorMessage = "Enter valid full name.")]

    public string FullName { get; set; }

How do I find the location of my Python site-packages directory?

You should try this command to determine pip's install location

Python 2

pip show six | grep "Location:" | cut -d " " -f2

Python 3

pip3 show six | grep "Location:" | cut -d " " -f2

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

WAMP Cannot access on local network 403 Forbidden

I got this answer from here. and its works for me

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

How can I see what has changed in a file before committing to git?

For some paths, the other answers will return an error of the form fatal: ambiguous argument.

In these cases diff needs a separator to differentiate filename arguments from commit strings. For example to answer the question asked you'd need to execute:

$ git diff --cached -- <path-to-file>

This will display the changes between the modified files and the last commit.

On the other hand:

git diff --cached HEAD~3 <path-to-file>

will display the changes between the local version of and the version three commits ago.

How to make a checkbox checked with jQuery?

$('#test').prop('checked', true);

Note only in jQuery 1.6+

jQuery: Test if checkbox is NOT checked

Return true if all checbox are checked in a div

function all_checked (id_div){
 all_checked = true;

 $(id_div+' input[type="checkbox"]').each(function() { 
    all_checked = all_checked && $('this').prop('checked');
 }

 return all_checked;
}

html - table row like a link

If you have to use a table, you can put a link into each table cell:

<table>
  <tbody>
    <tr>
      <td><a href="person1.html">John Smith</a></td>
      <td><a href="person1.html">123 Fake St</a></td>
      <td><a href="person1.html">90210</a></td>
    </tr>
    <tr>
      <td><a href="person2.html">Peter Nguyen</a></td>
      <td><a href="person2.html">456 Elm Ave</a></td>
      <td><a href="person2.html">90210</a></td>
    </tr>
  </tbody>
</table>

And make the links fill up the entire cells:

table tbody tr td a {
  display: block;
  width: 100%;
  height: 100%;
}

If you are able to use <div>s instead of a table, your HTML can be a lot simpler, and you won't get "gaps" in the links, between the table cells:

<div class="myTable">
  <a href="person1.html">
    <span>John Smith</span>
    <span>123 Fake St</span>
    <span>90210</span>
  </a>
  <a href="person2.html">
    <span>Peter Nguyen</span>
    <span>456 Elm Ave</span>
    <span>90210</span>
  </a>
</div>

Here is the CSS that goes with the <div> method:

.myTable {
  display: table;
}
.myTable a {
  display: table-row;
}
.myTable a span {
  display: table-cell;
  padding: 2px; /* this line not really needed */
}

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

go to link on button click - jquery

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

How many significant digits do floats and doubles have in java?

From java specification :

The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

As it's hard to do anything with numbers without understanding IEEE754 basics, here's another link.

It's important to understand that the precision isn't uniform and that this isn't an exact storage of the numbers as is done for integers.

An example :

double a = 0.3 - 0.1;
System.out.println(a);          

prints

0.19999999999999998

If you need arbitrary precision (for example for financial purposes) you may need Big Decimal.

How to decompile an APK or DEX file on Android platform?

You can decompile an apk on Android device using this : https://play.google.com/store/apps/details?id=com.njlabs.showjava

For more info look here: http://forum.xda-developers.com/showthread.php?t=2601315

EDIT: 28-02-2015

For decompiling an apk you can use this tool: https://apkstudio.codeplex.com/license

If that doesnt help check this link

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

How to add scroll bar to the Relative Layout?

The following code should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="638dp" >

<TextView
    android:id="@+id/textView1"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="64dp"
    android:text="Email" />

<TextView
    android:id="@+id/textView2"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="41dp"
    android:text="Password" />

<TextView
    android:id="@+id/textView3"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="47dp"
    android:text="Confirm Password" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textView4"
    android:inputType="textEmailAddress" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignParentRight="true"
    android:inputType="textPassword" />


<TextView
    android:id="@+id/textView4"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="42dp"
    android:text="Date of Birth" />

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/textView4" />

<TextView
    android:id="@+id/textView5"
    style="@style/normalcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/datePicker1"
    android:layout_marginTop="60dp"
    android:layout_toLeftOf="@+id/datePicker1"
    android:text="Gender" />

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView5"
    android:layout_alignBottom="@+id/textView5"
    android:layout_alignLeft="@+id/editText3"
    android:layout_marginLeft="24dp"
    android:text="Male" />

<RadioButton
    android:id="@+id/radioButton2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/radioButton1"
    android:layout_below="@+id/radioButton1"
    android:layout_marginTop="14dp"
    android:text="Female" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="23dp"
    android:layout_toLeftOf="@+id/radioButton2"
    android:background="@drawable/rectbutton"
    android:text="Sign Up" />

Using "like" wildcard in prepared statement

You need to set it in the value itself, not in the prepared statement SQL string.

So, this should do for a prefix-match:

notes = notes
    .replace("!", "!!")
    .replace("%", "!%")
    .replace("_", "!_")
    .replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
        "SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");

or a suffix-match:

pstmt.setString(1, "%" + notes);

or a global match:

pstmt.setString(1, "%" + notes + "%");

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Find nginx version?

In my case, I try to add sudo

sudo nginx -v

enter image description here

Best practice for Django project working directory structure

As per the Django Project Skeleton, the proper directory structure that could be followed is :

[projectname]/                  <- project root
+-- [projectname]/              <- Django root
¦   +-- __init__.py
¦   +-- settings/
¦   ¦   +-- common.py
¦   ¦   +-- development.py
¦   ¦   +-- i18n.py
¦   ¦   +-- __init__.py
¦   ¦   +-- production.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- apps/
¦   +-- __init__.py
+-- configs/
¦   +-- apache2_vhost.sample
¦   +-- README
+-- doc/
¦   +-- Makefile
¦   +-- source/
¦       +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦   +-- media/
¦   ¦   +-- README
¦   +-- README
¦   +-- static/
¦       +-- README
+-- static/
¦   +-- README
+-- templates/
    +-- base.html
    +-- core
    ¦   +-- login.html
    +-- README

Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.

How can I exclude all "permission denied" messages from "find"?

Note:
* This answer probably goes deeper than the use case warrants, and find 2>/dev/null may be good enough in many situations. It may still be of interest for a cross-platform perspective and for its discussion of some advanced shell techniques in the interest of finding a solution that is as robust as possible, even though the cases guarded against may be largely hypothetical.
* If your system is configured to show localized error messages, prefix the find calls below with LC_ALL=C (LC_ALL=C find ...) to ensure that English messages are reported, so that grep -v 'Permission denied' works as intended. Invariably, however, any error messages that do get displayed will then be in English as well.

If your shell is bash or zsh, there's a solution that is robust while being reasonably simple, using only POSIX-compliant find features; while bash itself is not part of POSIX, most modern Unix platforms come with it, making this solution widely portable:

find . > files_and_folders 2> >(grep -v 'Permission denied' >&2)

Note: There's a small chance that some of grep's output may arrive after find completes, because the overall command doesn't wait for the command inside >(...) to finish. In bash, you can prevent this by appending | cat to the command.

  • >(...) is a (rarely used) output process substitution that allows redirecting output (in this case, stderr output (2>) to the stdin of the command inside >(...).
    In addition to bash and zsh, ksh supports them as well in principle, but trying to combine them with redirection from stderr, as is done here (2> >(...)), appears to be silently ignored (in ksh 93u+).

    • grep -v 'Permission denied' filters out (-v) all lines (from the find command's stderr stream) that contain the phrase Permission denied and outputs the remaining lines to stderr (>&2).

This approach is:

  • robust: grep is only applied to error messages (and not to a combination of file paths and error messages, potentially leading to false positives), and error messages other than permission-denied ones are passed through, to stderr.

  • side-effect free: find's exit code is preserved: the inability to access at least one of the filesystem items encountered results in exit code 1 (although that won't tell you whether errors other than permission-denied ones occurred (too)).


POSIX-compliant solutions:

Fully POSIX-compliant solutions either have limitations or require additional work.

If find's output is to be captured in a file anyway (or suppressed altogether), then the pipeline-based solution from Jonathan Leffler's answer is simple, robust, and POSIX-compliant:

find . 2>&1 >files_and_folders | grep -v 'Permission denied' >&2

Note that the order of the redirections matters: 2>&1 must come first.

Capturing stdout output in a file up front allows 2>&1 to send only error messages through the pipeline, which grep can then unambiguously operate on.

The only downside is that the overall exit code will be the grep command's, not find's, which in this case means: if there are no errors at all or only permission-denied errors, the exit code will be 1 (signaling failure), otherwise (errors other than permission-denied ones) 0 - which is the opposite of the intent.
That said, find's exit code is rarely used anyway, as it often conveys little information beyond fundamental failure such as passing a non-existent path.
However, the specific case of even only some of the input paths being inaccessible due to lack of permissions is reflected in find's exit code (in both GNU and BSD find): if a permissions-denied error occurs for any of the files processed, the exit code is set to 1.

The following variation addresses that:

find . 2>&1 >files_and_folders | { grep -v 'Permission denied' >&2; [ $? -eq 1 ]; }

Now, the exit code indicates whether any errors other than Permission denied occurred: 1 if so, 0 otherwise.
In other words: the exit code now reflects the true intent of the command: success (0) is reported, if no errors at all or only permission-denied errors occurred.
This is arguably even better than just passing find's exit code through, as in the solution at the top.


gniourf_gniourf in the comments proposes a (still POSIX-compliant) generalization of this solution using sophisticated redirections, which works even with the default behavior of printing the file paths to stdout:

{ find . 3>&2 2>&1 1>&3 | grep -v 'Permission denied' >&3; } 3>&2 2>&1

In short: Custom file descriptor 3 is used to temporarily swap stdout (1) and stderr (2), so that error messages alone can be piped to grep via stdout.

Without these redirections, both data (file paths) and error messages would be piped to grep via stdout, and grep would then not be able to distinguish between error message Permission denied and a (hypothetical) file whose name happens to contain the phrase Permission denied.

As in the first solution, however, the the exit code reported will be grep's, not find's, but the same fix as above can be applied.


Notes on the existing answers:

  • There are several points to note about Michael Brux's answer, find . ! -readable -prune -o -print:

    • It requires GNU find; notably, it won't work on macOS. Of course, if you only ever need the command to work with GNU find, this won't be a problem for you.

    • Some Permission denied errors may still surface: find ! -readable -prune reports such errors for the child items of directories for which the current user does have r permission, but lacks x (executable) permission. The reason is that because the directory itself is readable, -prune is not executed, and the attempt to descend into that directory then triggers the error messages. That said, the typical case is for the r permission to be missing.

    • Note: The following point is a matter of philosophy and/or specific use case, and you may decide it is not relevant to you and that the command fits your needs well, especially if simply printing the paths is all you do:

      • If you conceptualize the filtering of the permission-denied error messages a separate task that you want to be able to apply to any find command, then the opposite approach of proactively preventing permission-denied errors requires introducing "noise" into the find command, which also introduces complexity and logical pitfalls.
      • For instance, the most up-voted comment on Michael's answer (as of this writing) attempts to show how to extend the command by including a -name filter, as follows:
        find . ! -readable -prune -o -name '*.txt'
        This, however, does not work as intended, because the trailing -print action is required (an explanation can be found in this answer). Such subtleties can introduce bugs.
  • The first solution in Jonathan Leffler's answer, find . 2>/dev/null > files_and_folders, as he himself states, blindly silences all error messages (and the workaround is cumbersome and not fully robust, as he also explains). Pragmatically speaking, however, it is the simplest solution, as you may be content to assume that any and all errors would be permission-related.

  • mist's answer, sudo find . > files_and_folders, is concise and pragmatic, but ill-advised for anything other than merely printing filenames, for security reasons: because you're running as the root user, "you risk having your whole system being messed up by a bug in find or a malicious version, or an incorrect invocation which writes something unexpectedly, which could not happen if you ran this with normal privileges" (from a comment on mist's answer by tripleee).

  • The 2nd solution in viraptor's answer, find . 2>&1 | grep -v 'Permission denied' > some_file runs the risk of false positives (due to sending a mix of stdout and stderr through the pipeline), and, potentially, instead of reporting non-permission-denied errors via stderr, captures them alongside the output paths in the output file.

Get gateway ip address in android

Try the following:

ConnectivityManager connectivityManager = ...;
LinkProperties linkProperties = connectivityManager.getLinProperties(connectivityManager.GetActiveNetwork());
for (RouteInfo routeInfo: linkProperties.getRoutes()) {
    if (routeInfo.IsDefaultRoute() && routeInfo.hasGateway()) {
        return routeInfo.getGateway();
    }
}

HashMap with multiple values under the same key

Apache Commons collection classes can implement multiple values under same key.

MultiMap multiMapDemo = new MultiValueMap();

multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");

System.out.println(multiMapDemo.get("fruit"));

Maven Dependency

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.4</version>
</dependency>

How to parse XML in Bash?

After some research for translation between Linux and Windows formats of the file paths in XML files I found interesting tutorials and solutions on:

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

2 "style" inline css img tags?

Do not use more than one style attribute. Just seperate styles in the style attribute with ; It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.

So in this case its: style="height:100px;width:100px;"

You can use this for any CSS style, so if you wanted to change the colour of the text to white: style="height:100px;width:100px;color:#ffffff" and so on.

However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

Using Laravel Homestead: 'no input file specified'

Restart your homestead. Worked for me.

homestead destroy
homestead up

C/C++ Struct vs Class

It's not possible to define member functions or derive structs from each other in C.

Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.

How to handle a lost KeyStore password in Android?

In terminal go to which might be different in your PC :

C:\Program Files\Java\jre1.8.0_241\bin

Then:

For Windows:

keytool -list -v -keystore C:\Users\YOURUSERPROFILENAME\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

For Mac:

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Download a single folder or directory from a GitHub repo

You can use ghget with any URL copied from the address bar:

ghget https://github.com/fivethirtyeight/data/tree/master/airline-safety

It's a self-contained portable shell script that doesn't use SVN (which didn't work for me on a big repo). It also doesn't use the API so it doesn't require a token and isn't rate-limited.

Disclaimer: I made it.

Style disabled button with CSS

For all of us using bootstrap, you can change the style by adding the "disabled" class and using the following:

HTML

<button type="button"class="btn disabled">Text</button>

CSS

.btn:disabled,
.btn.disabled{
  color:#fff;
  border-color: #a0a0a0;
  background-color: #a0a0a0;
}
.btn:disabled:hover,
.btn:disabled:focus,
.btn.disabled:hover,
.btn.disabled:focus {
  color:#fff;
  border-color: #a0a0a0;
  background-color: #a0a0a0;
}

Remember that adding the "disabled" class doesn't necessarily disable the button, for example in a submit form. To disable its behaviour use the disabled property:

<button type="button"class="btn disabled" disabled="disabled">Text</button>

A working fiddle with some examples is available here.

MySql Query Replace NULL with Empty String in Select

Try below ;

  select if(prereq IS NULL ," ",prereq ) from test

How to check if a string in Python is in ASCII?

Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.

Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character.

Instead of ord(u'é'), try this:

>>> [ord(x) for x in u'é']

That tells you which sequence of code points "é" represents. It may give you [233], or it may give you [101, 770].

Instead of chr() to reverse this, there is unichr():

>>> unichr(233)
u'\xe9'

This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure u'e\u0301' or u'\u00e9'.

Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, len(u'e\u0301') == 2 and len(u'\u00e9') == 1. If this matters to you, you can convert between composed and decomposed forms by using unicodedata.normalize.

The Unicode Glossary can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.

Angular 4 - get input value

<form (submit)="onSubmit()">
   <input [(ngModel)]="playerName">
</form>

let playerName: string;
onSubmit() {
  return this.playerName;
}

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

How to call a method after bean initialization is complete?

You could deploy a custom BeanPostProcessor in your application context to do it. Or if you don't mind implementing a Spring interface in your bean, you could use the InitializingBean interface or the "init-method" directive (same link).

What does %>% function mean in R?

%>% is similar to pipe in Unix. For example, in

a <- combined_data_set %>% group_by(Outlet_Identifier) %>% tally()

the output of combined_data_set will go into group_by and its output will go into tally, then the final output is assigned to a.

This gives you handy and easy way to use functions in series without creating variables and storing intermediate values.

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

How to create a temporary directory and get the path / file name in Python

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

Lua string to int

The clearer option is to use tonumber.

As of 5.3.2, this function will automatically detect (signed) integers, float (if a point is present) and hexadecimal (both integers and floats, if the string starts by "0x" or "0X").

The following snippets are shorter but not equivalent :

  • a + 0 -- forces the conversion into float, due to how + works.
    
  • a | 0 -- (| is the bitwise or) forces the conversion into integer. 
    -- However, unlike `math.tointeger`, it errors if it fails.
    

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

It May be due to some exceptions like (Parsing NUMERIC to String or vise versa).

Please verify cell values either are null or do handle Exception and see.

Best, Shahid

How can I get the data type of a variable in C#?

One option would be to use a helper extension method like follows:

public static class MyExtensions
{
    public static System.Type Type<T>(this T v)=>typeof(T);
}

var i=0;
console.WriteLine(i.Type().FullName);

Select mysql query between date?

select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()

or using >= and <= :

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

Hi recently looked into this and had issues referencing the named table (list object) within excel

if you place a suffix '$' on the table name all is well in the world

Sub testSQL()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset

    ' Declare variables
    strFile = ThisWorkbook.FullName

    ' construct connection string
    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"

    ' create connection and recordset objects
    Set cn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    ' open connection
    cn.Open strCon

    ' construct SQL query
    strSQL = "SELECT * FROM [TableName$] where [ColumnHeader] = 'wibble';"

    ' execute SQL query
    rs.Open strSQL, cn

    Debug.Print rs.GetString

    ' close connection
    rs.Close
    cn.Close
    Set rs = Nothing
    Set cn = Nothing
End Sub

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Neither BindingResult nor plain target object for bean name available as request attribute

I had problem like this, but with several "actions". My solution looks like this:

    <form method="POST" th:object="${searchRequest}" action="searchRequest" >
          <input type="text" th:field="*{name}"/>
          <input type="submit" value="find" th:value="find" />
    </form>
        ...
    <form method="POST" th:object="${commodity}" >
        <input type="text" th:field="*{description}"/>
        <input type="submit" value="add" />
    </form>

And controller

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @RequestMapping(value = "add", method = GET)
    public String showGoodsForm(Model model){
           model.addAttribute(new Commodity());
           model.addAttribute("searchRequest", new SearchRequest());
           return "goodsForm";
    }
    @RequestMapping(value = "add", method = POST)
    public ModelAndView processAddCommodities(
            @Valid Commodity commodity,
            Errors errors) {
        if (errors.hasErrors()) {
            ModelAndView model = new ModelAndView("goodsForm");
            model.addObject("searchRequest", new SearchRequest());
            return model;
        }
        ModelAndView model = new ModelAndView("redirect:/goods/" + commodity.getName());
        model.addObject(new Commodity());
        model.addObject("searchRequest", new SearchRequest());
        return model;
    }
    @RequestMapping(value="searchRequest", method=POST)
    public String processFindCommodity(SearchRequest commodity, Model model) {
    ...
        return "catalog";
    }

I'm sure - here is not "best practice", but it is works without "Neither BindingResult nor plain target object for bean name available as request attribute".

How do I import a specific version of a package using go get?

Nowadays you can just use go get for it. You can fetch your dependency by the version tag, branch or even the commit.

go get github.com/someone/some_module@master
go get github.com/someone/[email protected]
go get github.com/someone/some_module@commit_hash

more details here - How to point Go module dependency in go.mod to a latest commit in a repo?

Go get will also install the binary, like it says in the documentation -

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

(from https://golang.org/cmd/go/)

Get the correct week number of a given date

C# to Powershell port from code above from il_guru:

function GetWeekOfYear([datetime] $inputDate)
{
   $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
   if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
   {
      $inputDate = $inputDate.AddDays(3)
   }

   # Return the week of our adjusted day
   $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
   return $weekofYear
}

How to remove "href" with Jquery?

If you wanted to remove the href, change the cursor and also prevent clicking on it, this should work:

$("a").attr('href', '').css({'cursor': 'pointer', 'pointer-events' : 'none'});

Google Colab: how to read data from my google drive?

from google.colab import drive
drive.mount('/content/drive')

This worked perfect for me I was later able to use the os library to access my files just like how I access them on my PC

How to use SQL LIKE condition with multiple values in PostgreSQL?

You might be able to use IN, if you don't actually need wildcards.

SELECT * from table WHERE column IN ('AAA', 'BBB', 'CCC')

Extract specific columns from delimited file using Awk

I don't know if it's possible to do ranges in awk. You could do a for loop, but you would have to add handling to filter out the columns you don't want. It's probably easier to do this:

awk -F, '{OFS=",";print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$20,$21,$22,$23,$24,$25,$30,$33}' infile.csv > outfile.csv

something else to consider - and this faster and more concise:

cut -d "," -f1-10,20-25,30-33 infile.csv > outfile.csv

As to the second part of your question, I would probably write a script in perl that knows how to handle header rows, parsing the columns names from stdin or a file and then doing the filtering. It's probably a tool I would want to have for other things. I am not sure about doing in a one liner, although I am sure it can be done.

Make Bootstrap's Carousel both center AND responsive?

.carousel-inner > .item > img {
    margin: 0 auto;
}

This simple solution worked for me

Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]


<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

Parsing a CSV file using NodeJS

I use this simple one: https://www.npmjs.com/package/csv-parser

Very simple to use:

const csv = require('csv-parser')
const fs = require('fs')
const results = [];

fs.createReadStream('./CSVs/Update 20191103C.csv')
  .pipe(csv())
  .on('data', (data) => results.push(data))
  .on('end', () => {
    console.log(results);
    console.log(results[0]['Lowest Selling Price'])
  });

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Turns out I had a .csv file at the end of the folder from which I was reading all the images. Once I deleted that it worked alright

Make sure that it's all images and that you don't have any other type of file

SQL how to make null values come last when sorting ascending

In Oracle, you can use NULLS FIRST or NULLS LAST: specifies that NULL values should be returned before / after non-NULL values:

ORDER BY { column-Name | [ ASC | DESC ] | [ NULLS FIRST | NULLS LAST ] }

For example:

ORDER BY date DESC NULLS LAST

Ref: http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html

Maintaining Session through Angular.js

You can also try to make service based on window.sessionStorage or window.localStorage to keep state information between page reloads. I use it in the web app which is partially made in AngularJS and page URL is changed in "the old way" for some parts of workflow. Web storage is supported even by IE8. Here is angular-webstorage for convenience.

How to input automatically when running a shell over SSH?

For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.

Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command

How can I preview a merge in git?

Pull Request - I've used most of the already submitted ideas but one that I also often use is ( especially if its from another dev ) doing a Pull Request which gives a handy way to review all of the changes in a merge before it takes place. I know that is GitHub not git but it sure is handy.

Insert auto increment primary key to existing table

Well, you have multiple ways to do this: -if you don't have any data on your table, just drop it and create it again.

Dropping the existing field and creating it again like this

ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);

Or just modify it

ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);

How to find MAC address of an Android device programmatically

See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.

Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6 

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

How to detect if a string contains special characters?

Assuming SQL Server:

e.g. if you class special characters as anything NOT alphanumeric:

DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'

IF (@MyString LIKE '%[^a-zA-Z0-9]%')
    PRINT 'Contains "special" characters'
ELSE
    PRINT 'Does not contain "special" characters'

Just add to other characters you don't class as special, inside the square brackets

Get Value From Select Option in Angular 4

_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  items: any[] = [_x000D_
    { id: 1, name: 'one' },_x000D_
    { id: 2, name: 'two' },_x000D_
    { id: 3, name: 'three' },_x000D_
    { id: 4, name: 'four' },_x000D_
    { id: 5, name: 'five' },_x000D_
    { id: 6, name: 'six' }_x000D_
  ];_x000D_
  selected: number = 1;_x000D_
_x000D_
  constructor() {_x000D_
  }_x000D_
  _x000D_
  ngOnInit() {_x000D_
  }_x000D_
  _x000D_
  selectOption(id: number) {_x000D_
    //getted from event_x000D_
    console.log(id);_x000D_
    //getted from binding_x000D_
    console.log(this.selected)_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div>_x000D_
  <select (change)="selectOption($event.target.value)"_x000D_
  [(ngModel)]="selected">_x000D_
  <option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>_x000D_
   </select>_x000D_
</div> 
_x000D_
_x000D_
_x000D_

Soft hyphen in HTML (<wbr> vs. &shy;)

I used soft hyphen unicode character successfully in few desktop and mobile browsers to solve the issue.

The unicode symbol is \u00AD and is pretty easy to insert into Python unicode string like s = u'????? ? ?????? ???????\u00AD??\u00AD??\u00AD??\u00AD???'.

Other solution is to insert the unicode char itself, and the source string will look perfectly ordinary in editors like Sublime Text, Kate, Geany, etc (cursor will feel the invisible symbol though).

Hex editors of in-house tools can automate this task easily.

An easy kludge is to use rare and visible character, like ¦, which is easy to copy and paste, and replace it on soft hyphen using, e.g. frontend script in $(document).ready(...). Source code like s = u'????? ? ?????? ???¦???¦?¦??¦??¦??¦???'.replace('¦', u'\u00AD') is easier to read than s = u'????? ? ?????? ???\u00AD?\u00AD??\u00AD?\u00AD??\u00AD??\u00AD??\u00AD???'.

Cannot import keras after installation

Ran to the same issue, Assuming your using anaconda3 and your using a venv with >= python=3.6:

python -m pip install keras
sudo python -m pip install --user tensorflow

Declare a constant array

There is no such thing as array constant in Go.

Quoting from the Go Language Specification: Constants:

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

A Constant expression (which is used to initialize a constant) may contain only constant operands and are evaluated at compile time.

The specification lists the different types of constants. Note that you can create and initialize constants with constant expressions of types having one of the allowed types as the underlying type. For example this is valid:

func main() {
    type Myint int
    const i1 Myint = 1
    const i2 = Myint(2)
    fmt.Printf("%T %v\n", i1, i1)
    fmt.Printf("%T %v\n", i2, i2)
}

Output (try it on the Go Playground):

main.Myint 1
main.Myint 2

If you need an array, it can only be a variable, but not a constant.

I recommend this great blog article about constants: Constants

How to rename HTML "browse" button of an input type=file?

  1. Wrap the <input type="file"> with a <label> tag;
  2. Add a tag (with the text that you need) inside the label, like a <span> or <a>;
  3. Make this tag look like a button;
  4. Make input[type="file"] invisible via display: none.

How to add multiple classes to a ReactJS Component?


Generally people do like

<div className={  ['head', style.class1 , Style.class2].join(' ')  }><div>

But you can choose to Create a function to do this job

function joinAll(...classes) {
  return classes.join(" ")
}

then call it like:-

<div className={joinAll('head', style.class1 , style.class2)}><div>

String's Maximum length in Java - calling length() method

As mentioned in Takahiko Kawasaki's answer, java represents Unicode strings in the form of modified UTF-8 and in JVM-Spec CONSTANT_UTF8_info Structure, 2 bytes are allocated to length (and not the no. of characters of String).
To extend the answer, the ASM jvm bytecode library's putUTF8 method, contains this:

public ByteVector putUTF8(final String stringValue) {
    int charLength = stringValue.length();
    if (charLength > 65535) {   
   // If no. of characters> 65535, than however UTF-8 encoded length, wont fit in 2 bytes.
      throw new IllegalArgumentException("UTF8 string too large");
    }
    for (int i = 0; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= '\u0001' && charValue <= '\u007F') {
        // Unicode code-point encoding in utf-8 fits in 1 byte.
        currentData[currentLength++] = (byte) charValue;
      } else {
        // doesnt fit in 1 byte.
        length = currentLength;
        return encodeUtf8(stringValue, i, 65535);
      }
    }
    ...
}

But when code-point mapping > 1byte, it calls encodeUTF8 method:

final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength /*= 65535 */) {
    int charLength = stringValue.length();
    int byteLength = offset;
    for (int i = offset; i < charLength; ++i) {
      char charValue = stringValue.charAt(i);
      if (charValue >= 0x0001 && charValue <= 0x007F) {
        byteLength++;
      } else if (charValue <= 0x07FF) {
        byteLength += 2;
      } else {
        byteLength += 3;
      }
    }
   ...
}

In this sense, the max string length is 65535 bytes, i.e the utf-8 encoding length. and not char count
You can find the modified-Unicode code-point range of JVM, from the above utf8 struct link.

Are multi-line strings allowed in JSON?

Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.

    parseJSON = function() {
        var data = {};
        var reader = new FileReader();
        reader.onload = function() {
            try {
                data = JSON.parse(reader.result.replace(/'/g, "\""));
            } catch (ex) {
                console.log('error' + ex);
            }
        };
        reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}

What is the difference between private and protected members of C++ classes?

Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.

Regular Expression: Any character that is NOT a letter or number

Just for others to see:

someString.replaceAll("([^\\p{L}\\p{N}])", " ");

will remove any non-letter and non-number unicode characters.

Source

GitHub authentication failing over https, returning wrong email address

It may happen in Windows if you stored a different credentials before. Go to Credential Manager and delete stored github credentials

Concatenate two slices in Go

append([]int{1,2}, []int{3,4}...) will work. Passing arguments to ... parameters.

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T.

If f is invoked with no actual arguments for p, the value passed to p is nil.

Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

Given the function and calls

func Greeting(prefix string, who ...string)
Greeting("nobody")
Greeting("hello:", "Joe", "Anna", "Eileen")

jQuery issue - #<an Object> has no method

I had this problem, or one that looked superficially similar, yesterday. It turned out that I wasn't being careful when mixing jQuery and prototype. I found several solutions at http://docs.jquery.com/Using_jQuery_with_Other_Libraries. I opted for

var $j = jQuery.noConflict();

but there are other reasonable options described there.

How does a Java HashMap handle different objects with the same hash code?

I will not get into the details of how HashMap works, but will give an example so we can remember how HashMap works by relating it to reality.

We have Key, Value ,HashCode and bucket.

For sometime, we will relate each of them with the following:

  • Bucket -> A Society
  • HashCode -> Society's address(unique always)
  • Value -> A House in the Society
  • Key -> House address.

Using Map.get(key) :

Stevie wants to get to his friend's(Josse) house who lives in a villa in a VIP society, let it be JavaLovers Society. Josse's address is his SSN(which is different for everyone). There's an index maintained in which we find out the Society's name based on SSN. This index can be considered to be an algorithm to find out the HashCode.

  • SSN Society's Name
  • 92313(Josse's) -- JavaLovers
  • 13214 -- AngularJSLovers
  • 98080 -- JavaLovers
  • 53808 -- BiologyLovers

  1. This SSN(key) first gives us a HashCode(from the index table) which is nothing but Society's name.
  2. Now, mulitple houses can be in the same society, so the HashCode can be common.
  3. Suppose, the Society is common for two houses, how are we going to identify which house we are going to, yes, by using the (SSN)key which is nothing but the House address

Using Map.put(key,Value)

This finds a suitable society for this Value by finding the HashCode and then the value is stored.

I hope this helps and this is open for modifications.

How to export all data from table to an insertable sql format?

I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).

If you dont have identity column in table B_table:

INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table

If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.

In case if you dont have existing B_table in B_db

SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table

will create table B_table in database B_db with all existing values

jQuery scroll() detect when user stops scrolling

Here is how you can handle this:

_x000D_
_x000D_
    var scrollStop = function (callback) {_x000D_
        if (!callback || typeof callback !== 'function') return;_x000D_
        var isScrolling;_x000D_
        window.addEventListener('scroll', function (event) {_x000D_
            window.clearTimeout(isScrolling);_x000D_
            isScrolling = setTimeout(function() {_x000D_
                callback();_x000D_
            }, 66);_x000D_
        }, false);_x000D_
    };_x000D_
    scrollStop(function () {_x000D_
        console.log('Scrolling has stopped.');_x000D_
    });
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <title>Title</title>_x000D_
</head>_x000D_
<body>_x000D_
.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>.<br>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I ignore a directory with SVN?

"Thank-you" svn for such a hideous, bogus and difficult way to ignore files.

So I wrote a script svn-ignore-all:

#!/bin/sh

# svn-ignore-all

# usage: 
#   1. run svn status to see what is going on at each step 
#   2. add or commit all files that you DO want to have in svn
#   3. remove any random files that you don't want to svn:ignore
#   4. run this script to svn:ignore everything marked '?' in output of `svn status`

svn status |
grep '^?' |
sed 's/^? *//' |
while read f; do
    d=`dirname "$f"`
    b=`basename "$f"`
    ignore=`svn propget svn:ignore "$d"`
    if [ -n "$ignore" ]; then
        ignore="$ignore
"
    fi
    ignore="$ignore$b"
    svn propset svn:ignore "$ignore" "$d"
done

Also, to ignore specific list of files / pathnames, we can use this variant svn-ignore. I guess svn-ignore-all should really be like xargs svn-ignore.

#!/bin/sh

# svn-ignore

# usage:
#   svn-ignore file/to/ignore ...

for f; do
    d=`dirname "$f"`
    b=`basename "$f"`
    ignore=`svn propget svn:ignore "$d"`
    if [ -n "$ignore" ]; then
        ignore="$ignore
"
    fi
    ignore="$ignore$b"
    svn propset svn:ignore "$ignore" "$d"
done

One more thing: I tend to pollute my svn checkouts with many random files. When it's time to commit, I move those files into an 'old' subdirectory, and tell svn to ignore 'old'.

How to unload a package without restarting R

You can try all you want to remove a package (and all the dependencies it brought in alongside) using unloadNamespace() but the memory footprint will still persist. And no, detach("package:,packageName", unload=TRUE, force = TRUE) will not work either.

From a fresh new console or Session > Restart R check memory with the pryr package:

pryr::mem_used()

# 40.6 MB   ## This will depend on which packages are loaded obviously (can also fluctuate a bit after the decimal)

Check my sessionInfo()

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] compiler_3.6.1   pryr_0.1.4       magrittr_1.5     tools_3.6.1      Rcpp_1.0.3       stringi_1.4.3    codetools_0.2-16 stringr_1.4.0   
[9] packrat_0.5.0   

Let's load the Seurat package and check the new memory footprint:

library(Seurat)
pryr::mem_used()

# 172 MB    ## Likely to change in the future but just to give you an idea

Let's use unloadNamespace() to remove everything:

unloadNamespace("Seurat")
unloadNamespace("ape")
unloadNamespace("cluster")
unloadNamespace("cowplot")
unloadNamespace("ROCR")
unloadNamespace("gplots")
unloadNamespace("caTools")
unloadNamespace("bitops")
unloadNamespace("fitdistrplus")
unloadNamespace("RColorBrewer")
unloadNamespace("sctransform")
unloadNamespace("future.apply")
unloadNamespace("future")
unloadNamespace("plotly")
unloadNamespace("ggrepel")
unloadNamespace("ggridges")
unloadNamespace("ggplot2")
unloadNamespace("gridExtra")
unloadNamespace("gtable")
unloadNamespace("uwot")
unloadNamespace("irlba")
unloadNamespace("leiden")
unloadNamespace("reticulate")
unloadNamespace("rsvd")
unloadNamespace("survival")
unloadNamespace("Matrix")
unloadNamespace("nlme")
unloadNamespace("lmtest")
unloadNamespace("zoo")
unloadNamespace("metap")
unloadNamespace("lattice")
unloadNamespace("grid")
unloadNamespace("httr")
unloadNamespace("ica")
unloadNamespace("igraph")
unloadNamespace("irlba")
unloadNamespace("KernSmooth")
unloadNamespace("leiden")
unloadNamespace("MASS")
unloadNamespace("pbapply")
unloadNamespace("plotly")
unloadNamespace("png")
unloadNamespace("RANN")
unloadNamespace("RcppAnnoy")
unloadNamespace("tidyr")
unloadNamespace("dplyr")
unloadNamespace("tibble")
unloadNamespace("RANN")
unloadNamespace("tidyselect")
unloadNamespace("purrr")
unloadNamespace("htmlwidgets")
unloadNamespace("htmltools")
unloadNamespace("lifecycle")
unloadNamespace("pillar")
unloadNamespace("vctrs")
unloadNamespace("rlang")
unloadNamespace("Rtsne")
unloadNamespace("SDMTools")
unloadNamespace("Rdpack")
unloadNamespace("bibtex")
unloadNamespace("tsne")
unloadNamespace("backports")
unloadNamespace("R6")
unloadNamespace("lazyeval")
unloadNamespace("scales")
unloadNamespace("munsell")
unloadNamespace("colorspace")
unloadNamespace("npsurv")
unloadNamespace("compiler")
unloadNamespace("digest")
unloadNamespace("R.utils")
unloadNamespace("pkgconfig")
unloadNamespace("gbRd")
unloadNamespace("parallel")
unloadNamespace("gdata")
unloadNamespace("listenv")
unloadNamespace("crayon")
unloadNamespace("splines")
unloadNamespace("zeallot")
unloadNamespace("reshape")
unloadNamespace("glue")
unloadNamespace("lsei")
unloadNamespace("RcppParallel")
unloadNamespace("data.table")
unloadNamespace("viridisLite")
unloadNamespace("globals")

Now check sessionInfo():

R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] tools_3.6.1       stringr_1.4.0     rstudioapi_0.10   pryr_0.1.4        jsonlite_1.6      gtools_3.8.1      R.oo_1.22.0      
 [8] magrittr_1.5      Rcpp_1.0.3        R.methodsS3_1.7.1 stringi_1.4.3     plyr_1.8.4        reshape2_1.4.3    codetools_0.2-16 
[15] packrat_0.5.0     assertthat_0.2.1 

Check the memory footprint:

pryr::mem_used()

# 173 MB

Link to screen-cast demonstration

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")