Programs & Examples On #Promotion code

How to add url parameter to the current url?

Maybe you can write a function as follows:

var addParams = function(key, val, url) {
  var arr = url.split('?');
  if(arr.length == 1) {
    return url + '?' + key + '=' + val;
  }
  else if(arr.length == 2) {
    var params = arr[1].split('&');
    var p = {};
    var a = [];
    var strarr = [];
    $.each(params, function(index, element) {
      a = element.split('=');
      p[a[0]] = a[1];
      })
    p[key] = val;
    for(var o in p) {
      strarr.push(o + '=' + p[o]);
    }
    var str = strarr.join('&');
    return(arr[0] + '?' + str);
  }
}

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can use it like this:

In Mvc:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

In Html:

<input type="text" name="Id" data_val_number="10"/>

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Java Swing revalidate() vs repaint()

revalidate is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel are considered dirty by the RepaintManager.

repaint is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.

Join two data frames, select all columns from one and some columns from the other

I got an error: 'a not found' using the suggested code:

from pyspark.sql.functions import col df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

I changed a.columns to df1.columns and it worked out.

Collections sort(List<T>,Comparator<? super T>) method example

To use Collections sort(List,Comparator) , you need to create a class that implements Comparator Interface, and code for the compare() in it, through Comparator Interface

You can do something like this:

class StudentComparator implements Comparator
{
    public int compare (Student s1 Student s2)
    {
        // code to compare 2 students
    }
}

To sort do this:

 Collections.sort(List,new StudentComparator())

C# "must declare a body because it is not marked abstract, extern, or partial"

I got the same error message because I had a function with a parameter named with a reserved word.

   public int SaveDelegate(MyModel.Delegate delegate)

Renaming the variable delegate solved the problem.

All combinations of a list of lists

The most elegant solution is to use itertools.product in python 2.6.

If you aren't using Python 2.6, the docs for itertools.product actually show an equivalent function to do the product the "manual" way:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

Get Android Device Name

In order to get Android device name you have to add only a single line of code:

android.os.Build.MODEL;

Found here: getting-android-device-name

Avoid duplicates in INSERT INTO SELECT query in SQL Server

In MySQL you can do this:

INSERT IGNORE INTO Table2(Id, Name) SELECT Id, Name FROM Table1

Does SQL Server have anything similar?

How to delete a file from SD card?

private boolean deleteFromExternalStorage(File file) {
                        String fileName = "/Music/";
                        String myPath= Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;

                        file = new File(myPath);
                        System.out.println("fullPath - " + myPath);
                            if (file.exists() && file.canRead()) {
                                System.out.println(" Test - ");
                                file.delete();
                                return false; // File exists
                            }
                            System.out.println(" Test2 - ");
                            return true; // File not exists
                    }

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

Select From all tables - MySQL

SELECT product FROM Your_table_name WHERE Product LIKE '%XYZ%';

The above statement will show result from a single table. If you want to add more tables then simply use the UNION statement.

SELECT product FROM Table_name_1 
WHERE Product LIKE '%XYZ%'  
UNION  
SELECT product FROM Table_name_2 
WHERE Product LIKE '%XYZ%'  
UNION  
SELECT product FROM Table_name_3 
WHERE Product LIKE '%XYZ%' 

... and so on

Error in finding last used cell in Excel with VBA

One important note to keep in mind when using the solution ...

LastRow = ws.Cells.Find(What:="*", After:=ws.range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

... is to ensure that your LastRow variable is of Long type:

Dim LastRow as Long

Otherwise you will end up getting OVERFLOW errors in certain situations in .XLSX workbooks

This is my encapsulated function that I drop in to various code uses.

Private Function FindLastRow(ws As Worksheet) As Long
    ' --------------------------------------------------------------------------------
    ' Find the last used Row on a Worksheet
    ' --------------------------------------------------------------------------------
    If WorksheetFunction.CountA(ws.Cells) > 0 Then
        ' Search for any entry, by searching backwards by Rows.
        FindLastRow = ws.Cells.Find(What:="*", After:=ws.range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
End Function

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

For me the issue was that the DNS record was wrong...

The following, which proved very helpful, is largely taken from this blog post.

This error message is actually pretty specific and the solution quite simple.

You get this error message only if you are trying to connect to a SQL Server named instance. For a default instance, you never see this because even if we failed at this stage (i.e. error locating server/instance specified), we will continue to try connect using default values, e.g default TCP port 1433, default pipe name for Named Pipes.

Every time a client makes a connection to SQL Server named instance, we will send a SSRP UDP packet to the server machine UDP port 1434. We need this step to know configuration information of the SQL instance, e.g., protocols enabled, TCP port, pipe name etc. Without this information the client does not know how to connect and it fails with this error message.

In a word, the reason that we get this error message is the client stack could not receive SSRP response UDP packet from SQL Browser. In order to isolate the exact issue follow these steps:

  1. Make sure your server name is correct, e.g., no typo on the name.

  2. Make sure your instance name is correct and there is actually such an instance on your target machine. (Be aware that some applications convert \ to ).

  3. Make sure the server machine is reachable, e.g, DNS can be resolve correctly, you are able to ping the server (not always true).

  4. Make sure the SQL Browser service is running on the server.

  5. If the firewall is enabled on the server, you need to put sqlbrowser.exe and/or UDP port 1434 into exception.

There is one corner case where you may still fail after you checked steps 1 to 4. It also may happen when:

  1. your server is a named instance on cluster or on a multi-homed machine
  2. your client is a Vista machine with Firewall on.

A tool which could prove useful (it did for me) is PortQry. If this command returns information and it contains your target instance, then you can rule out possiblity 4) and 5) above, meaning you do have a SQL Browser running and your firewall does not block SQL Browser UDP packet. In this case, you can check other possible issues such as an incorrect connection string.

As a final note, the error message for the same issue when you use SNAC is: [SQL Native Client]SQL Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].

Microsoft recently released a guided walk through that can serve as a one stop shop to troubleshoot a majority of connectivity issues to SQL Server: Solving Connectivity errors to SQL Server

Text Editor which shows \r\n?

I'd bet that Programmer's Notepad would give you something like that...

Redis: Show database size/size for keys

You might find it very useful to sample Redis keys and group them by type. Salvatore has written a tool called redis-sampler that issues about 10000 RANDOMKEY commands followed by a TYPE on retrieved keys. In a matter of seconds, or minutes, you should get a fairly accurate view of the distribution of key types.

I've written an extension (unfortunately not anywhere open-source because it's work related), that adds a bit of introspection of key names via regexs that give you an idea of what kinds of application keys (according to whatever naming structure you're using), are stored in Redis. Combined with the more general output of redis-sampler, this should give you an extremely good idea of what's going on.

How do you run your own code alongside Tkinter's event loop?

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

Creating an instance using the class name and calling constructor

You can use Class.forName() to get a Class object of the desired class.

Then use getConstructor() to find the desired Constructor object.

Finally, call newInstance() on that object to get your new instance.

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

Using HTML and Local Images Within UIWebView

You can add folder (say WEB with sub folders css, img and js and file test.html) to your project by choosing Add Files to "MyProj" and selecting Create folder references. Now the following code will take care about all the referred images, css and javascript

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WEB/test.html" ofType:nil];
[webView  loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];

Open firewall port on CentOS 7

The top answers here work, but I found something more elegant in Michael Hampton's answer to a related question. The "new" (firewalld-0.3.9-11+) --runtime-to-permanent option to firewall-cmd lets you create runtime rules and test them out before making them permanent:

$ firewall-cmd --zone=<zone> --add-port=2888/tcp
<Test it out>
$ firewall-cmd --runtime-to-permanent

Or to revert the runtime-only changes:

$ firewall-cmd --reload

Also see Antony Nguyen's comment. Apparently firewall-cmd --reload may not work properly in some cases where rules have been removed. In that case, he suggests restarting the firewalld service:

$ systemctl restart firewalld

Android ADB commands to get the device properties

For Power-Shell

./adb shell getprop | Select-String -Pattern '(model)|(version.sdk)|(manufacturer)|(platform)|(serialno)|(product.name)|(brand)'

For linux(burrowing asnwer from @0x8BADF00D)

adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"

For single string find in power shell

./adb shell getprop | Select-String -Pattern 'model'

or

./adb shell getprop | Select-String -Pattern '(model)'

For multiple

./adb shell getprop | Select-String -Pattern '(a|b|c|d)'

Upload failed You need to use a different version code for your APK because you already have one with version code 2

android:versionCode="28"

Your previous versionCode was 28. You should increment it by 1 to 29.

android:versionCode="29"

Presumably, your previous app versions were 1 through 28. By releasing with versionCode 3, you are conflicting with a previous version of your app that was already released with this versionCode.

AFNetworking Post Request

// For Image with parameter /// AFMultipartFormData

NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    if (Imagedata.length>0) {
        [formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    }
} progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     NSLog(@"update_profile %@", responseObject);

     if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
             [self.navigationController popViewControllerAnimated:YES];

         }] animated:YES completion:nil];


     }
     else
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
         }] animated:YES completion:nil];

     }
     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     [SVProgressHUD dismiss];
 }];

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Difference between declaring variables before or in loop?

Which is better, a or b?

From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).

From a maintenance perspective, b is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.

.htaccess 301 redirect of single page

redirect 301 /contact.php /contact-us.php

There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally

fatal error LNK1169: one or more multiply defined symbols found in game programming

I answered a similar question here.

In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

That's what programmers call a "quick and dirty" solution, but sometimes you just want the build to be completed and get to the bottom of the problem later, so that's kind of a ad-hoc solution. To actually avoid this error, provided that you want

int WIDTH = 1024;
int HEIGHT = 800;

to be shared among several source files, just declare them only in a single .c / .cpp file, and refer to them in a header file:

extern int WIDTH;
extern int HEIGHT;

Then include the header in any other source file you wish these global variables to be available.

How to align LinearLayout at the center of its parent?

The problem is that the root's (the main layout you store the other elements) gravity is not set. If you change it to center the other elements' gravity must work just fine.

CSS Box Shadow - Top and Bottom Only

I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.

Legend: insetOption leftPosition topPosition blurStrength spreadStrength color

Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).

Solution

.styleName {   
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);  

/* for IE 9 */ 
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for webkit browsers */ 
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);   
}

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Yes. Regardless of what anyone else says, Eclipse contains some bug(s) that sometimes causes the workspace setting (e.g. 1.6 compliant) to be ignored. This is even when the per-project settings are disabled, the workspace settings are correct (1.6), the JRE is correctly set, there is only a 1.6 JRE defined, etc., all the things that people generally recommend when questions about this issue are posted to various forums (as they often are).

We hit this irregularly, but often, and typically when there is some unrelated issue with build-time dependencies or other project issues. It seems to fall into the general category of "unable to get Eclipse to recognize reality" issues that I always attribute, rightly or wrongly, to refresh issues with Eclipse' extensive metadata. Eclipse metadata is a blessing and a curse; when all is working well, it makes the tool exceedingly powerful and fast. But when there are problems, the extensive caching makes straightening out the issues more difficult - sometimes much more difficult - than with other tools.

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Important: This issue drove me crazy for a couple days and I couldn't figure out what was going on with my curl & openssl installations. I finally figured out that it was my intermediate certificate (in my case, GoDaddy) which was out of date. I went back to my godaddy SSL admin panel, downloaded the new intermediate certificate, and the issue disappeared.

I'm sure this is the issue for some of you.

Apparently, GoDaddy had changed their intermediate certificate at some point, due to scurity issues, as they now display this warning:

"Please be sure to use the new SHA-2 intermediate certificates included in your downloaded bundle."

Hope this helps some of you, because I was going nuts and this cleaned up the issue on ALL my servers.

Spark : how to run spark file from spark shell

Just to give more perspective to the answers

Spark-shell is a scala repl

You can type :help to see the list of operation that are possible inside the scala shell

scala> :help
All commands can be abbreviated, e.g., :he instead of :help.
:edit <id>|<line>        edit history
:help [command]          print this summary or command-specific help
:history [num]           show the history (optional num is commands to show)
:h? <string>             search the history
:imports [name name ...] show import history, identifying sources of names
:implicits [-v]          show the implicits in scope
:javap <path|class>      disassemble a file or class name
:line <id>|<line>        place line(s) at the end of history
:load <path>             interpret lines in a file
:paste [-raw] [path]     enter paste mode or paste a file
:power                   enable power user mode
:quit                    exit the interpreter
:replay [options]        reset the repl and replay all previous commands
:require <path>          add a jar to the classpath
:reset [options]         reset the repl to its initial state, forgetting all session entries
:save <path>             save replayable session to a file
:sh <command line>       run a shell command (result is implicitly => List[String])
:settings <options>      update compiler options, if possible; see reset
:silent                  disable/enable automatic printing of results
:type [-v] <expr>        display the type of an expression without evaluating it
:kind [-v] <expr>        display the kind of expression's type
:warnings                show the suppressed warnings from the most recent line which had any

:load interpret lines in a file

Sort a list by multiple attributes?

A key can be a function that returns a tuple:

s = sorted(s, key = lambda x: (x[1], x[2]))

Or you can achieve the same using itemgetter (which is faster and avoids a Python function call):

import operator
s = sorted(s, key = operator.itemgetter(1, 2))

And notice that here you can use sort instead of using sorted and then reassigning:

s.sort(key = operator.itemgetter(1, 2))

How to use patterns in a case statement?

if and grep -Eq

arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
  echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
  echo 'second'
fi

where:

  • -q prevents grep from producing output, it just produces the exit status
  • -E enables extended regular expressions

I like this because:

One downside is that this is likely slower than case since it calls an external grep program, but I tend to consider performance last when using Bash.

case is POSIX 7

Bash appears to follow POSIX by default without shopt as mentioned by https://stackoverflow.com/a/4555979/895245

Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":

The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]

The format for the case construct is as follows:

case word in
     [(] pattern1 ) compound-list ;;
     [[(] pattern[ | pattern] ... ) compound-list ;;] ...
     [[(] pattern[ | pattern] ... ) compound-list]
  esac

and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?, * and [].

Add line break to ::after or ::before pseudo-element content

Found this question here that seems to ask the same thing: Newline character sequence in CSS 'content' property?

Looks like you can use \A or \00000a to achieve a newline

Python way to clone a git repository

With Dulwich tip you should be able to do:

from dulwich.repo import Repo
Repo("/path/to/source").clone("/path/to/target")

This is still very basic - it copies across the objects and the refs, but it doesn't yet create the contents of the working tree if you create a non-bare repository.

How do I rotate the Android emulator display?

Ubuntu 12.10 (Quantal Quetzal): [LEFT Ctrl] + F12.

For some reason NumLock isn't working on a new install on a Dell XPS 8500, but the above worked.

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

Write output to a text file in PowerShell

The simplest way is to just redirect the output, like so:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

How to check if a value exists in an object using JavaScript

Try:

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

Object.keys(obj).forEach(function(key) {
  if (obj[key] == 'test1') {
    alert('exists');
  }
});
_x000D_
_x000D_
_x000D_

Or

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

var found = Object.keys(obj).filter(function(key) {
  return obj[key] === 'test1';
});

if (found.length) {
   alert('exists');
}
_x000D_
_x000D_
_x000D_

This will not work for NaN and -0 for those values. You can use (instead of ===) what is new in ECMAScript 6:

 Object.is(obj[key], value);

With modern browsers you can also use:

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

if (Object.values(obj).includes('test1')) {
  alert('exists');
}
_x000D_
_x000D_
_x000D_

How to instantiate a File object in JavaScript?

Update

BlobBuilder has been obsoleted see how you go using it, if you're using it for testing purposes.

Otherwise apply the below with migration strategies of going to Blob, such as the answers to this question.

Use a Blob instead

As an alternative there is a Blob that you can use in place of File as it is what File interface derives from as per W3C spec:

interface File : Blob {
    readonly attribute DOMString name;
    readonly attribute Date lastModifiedDate;
};

The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Create the Blob

Using the BlobBuilder like this on an existing JavaScript method that takes a File to upload via XMLHttpRequest and supplying a Blob to it works fine like this:

var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);

xhr.responseType = 'arraybuffer';

bb.append(this.response); // Note: not xhr.responseText

//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');

/* more setup code */
xhr.send(blob);

Extended example

The rest of the sample is up on jsFiddle in a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.

Google Play Services Missing in Emulator (Android 4.4.2)

Setp 1 : Download the following apk files. 1)com.google.android.gms.apk (https://androidfilehost.com/?fid=95916177934534438) 2)com.android.vending-4.4.22.apk (https://androidfilehost.com/?fid=23203820527945795)

Step 2 : Create a new AVD without the google API's

Step 3 : Run the AVD (Start the emulator)

Step 4 : Install the downloaded apks using adb .

     1)adb install com.google.android.gms-6.7.76_\(1745988-038\)-6776038-minAPI9.apk  
     2)adb install com.android.vending-4.4.22.apk

adb come up with android sdks/studio

Step 5 : Create the application in google developer console

Step 6 : Configure the api key in your Androidmanifest.xml and google api version.

Note : In step1 you need to download the apk based on your Android API level(..18,19,21..) and google play services version (5,5.1,6,6.5......)

This will work 100%.

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

How to get out of while loop in java with Scanner method "hasNext" as condition?

it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer. the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Most programs will check the $EDITOR environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.

How to do this:

  • Add the following to your ~/.bashrc file:
    export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
  • or just type the following command into your Terminal:
    echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc

If you are using zsh, use ~/.zshrc instead of ~/.bashrc.

CSS transition with visibility not working

Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.

This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see http://taccgl.org/blog/css-transition-visibility.html

It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See http://taccgl.org/blog/css-transition-opacity-for-fade-effects.html.

This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.

open existing java project in eclipse

The typical pattern is to check out the root project folder (=the one containing a file called ".project") from SVN using eclipse's svn integration (SVN repository exploring perspective). The project is then recognized automatically.

ReferenceError: Invalid left-hand side in assignment

You have to use == to compare (or even ===, if you want to compare types). A single = is for assignment.

if (one == 'rock' && two == 'rock') {
    console.log('Tie! Try again!');
}

Default argument values in JavaScript functions

You have to check if the argument is undefined:

function func(a, b) {
    if (a === undefined) a = "default value";
    if (b === undefined) b = "default value";
}

Also note that this question has been answered before.

Spring MVC - How to return simple String as JSON in Rest Controller

You can easily return JSON with String in property response as following

@RestController
public class TestController {
    @RequestMapping(value = "/getString", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map getString() {
        return Collections.singletonMap("response", "Hello World");
    }
}

Python Git Module experiences?

For the sake of completeness, http://github.com/alex/pyvcs/ is an abstraction layer for all dvcs's. It uses dulwich, but provides interop with the other dvcs's.

How to maintain aspect ratio using HTML IMG tag

Set width and height of the images to auto, but limit both max-width and max-height:

img {
    max-width:64px;
    max-height:64px;
    width:auto;
    height:auto;
}

Fiddle

If you want to display images of arbitrary size in the 64x64px "frames", you can use inline-block wrappers and positioning for them, like in this fiddle.

How do I tokenize a string in C++?

I posted this answer for similar question.
Don't reinvent the wheel. I've used a number of libraries and the fastest and most flexible I have come across is: C++ String Toolkit Library.

Here is an example of how to use it that I've posted else where on the stackoverflow.

#include <iostream>
#include <vector>
#include <string>
#include <strtk.hpp>

const char *whitespace  = " \t\r\n\f";
const char *whitespace_and_punctuation  = " \t\r\n\f;,=";

int main()
{
    {   // normal parsing of a string into a vector of strings
       std::string s("Somewhere down the road");
       std::vector<std::string> result;
       if( strtk::parse( s, whitespace, result ) )
       {
           for(size_t i = 0; i < result.size(); ++i )
            std::cout << result[i] << std::endl;
       }
    }

    {  // parsing a string into a vector of floats with other separators
       // besides spaces

       std::string s("3.0, 3.14; 4.0");
       std::vector<float> values;
       if( strtk::parse( s, whitespace_and_punctuation, values ) )
       {
           for(size_t i = 0; i < values.size(); ++i )
            std::cout << values[i] << std::endl;
       }
    }

    {  // parsing a string into specific variables

       std::string s("angle = 45; radius = 9.9");
       std::string w1, w2;
       float v1, v2;
       if( strtk::parse( s, whitespace_and_punctuation, w1, v1, w2, v2) )
       {
           std::cout << "word " << w1 << ", value " << v1 << std::endl;
           std::cout << "word " << w2 << ", value " << v2 << std::endl;
       }
    }

    return 0;
}

RuntimeWarning: invalid value encountered in divide

You are dividing by rr which may be 0.0. Check if rr is zero and do something reasonable other than using it in the denominator.

import module from string variable

Apart from using the importlib one can also use exec method to import a module from a string variable.

Here I am showing an example of importing the combinations method from itertools package using the exec method:

MODULES = [
    ['itertools','combinations'],
]

for ITEM in MODULES:
    import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
    exec(import_str)

ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
    print(elements)

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

Changing the cursor in WPF sometimes works, sometimes doesn't

The following worked for me:

ForceCursor = true;
Cursor = Cursors.Wait;

Handling very large numbers in Python

You could do this for the fun of it, but other than that it's not a good idea. It would not speed up anything I can think of.

  • Getting the cards in a hand will be an integer factoring operation which is much more expensive than just accessing an array.

  • Adding cards would be multiplication, and removing cards division, both of large multi-word numbers, which are more expensive operations than adding or removing elements from lists.

  • The actual numeric value of a hand will tell you nothing. You will need to factor the primes and follow the Poker rules to compare two hands. h1 < h2 for such hands means nothing.

LaTeX Optional Arguments

Here's my attempt, it doesn't follow your specs exactly though. Not fully tested, so be cautious.

\newcount\seccount

\def\sec{%
    \seccount0%
    \let\go\secnext\go
}

\def\secnext#1{%
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\secparse{%
    \ifx\next\bgroup
        \let\go\secparseii
    \else
        \let\go\seclast
    \fi
    \go
}

\def\secparseii#1{%
    \ifnum\seccount>0, \fi
    \advance\seccount1\relax
    \last
    \def\last{#1}%
    \futurelet\next\secparse
}

\def\seclast{\ifnum\seccount>0{} and \fi\last}%

\sec{a}{b}{c}{d}{e}
% outputs "a, b, c, d and e"

\sec{a}
% outputs "a"

\sec{a}{b}
% outputs "a and b"

DLL References in Visual C++

The additional include directories are relative to the project dir. This is normally the dir where your project file, *.vcproj, is located. I guess that in your case you have to add just "include" to your include and library directories.

If you want to be sure what your project dir is, you can check the value of the $(ProjectDir) macro. To do that go to "C/C++ -> Additional Include Directories", press the "..." button and in the pop-up dialog press "Macros>>".

Difference between <context:annotation-config> and <context:component-scan>

<context:component-scan /> implicitly enables <context:annotation-config/>

try with <context:component-scan base-package="..." annotation-config="false"/> , in your configuration @Service, @Repository, @Component works fine, but @Autowired,@Resource and @Inject doesn't work.

This means AutowiredAnnotationBeanPostProcessor will not be enabled and Spring container will not process the Autowiring annotations.

Attach a file from MemoryStream to a MailMessage in C#

Here is the sample code.

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
ms.Position = 0;

System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.txt";

// I guess you know how to send email with an attachment
// after sending email
ms.Close();

Edit 1

You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf

Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"

Parameter in like clause JPQL

Use JpaRepository or CrudRepository as repository interface:

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

    @Query("SELECT t from Customer t where LOWER(t.name) LIKE %:name%")
    public List<Customer> findByName(@Param("name") String name);

}


@Service(value="customerService")
public class CustomerServiceImpl implements CustomerService {

    private CustomerRepository customerRepository;
    
    //...

    @Override
    public List<Customer> pattern(String text) throws Exception {
        return customerRepository.findByName(text.toLowerCase());
    }
}

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

Use ISNULL(field, 0) It can also be used with aggregates:

ISNULL(count(field), 0)

However, you might consider changing count(field) to count(*)

Edit:

try:

closedcases = ISNULL(
   (select count(closed) from ticket       
    where assigned_to = c.user_id and closed is not null       
    group by assigned_to), 0), 

opencases = ISNULL(
    (select count(closed) from ticket 
     where assigned_to = c.user_id and closed is null 
     group by assigned_to), 0),

How do I remove a library from the arduino environment?

Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.

Your Arduino library folder should look like this (on Windows):

  My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
  My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
  My Documents\Arduino\libraries\ArduinoParty\examples
  ....

or like this (on Mac and Linux):

  Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
  Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
  Documents/Arduino/libraries/ArduinoParty/examples

The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.

How to scroll the page when a modal dialog is longer than the screen?

fixed positioning alone should have fixed that problem but another good workaround to avoid this issue is to place your modal divs or elements at the bottom of the page not within your sites layout. Most modal plugins give their modal positioning absolute to allow the user keep main page scrolling.

<html>
        <body>
        <!-- Put all your page layouts and elements


        <!-- Let the last element be the modal elemment  -->
        <div id="myModals">
        ...
        </div>

        </body>
</html>

How can I debug javascript on Android?

You could try https://github.com/fullpipe/screen-log. Tried to make it clean and simple.

Convert Variable Name to String?

Totally possible with the python-varname package (python3):

from varname import nameof

s = 'Hey!'

print (nameof(s))

Output:

s

Get the package here:

https://github.com/pwwang/python-varname

How do I pass a unique_ptr argument to a constructor or a function?

Edit: This answer is wrong, even though, strictly speaking, the code works. I'm only leaving it here because the discussion under it is too useful. This other answer is the best answer given at the time I last edited this: How do I pass a unique_ptr argument to a constructor or a function?

The basic idea of ::std::move is that people who are passing you the unique_ptr should be using it to express the knowledge that they know the unique_ptr they're passing in will lose ownership.

This means you should be using an rvalue reference to a unique_ptr in your methods, not a unique_ptr itself. This won't work anyway because passing in a plain old unique_ptr would require making a copy, and that's explicitly forbidden in the interface for unique_ptr. Interestingly enough, using a named rvalue reference turns it back into an lvalue again, so you need to use ::std::move inside your methods as well.

This means your two methods should look like this:

Base(Base::UPtr &&n) : next(::std::move(n)) {} // Spaces for readability

void setNext(Base::UPtr &&n) { next = ::std::move(n); }

Then people using the methods would do this:

Base::UPtr objptr{ new Base; }
Base::UPtr objptr2{ new Base; }
Base fred(::std::move(objptr)); // objptr now loses ownership
fred.setNext(::std::move(objptr2)); // objptr2 now loses ownership

As you see, the ::std::move expresses that the pointer is going to lose ownership at the point where it's most relevant and helpful to know. If this happened invisibly, it would be very confusing for people using your class to have objptr suddenly lose ownership for no readily apparent reason.

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

How to update core-js to core-js@3 dependency?

With this

npm install --save core-js@^3

you now get the error

"core-js@<3 is no longer maintained and not recommended for usage due to the number of
issues. Please, upgrade your dependencies to the actual version of core-js@3"

so you might want to instead try

npm install --save core-js@3

if you're reading this post June 9 2020.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We solved the problem by stopping the FinalizerWatchdogDaemon.

public static void fix() {
    try {
        Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

        Method method = clazz.getSuperclass().getDeclaredMethod("stop");
        method.setAccessible(true);

        Field field = clazz.getDeclaredField("INSTANCE");
        field.setAccessible(true);

        method.invoke(field.get(null));

    }
    catch (Throwable e) {
        e.printStackTrace();
    }
}

You can call the method in Application's lifecycle, like attachBaseContext(). For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.

How to check status of PostgreSQL server Mac OS X

You can use brew to start/stop pgsql. I've following short cuts in my ~/.bashrc file

alias start-pg='brew services start postgresql'
alias stop-pg='brew services stop postgresql'
alias restart-pg='brew services restart postgresql'

What is the difference between primary, unique and foreign key constraints, and indexes?

1)A primary key is a set of one or more attributes that uniquely identifies tuple within relation.

2)A foreign key is a set of attributes from a relation scheme which can be uniquely identify tuples fron another relation scheme.

How to find out if an item is present in a std::vector?

Use find from the algorithm header of stl.I've illustrated its use with int type. You can use any type you like as long as you can compare for equality (overload == if you need to for your custom class).

#include <algorithm>
#include <vector>

using namespace std;
int main()
{   
    typedef vector<int> IntContainer;
    typedef IntContainer::iterator IntIterator;

    IntContainer vw;

    //...

    // find 5
    IntIterator i = find(vw.begin(), vw.end(), 5);

    if (i != vw.end()) {
        // found it
    } else {
        // doesn't exist
    }

    return 0;
}

How to use if statements in LESS

I wrote a mixin for some syntactic sugar ;)
Maybe someone likes this way of writing if-then-else better than using guards

depends on Less 1.7.0

https://github.com/pixelass/more-or-less/blob/master/less/fn/_if.less

Usage:

.if(isnumber(2), {
    .-then(){
        log {
            isnumber: true;
        }
    }
    .-else(){
        log {
            isnumber: false;
        }
    }
});

.if(lightness(#fff) gt (20% * 2), {
    .-then(){
        log {
            is-light: true;
        }
    }
});

using on example from above

.if(@debug, {
    .-then(){
        header {
            background-color: yellow;
            #title {
                background-color: orange;
            }
        }
        article {
            background-color: red;
        }
    }
});

Using R to list all files with a specified extension

files <- list.files(pattern = "\\.dbf$")

$ at the end means that this is end of string. "dbf$" will work too, but adding \\. (. is special character in regular expressions so you need to escape it) ensure that you match only files with extension .dbf (in case you have e.g. .adbf files).

Simple dynamic breadcrumb

hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.

//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);

I dont know if that is the most elegant way, but it now works for me.

I add that code before this one on line 13 or something

// Find out the index for the last value in our path array
$last = end(array_keys($path));

@Scope("prototype") bean scope not creating new bean

Your controller also need the @Scope("prototype") defined

like this:

@Controller
@Scope("prototype")
public class HomeController { 
 .....
 .....
 .....

}

How to convert md5 string to normal text?

Md5 is a hashing algorithm. There is no way to retrieve the original input from the hashed result.

If you want to add a "forgotten password?" feature, you could send your user an email with a temporary link to create a new password.

Note: Sending passwords in plain text is a BAD idea :)

Overloading and overriding

shadowing = maintains two definitions at derived class and in order to project the base class definition it shadowes(hides)derived class definition and vice versa.

How to find day of week in php in a specific timezone

$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);

This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.

You might have some adventures with timezone identifiers, though.

Error: Failed to lookup view in Express

npm install [email protected] installs the previous version, if it helps.

I know in 3.x the view layout mechanic was removed, but this might not be your problem. Also replace express.createServer() with express()

Update:

It's your __dirname from environment.js
It should be:

app.use(express.static(__dirname + '../public'));

Creating a very simple 1 username/password login in php

Here is a simple php script for login and a page that can only be accessed by logged in users.

login.php

<?php
    session_start();
    echo isset($_SESSION['login']);
    if(isset($_SESSION['login'])) {
      header('LOCATION:index.php'); die();
    }
?>
<!DOCTYPE html>
<html>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
<body>
  <div class="container">
    <h3 class="text-center">Login</h3>
    <?php
      if(isset($_POST['submit'])){
        $username = $_POST['username']; $password = $_POST['password'];
        if($username === 'admin' && $password === 'password'){
          $_SESSION['login'] = true; header('LOCATION:admin.php'); die();
        } {
          echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
        }

      }
    ?>
    <form action="" method="post">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" name="password" required>
      </div>
      <button type="submit" name="submit" class="btn btn-default">Login</button>
    </form>
  </div>
</body>
</html>

admin.php ( only logged in users can access it )

<?php
    session_start();
    if(!isset($_SESSION['login'])) {
        header('LOCATION:login.php'); die();
    }
?>
<html>
    <head>
        <title>Admin Page</title>
    </head>
    <body>
        This is admin page view able only by logged in users.
    </body> 
</html>

Get changes from master into branch in Git

Easy way

# 1. Create a new remote branch A base on last master
# 2. Checkout A
# 3. Merge aq to A

Standard Android Button with a different color

You can set theme of your button to this

<style name="AppTheme.ButtonBlue" parent="Widget.AppCompat.Button.Colored">
 <item name="colorButtonNormal">@color/HEXColor</item>
 <item name="android:textColor">@color/HEXColor</item>
</style>

Module AppRegistry is not registered callable module (calling runApplication)

What worked for me was to just stop the node server running and run 'react-native run-ios' once again

Change Twitter Bootstrap Tooltip content on click

I'm using this easy way out:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $("#btn").prop('title', 'Click to copy your shorturl');_x000D_
});_x000D_
_x000D_
function myFunction(){_x000D_
  $(btn).tooltip('hide');_x000D_
  $(btn).attr('data-original-title', 'Test');_x000D_
  $(btn).tooltip('show');_x000D_
});
_x000D_
_x000D_
_x000D_

User Control - Custom Properties

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

How to Consolidate Data from Multiple Excel Columns All into One Column

Here is how you do it with some simple Excel formulae, and no fancy VBA needed. The trick is to use the OFFSET formula. Please see this example spreadsheet:

https://docs.google.com/spreadsheet/ccc?key=0AuSyDFZlcRtHdGJOSnFwREotRzFfM28tWElpZ1FaR2c&usp=sharing#gid=0

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

How to remove item from array by value?

Simply

var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1

if (index > -1) { //if found
  ary.splice(index, 1);
}

How to convert URL parameters to a JavaScript object?

If you need recursion, you can use the tiny js-extension-ling library.

npm i js-extension-ling
const jsx = require("js-extension-ling");

console.log(jsx.queryStringToObject("a=1")); 
console.log(jsx.queryStringToObject("a=1&a=3")); 
console.log(jsx.queryStringToObject("a[]=1")); 
console.log(jsx.queryStringToObject("a[]=1&a[]=pomme")); 
console.log(jsx.queryStringToObject("a[0]=one&a[1]=five"));
console.log(jsx.queryStringToObject("http://blabla?foo=bar&number=1234")); 
console.log(jsx.queryStringToObject("a[fruits][red][]=strawberry"));
console.log(jsx.queryStringToObject("a[fruits][red][]=strawberry&a[1]=five&a[fruits][red][]=cherry&a[fruits][yellow][]=lemon&a[fruits][yellow][688]=banana"));

This will output something like this:

{ a: '1' }
{ a: '3' }
{ a: { '0': '1' } }
{ a: { '0': '1', '1': 'pomme' } }
{ a: { '0': 'one', '1': 'five' } }
{ foo: 'bar', number: '1234' }
{
  a: { fruits: { red: { '0': 'strawberry' } } }
}
{
  a: {
    '1': 'five',
    fruits: {
      red: { '0': 'strawberry', '1': 'cherry' },
      yellow: { '0': 'lemon', '688': 'banana' }
    }
  }
}

Note: it's based on locutus parse_str function (https://locutus.io/php/strings/parse_str/).

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Best way to alphanumeric check in JavaScript

To check whether input_string is alphanumeric, simply use:

input_string.match(/[^\w]|_/) == null

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

create a text file using javascript

That works better with this :

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

Implicit type conversion rules in C++ operators

Since the other answers don't talk about the rules in C++11 here's one. From C++11 standard (draft n3337) §5/9 (emphasized the difference):

This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.

— If either operand is of type long double, the other shall be converted to long double.

— Otherwise, if either operand is double, the other shall be converted to double.

— Otherwise, if either operand is float, the other shall be converted to float.

— Otherwise, the integral promotions shall be performed on both operands. Then the following rules shall be applied to the promoted operands:

— If both operands have the same type, no further conversion is needed.

— Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

— Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

— Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

— Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

See here for a list that's frequently updated.

Exit from app when click button in android phonegap?

@Pradip Kharbuja

In Cordova-2.6.0.js (l. 4032) :

exitApp:function() {
  console.log("Device.exitApp() is deprecated. Use App.exitApp().");
  app.exitApp();
}

How to add a browser tab icon (favicon) for a website?

<link rel="shortcut icon" 
href="http://someWebsiteLocation/images/imageName.ico">

If i may add more clarity for those of you that are still confused. The .ico file tends to provide more transparency than the .png, which is why i recommend converting your image here as mentioned above: http://www.favicomatic.com/done also, inside the href is just the location of the image, it can be any server location, remember to add the http:// in front, otherwise it won't work.

Should I use PATCH or PUT in my REST API?

I would generally prefer something a bit simpler, like activate/deactivate sub-resource (linked by a Link header with rel=service).

POST /groups/api/v1/groups/{group id}/activate

or

POST /groups/api/v1/groups/{group id}/deactivate

For the consumer, this interface is dead-simple, and it follows REST principles without bogging you down in conceptualizing "activations" as individual resources.

ImportError: No module named - Python

from ..gen_py.lib import MyService

or

from main.gen_py.lib import MyService

Make sure you have a (at least empty) __init__.py file on each directory.

Java - No enclosing instance of type Foo is accessible

Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

 public class PQ {

    public static void main(String[] args) {

        // create dog object here
        Dog dog = new PQ().new Dog();
        //OR
        PQ pq = new PQ();
        Dog dog1 = pq.new Dog();
    }

    abstract class Animal {
        abstract void checkup();
    }

    class Dog extends Animal {
        @Override
        void checkup() {
            System.out.println("Dog checkup");

        }
    }

    class Cat extends Animal {
        @Override
        void checkup() {
            System.out.println("Cat Checkup");

        }
    }
}

How to use UIVisualEffectView to Blur Image?

Just put this blur view on the imageView. Here is an example in Objective-C:

UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];

UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];

visualEffectView.frame = imageView.bounds;
[imageView addSubview:visualEffectView];

and Swift:

var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))    

visualEffectView.frame = imageView.bounds

imageView.addSubview(visualEffectView)

Rotating and spacing axis labels in ggplot2

ggplot 3.3.0 fixes this by providing guide_axis(angle = 90) (as guide argument to scale_.. or as x argument to guides):

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))

ggplot(diamonds, aes(cut, carat)) +
  geom_boxplot() +
  scale_x_discrete(guide = guide_axis(angle = 90)) +
  # ... or, equivalently:
  # guides(x =  guide_axis(angle = 90)) +
  NULL

From the documentation of the angle argument:

Compared to setting the angle in theme() / element_text(), this also uses some heuristics to automatically pick the hjust and vjust that you probably want.


Alternatively, it also provides guide_axis(n.dodge = 2) (as guide argument to scale_.. or as x argument to guides) to overcome the over-plotting problem by dodging the labels vertically. It works quite well in this case:

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))

ggplot(diamonds, aes(cut, carat)) + 
  geom_boxplot() +
  scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
  NULL

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

How do you set autocommit in an SQL Server session?

You can turn autocommit ON by setting implicit_transactions OFF:

SET IMPLICIT_TRANSACTIONS OFF

When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

Maybe an example is clearer. This will write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION

This will not write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

The following example will update a row, and then complain that there's no transaction to commit:

SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

How to extract text from an existing docx file using python-docx

you can try this

import docx

def getText(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Wait for all jobs and return the exit code of the last failing job. Unlike solutions above, this does not require pid saving. Just bg away, and wait.

function wait_ex {
    # this waits for all jobs and returns the exit code of the last failing job
    ecode=0
    while true; do
        wait -n
        err="$?"
        [ "$err" == "127" ] && break
        [ "$err" != "0" ] && ecode="$err"
    done
    return $ecode
}

How do you extract IP addresses from files using a regex in a linux shell?

I'd suggest perl. (\d+.\d+.\d+.\d+) should probably do the trick.

EDIT: Just to make it more like a complete program, you could do something like the following (not tested):

#!/usr/bin/perl -w
use strict;

while (<>) {
    if (/(\d+\.\d+\.\d+\.\d+)/) {
        print "$1\n";
    }
}

This handles one IP per line. If you have more than one IPs per line, you need to use the /g option. man perlretut gives you a more detailed tutorial on regular expressions.

Creating a simple login form

edited @Asraful Haque answer with a bit of js to show and hide the box

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
    /* Basics */
    html, body {
        width: 100%;
        height: 100%;
        font-family: "Helvetica Neue", Helvetica, sans-serif;
        color: #444;
        -webkit-font-smoothing: antialiased;
        background: #f0f0f0;
    }
    #container {
        position: fixed;
        width: 340px;
        height: 280px;
        top: 50%;
        left: 50%;
        margin-top: -140px;
        margin-left: -170px;
        background: #fff;
        border-radius: 3px;
        border: 1px solid #ccc;
        box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
        display: none;
    }
    form {
        margin: 0 auto;
        margin-top: 20px;
    }
    label {
        color: #555;
        display: inline-block;
        margin-left: 18px;
        padding-top: 10px;
        font-size: 14px;
    }
    p a {
        font-size: 11px;
        color: #aaa;
        float: right;
        margin-top: -13px;
        margin-right: 20px;
     -webkit-transition: all .4s ease;
        -moz-transition: all .4s ease;
        transition: all .4s ease;
    }
    p a:hover {
        color: #555;
    }
    input {
        font-family: "Helvetica Neue", Helvetica, sans-serif;
        font-size: 12px;
        outline: none;
    }
    input[type=text],
    input[type=password] ,input[type=time]{
        color: #777;
        padding-left: 10px;
        margin: 10px;
        margin-top: 12px;
        margin-left: 18px;
        width: 290px;
        height: 35px;
        border: 1px solid #c7d0d2;
        border-radius: 2px;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
        -webkit-transition: all .4s ease;
        -moz-transition: all .4s ease;
        transition: all .4s ease;
        }
    input[type=text]:hover,
    input[type=password]:hover,input[type=time]:hover {
        border: 1px solid #b6bfc0;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
    }
    input[type=text]:focus,
    input[type=password]:focus,input[type=time]:focus {
        border: 1px solid #a8c9e4;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
    }
    #lower {
        background: #ecf2f5;
        width: 100%;
        height: 69px;
        margin-top: 20px;
          box-shadow: inset 0 1px 1px #fff;
        border-top: 1px solid #ccc;
        border-bottom-right-radius: 3px;
        border-bottom-left-radius: 3px;
    }
    input[type=checkbox] {
        margin-left: 20px;
        margin-top: 30px;
    }
    .check {
        margin-left: 3px;
        font-size: 11px;
        color: #444;
        text-shadow: 0 1px 0 #fff;
    }
    input[type=submit] {
        float: right;
        margin-right: 20px;
        margin-top: 20px;
        width: 80px;
        height: 30px;
        font-size: 14px;
        font-weight: bold;
        color: #fff;
        background-color: #acd6ef; /*IE fallback*/
        background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
        background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
        background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
        border-radius: 30px;
        border: 1px solid #66add6;
        box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
        cursor: pointer;
    }
    input[type=submit]:hover {
        background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
        background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
        background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
    }
    input[type=submit]:active {
        background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
        background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
        background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
    }
</style>
<script>
    function clicker () {
        var login = document.getElementById("container");
        login.style.display="block";
    }
</script>
</head>

<body>
    <a href="#" id="link" onClick="clicker();">login</a>
    <!-- Begin Page Content -->
    <div id="container">
        <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
                <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
                <input type="submit" value="Login">
            </div><!--/ lower-->
        </form>
    </div><!--/ container-->
    <!-- End Page Content -->
</body>
</html>

Can't get Python to import from a different folder

My preferred way is to have __init__.py on every directory that contains modules that get used by other modules, and in the entry point, override sys.path as below:

def get_path(ss):
  return os.path.join(os.path.dirname(__file__), ss)
sys.path += [
  get_path('Server'), 
  get_path('Models')
]

This makes the files in specified directories visible for import, and I can import user from Server.py.

Converting from byte to int in java

if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff

iOS: Multi-line UILabel in Auto Layout

I find you need the following:

  • A top constraint
  • A leading constraint (eg left side)
  • A trailing constraint (eg right side)
  • Set content hugging priority, horizontal to low, so it'll fill the given space if the text is short.
  • Set content compression resistance, horizontal to low, so it'll wrap instead of try to become wider.
  • Set the number of lines to 0.
  • Set the line break mode to word wrap.

Java 8 - Difference between Optional.flatMap and Optional.map

You can refer below link to understand in detail (best explanation which I could find):

https://www.programmergirl.com/java-8-map-flatmap-difference/

Both map and flatMap - accept Function. The return type of map() is a single value whereas flatMap is returning stream of values

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

Best way to encode text data for XML

SecurityElement.Escape

documented here

Display string as html in asp.net mvc view

I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"

The resolution was to put the variable in quotes in the value statement as follows:

<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
       onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">

What does "ulimit -s unlimited" do?

When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.

To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s. If we remove that limit via ulimit -s unlimited, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.

int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.

Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.

Impact on performace is minor but does exist. Using the time command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).

How to create a custom attribute in C#

The short answer is for creating an attribute in c# you only need to inherit it from Attribute class, Just this :)

But here I'm going to explain attributes in detail:

basically attributes are classes that we can use them for applying our logic to assemblies, classes, methods, properties, fields, ...

In .Net, Microsoft has provided some predefined Attributes like Obsolete or Validation Attributes like ( [Required], [StringLength(100)], [Range(0, 999.99)]), also we have kind of attributes like ActionFilters in asp.net that can be very useful for applying our desired logic to our codes (read this article about action filters if you are passionate to learn it)

one another point, you can apply a kind of configuration on your attribute via AttibuteUsage.

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]

When you decorate an attribute class with AttributeUsage you can tell to c# compiler where I'm going to use this attribute: I'm going to use this on classes, on assemblies on properties or on ... and my attribute is allowed to use several times on defined targets(classes, assemblies, properties,...) or not?!

After this definition about attributes I'm going to show you an example: Imagine we want to define a new lesson in university and we want to allow just admins and masters in our university to define a new Lesson, Ok?

namespace ConsoleApp1
{
    /// <summary>
    /// All Roles in our scenario
    /// </summary>
    public enum UniversityRoles
    {
        Admin,
        Master,
        Employee,
        Student
    }

    /// <summary>
    /// This attribute will check the Max Length of Properties/fields
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)]
    public class ValidRoleForAccess : Attribute
    {
        public ValidRoleForAccess(UniversityRoles role)
        {
            Role = role;
        }
        public UniversityRoles Role { get; private set; }

    }


    /// <summary>
    /// we suppose that just admins and masters can define new Lesson
    /// </summary>
    [ValidRoleForAccess(UniversityRoles.Admin)]
    [ValidRoleForAccess(UniversityRoles.Master)]
    public class Lesson
    {
        public Lesson(int id, string name, DateTime startTime, User owner)
        {
            var lessType = typeof(Lesson);
            var validRolesForAccesses = lessType.GetCustomAttributes<ValidRoleForAccess>();

            if (validRolesForAccesses.All(x => x.Role.ToString() != owner.GetType().Name))
            {
                throw new Exception("You are not Allowed to define a new lesson");
            }
            
            Id = id;
            Name = name;
            StartTime = startTime;
            Owner = owner;
        }
        public int Id { get; private set; }
        public string Name { get; private set; }
        public DateTime StartTime { get; private set; }

        /// <summary>
        /// Owner is some one who define the lesson in university website
        /// </summary>
        public User Owner { get; private set; }

    }

    public abstract class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
    }


    public class Master : User
    {
        public DateTime HireDate { get; set; }
        public Decimal Salary { get; set; }
        public string Department { get; set; }
    }

    public class Student : User
    {
        public float GPA { get; set; }
    }



    class Program
    {
        static void Main(string[] args)
        {

            #region  exampl1

            var master = new Master()
            {
                Name = "Hamid Hasani",
                Id = 1,
                DateOfBirth = new DateTime(1994, 8, 15),
                Department = "Computer Engineering",
                HireDate = new DateTime(2018, 1, 1),
                Salary = 10000
            };
            var math = new Lesson(1, "Math", DateTime.Today, master);

            #endregion

            #region exampl2
            var student = new Student()
            {
                Name = "Hamid Hasani",
                Id = 1,
                DateOfBirth = new DateTime(1994, 8, 15),
                GPA = 16
            };
            var literature = new Lesson(2, "literature", DateTime.Now.AddDays(7), student);
            #endregion

            ReadLine();
        }
    }


}

In the real world of programming maybe we don't use this approach for using attributes and I said this because of its educational point in using attributes

How can one display images side by side in a GitHub README.md?

The easiest way I can think of solving this is using the tables included in GitHub's flavored markdown.

To your specific example it would look something like this:

Solarized dark             |  Solarized Ocean
:-------------------------:|:-------------------------:
![](https://...Dark.png)  |  ![](https://...Ocean.png)

This creates a table with Solarized Dark and Ocean as headers and then contains the images in the first row. Obviously you would replace the ... with the real link. The :s are optional (They just center the content in the cells, which is kinda unnecessary in this case). Also you might want to downsize the images so they will display better side-by-side.

Run a mySQL query as a cron job?

It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

# crontab -e
00 * * * * /usr/local/bin/php /home/path/script.php

On my system, I don't even have to put the path to the php installation:

00 * * * * php /home/path/script.php

On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

SQL statement to select all rows from previous day

Another way to tell it "Yesterday"...

Select * from TABLE
where Day(DateField) = (Day(GetDate())-1)
and Month(DateField) = (Month(GetDate()))
and Year(DateField) = (Year(getdate()))

This conceivably won't work well on January 1, as well as the first day of every month. But on the fly it's effective.

How to open local files in Swagger-UI

If all you want is just too see the the swagger doc file (say swagger.json) in swagger UI, try open-swagger-ui (is essentially, open "in" swagger ui).

open-swagger-ui ./swagger.json --open

Maximum call stack size exceeded error

If you are working with google maps, then check if the lat lng are being passed into new google.maps.LatLng are of a proper format. In my case they were being passed as undefined.

How to store printStackTrace into a string

call:  getStackTraceAsString(sqlEx)

public String getStackTraceAsString(Exception exc)  
{  
String stackTrace = "*** Error in getStackTraceAsString()";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
    stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
    } 
catch( UnsupportedEncodingException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
ps.close();
try {
    baos.close();
    } 
catch( IOException ex )
    {
    Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
    }
return stackTrace;
}

What is the OAuth 2.0 Bearer Token exactly?

As I read your question, I have tried without success to search on the Internet how Bearer tokens are encrypted or signed. I guess bearer tokens are not hashed (maybe partially, but not completely) because in that case, it will not be possible to decrypt it and retrieve users properties from it.

But your question seems to be trying to find answers on Bearer token functionality:

Suppose I am implementing an authorization provider, can I supply any kind of string for the bearer token? Can it be a random string? Does it has to be a base64 encoding of some attributes? Should it be hashed?

So, I'll try to explain how Bearer tokens and Refresh tokens work:

When user requests to the server for a token sending user and password through SSL, the server returns two things: an Access token and a Refresh token.

An Access token is a Bearer token that you will have to add in all request headers to be authenticated as a concrete user.

Authorization: Bearer <access_token>

An Access token is an encrypted string with all User properties, Claims and Roles that you wish. (You can check that the size of a token increases if you add more roles or claims). Once the Resource Server receives an access token, it will be able to decrypt it and read these user properties. This way, the user will be validated and granted along with all the application.

Access tokens have a short expiration (ie. 30 minutes). If access tokens had a long expiration it would be a problem, because theoretically there is no possibility to revoke it. So imagine a user with a role="Admin" that changes to "User". If a user keeps the old token with role="Admin" he will be able to access till the token expiration with Admin rights. That's why access tokens have a short expiration.

But, one issue comes in mind. If an access token has short expiration, we have to send every short period the user and password. Is this secure? No, it isn't. We should avoid it. That's when Refresh tokens appear to solve this problem.

Refresh tokens are stored in DB and will have long expiration (example: 1 month).

A user can get a new Access token (when it expires, every 30 minutes for example) using a refresh token, that the user had received in the first request for a token. When an access token expires, the client must send a refresh token. If this refresh token exists in DB, the server will return to the client a new access token and another refresh token (and will replace the old refresh token by the new one).

In case a user Access token has been compromised, the refresh token of that user must be deleted from DB. This way the token will be valid only till the access token expires because when the hacker tries to get a new access token sending the refresh token, this action will be denied.

What is the optimal algorithm for the game 2048?

My attempt uses expectimax like other solutions above, but without bitboards. Nneonneo's solution can check 10millions of moves which is approximately a depth of 4 with 6 tiles left and 4 moves possible (2*6*4)4. In my case, this depth takes too long to explore, I adjust the depth of expectimax search according to the number of free tiles left:

depth = free > 7 ? 1 : (free > 4 ? 2 : 3)

The scores of the boards are computed with the weighted sum of the square of the number of free tiles and the dot product of the 2D grid with this:

[[10,8,7,6.5],
 [.5,.7,1,3],
 [-.5,-1.5,-1.8,-2],
 [-3.8,-3.7,-3.5,-3]]

which forces to organize tiles descendingly in a sort of snake from the top left tile.

code below or on github:

_x000D_
_x000D_
var n = 4,_x000D_
 M = new MatrixTransform(n);_x000D_
_x000D_
var ai = {weights: [1, 1], depth: 1}; // depth=1 by default, but we adjust it on every prediction according to the number of free tiles_x000D_
_x000D_
var snake= [[10,8,7,6.5],_x000D_
            [.5,.7,1,3],_x000D_
            [-.5,-1.5,-1.8,-2],_x000D_
            [-3.8,-3.7,-3.5,-3]]_x000D_
snake=snake.map(function(a){return a.map(Math.exp)})_x000D_
_x000D_
initialize(ai)_x000D_
_x000D_
function run(ai) {_x000D_
 var p;_x000D_
 while ((p = predict(ai)) != null) {_x000D_
  move(p, ai);_x000D_
 }_x000D_
 //console.log(ai.grid , maxValue(ai.grid))_x000D_
 ai.maxValue = maxValue(ai.grid)_x000D_
 console.log(ai)_x000D_
}_x000D_
_x000D_
function initialize(ai) {_x000D_
 ai.grid = [];_x000D_
 for (var i = 0; i < n; i++) {_x000D_
  ai.grid[i] = []_x000D_
  for (var j = 0; j < n; j++) {_x000D_
   ai.grid[i][j] = 0;_x000D_
  }_x000D_
 }_x000D_
 rand(ai.grid)_x000D_
 rand(ai.grid)_x000D_
 ai.steps = 0;_x000D_
}_x000D_
_x000D_
function move(p, ai) { //0:up, 1:right, 2:down, 3:left_x000D_
 var newgrid = mv(p, ai.grid);_x000D_
 if (!equal(newgrid, ai.grid)) {_x000D_
  //console.log(stats(newgrid, ai.grid))_x000D_
  ai.grid = newgrid;_x000D_
  try {_x000D_
   rand(ai.grid)_x000D_
   ai.steps++;_x000D_
  } catch (e) {_x000D_
   console.log('no room', e)_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function predict(ai) {_x000D_
 var free = freeCells(ai.grid);_x000D_
 ai.depth = free > 7 ? 1 : (free > 4 ? 2 : 3);_x000D_
 var root = {path: [],prob: 1,grid: ai.grid,children: []};_x000D_
 var x = expandMove(root, ai)_x000D_
 //console.log("number of leaves", x)_x000D_
 //console.log("number of leaves2", countLeaves(root))_x000D_
 if (!root.children.length) return null_x000D_
 var values = root.children.map(expectimax);_x000D_
 var mx = max(values);_x000D_
 return root.children[mx[1]].path[0]_x000D_
_x000D_
}_x000D_
_x000D_
function countLeaves(node) {_x000D_
 var x = 0;_x000D_
 if (!node.children.length) return 1;_x000D_
 for (var n of node.children)_x000D_
  x += countLeaves(n);_x000D_
 return x;_x000D_
}_x000D_
_x000D_
function expectimax(node) {_x000D_
 if (!node.children.length) {_x000D_
  return node.score_x000D_
 } else {_x000D_
  var values = node.children.map(expectimax);_x000D_
  if (node.prob) { //we are at a max node_x000D_
   return Math.max.apply(null, values)_x000D_
  } else { // we are at a random node_x000D_
   var avg = 0;_x000D_
   for (var i = 0; i < values.length; i++)_x000D_
    avg += node.children[i].prob * values[i]_x000D_
   return avg / (values.length / 2)_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function expandRandom(node, ai) {_x000D_
 var x = 0;_x000D_
 for (var i = 0; i < node.grid.length; i++)_x000D_
  for (var j = 0; j < node.grid.length; j++)_x000D_
   if (!node.grid[i][j]) {_x000D_
    var grid2 = M.copy(node.grid),_x000D_
     grid4 = M.copy(node.grid);_x000D_
    grid2[i][j] = 2;_x000D_
    grid4[i][j] = 4;_x000D_
    var child2 = {grid: grid2,prob: .9,path: node.path,children: []};_x000D_
    var child4 = {grid: grid4,prob: .1,path: node.path,children: []}_x000D_
    node.children.push(child2)_x000D_
    node.children.push(child4)_x000D_
    x += expandMove(child2, ai)_x000D_
    x += expandMove(child4, ai)_x000D_
   }_x000D_
 return x;_x000D_
}_x000D_
_x000D_
function expandMove(node, ai) { // node={grid,path,score}_x000D_
 var isLeaf = true,_x000D_
  x = 0;_x000D_
 if (node.path.length < ai.depth) {_x000D_
  for (var move of[0, 1, 2, 3]) {_x000D_
   var grid = mv(move, node.grid);_x000D_
   if (!equal(grid, node.grid)) {_x000D_
    isLeaf = false;_x000D_
    var child = {grid: grid,path: node.path.concat([move]),children: []}_x000D_
    node.children.push(child)_x000D_
    x += expandRandom(child, ai)_x000D_
   }_x000D_
  }_x000D_
 }_x000D_
 if (isLeaf) node.score = dot(ai.weights, stats(node.grid))_x000D_
 return isLeaf ? 1 : x;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
var cells = []_x000D_
var table = document.querySelector("table");_x000D_
for (var i = 0; i < n; i++) {_x000D_
 var tr = document.createElement("tr");_x000D_
 cells[i] = [];_x000D_
 for (var j = 0; j < n; j++) {_x000D_
  cells[i][j] = document.createElement("td");_x000D_
  tr.appendChild(cells[i][j])_x000D_
 }_x000D_
 table.appendChild(tr);_x000D_
}_x000D_
_x000D_
function updateUI(ai) {_x000D_
 cells.forEach(function(a, i) {_x000D_
  a.forEach(function(el, j) {_x000D_
   el.innerHTML = ai.grid[i][j] || ''_x000D_
  })_x000D_
 });_x000D_
}_x000D_
_x000D_
_x000D_
updateUI(ai);_x000D_
updateHint(predict(ai));_x000D_
_x000D_
function runAI() {_x000D_
 var p = predict(ai);_x000D_
 if (p != null && ai.running) {_x000D_
  move(p, ai);_x000D_
  updateUI(ai);_x000D_
  updateHint(p);_x000D_
  requestAnimationFrame(runAI);_x000D_
 }_x000D_
}_x000D_
runai.onclick = function() {_x000D_
 if (!ai.running) {_x000D_
  this.innerHTML = 'stop AI';_x000D_
  ai.running = true;_x000D_
  runAI();_x000D_
 } else {_x000D_
  this.innerHTML = 'run AI';_x000D_
  ai.running = false;_x000D_
  updateHint(predict(ai));_x000D_
 }_x000D_
}_x000D_
_x000D_
_x000D_
function updateHint(dir) {_x000D_
 hintvalue.innerHTML = ['?', '?', '?', '?'][dir] || '';_x000D_
}_x000D_
_x000D_
document.addEventListener("keydown", function(event) {_x000D_
 if (!event.target.matches('.r *')) return;_x000D_
 event.preventDefault(); // avoid scrolling_x000D_
 if (event.which in map) {_x000D_
  move(map[event.which], ai)_x000D_
  console.log(stats(ai.grid))_x000D_
  updateUI(ai);_x000D_
  updateHint(predict(ai));_x000D_
 }_x000D_
})_x000D_
var map = {_x000D_
 38: 0, // Up_x000D_
 39: 1, // Right_x000D_
 40: 2, // Down_x000D_
 37: 3, // Left_x000D_
};_x000D_
init.onclick = function() {_x000D_
 initialize(ai);_x000D_
 updateUI(ai);_x000D_
 updateHint(predict(ai));_x000D_
}_x000D_
_x000D_
_x000D_
function stats(grid, previousGrid) {_x000D_
_x000D_
 var free = freeCells(grid);_x000D_
_x000D_
 var c = dot2(grid, snake);_x000D_
_x000D_
 return [c, free * free];_x000D_
}_x000D_
_x000D_
function dist2(a, b) { //squared 2D distance_x000D_
 return Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2)_x000D_
}_x000D_
_x000D_
function dot(a, b) {_x000D_
 var r = 0;_x000D_
 for (var i = 0; i < a.length; i++)_x000D_
  r += a[i] * b[i];_x000D_
 return r_x000D_
}_x000D_
_x000D_
function dot2(a, b) {_x000D_
 var r = 0;_x000D_
 for (var i = 0; i < a.length; i++)_x000D_
  for (var j = 0; j < a[0].length; j++)_x000D_
   r += a[i][j] * b[i][j]_x000D_
 return r;_x000D_
}_x000D_
_x000D_
function product(a) {_x000D_
 return a.reduce(function(v, x) {_x000D_
  return v * x_x000D_
 }, 1)_x000D_
}_x000D_
_x000D_
function maxValue(grid) {_x000D_
 return Math.max.apply(null, grid.map(function(a) {_x000D_
  return Math.max.apply(null, a)_x000D_
 }));_x000D_
}_x000D_
_x000D_
function freeCells(grid) {_x000D_
 return grid.reduce(function(v, a) {_x000D_
  return v + a.reduce(function(t, x) {_x000D_
   return t + (x == 0)_x000D_
  }, 0)_x000D_
 }, 0)_x000D_
}_x000D_
_x000D_
function max(arr) { // return [value, index] of the max_x000D_
 var m = [-Infinity, null];_x000D_
 for (var i = 0; i < arr.length; i++) {_x000D_
  if (arr[i] > m[0]) m = [arr[i], i];_x000D_
 }_x000D_
 return m_x000D_
}_x000D_
_x000D_
function min(arr) { // return [value, index] of the min_x000D_
 var m = [Infinity, null];_x000D_
 for (var i = 0; i < arr.length; i++) {_x000D_
  if (arr[i] < m[0]) m = [arr[i], i];_x000D_
 }_x000D_
 return m_x000D_
}_x000D_
_x000D_
function maxScore(nodes) {_x000D_
 var min = {_x000D_
  score: -Infinity,_x000D_
  path: []_x000D_
 };_x000D_
 for (var node of nodes) {_x000D_
  if (node.score > min.score) min = node;_x000D_
 }_x000D_
 return min;_x000D_
}_x000D_
_x000D_
_x000D_
function mv(k, grid) {_x000D_
 var tgrid = M.itransform(k, grid);_x000D_
 for (var i = 0; i < tgrid.length; i++) {_x000D_
  var a = tgrid[i];_x000D_
  for (var j = 0, jj = 0; j < a.length; j++)_x000D_
   if (a[j]) a[jj++] = (j < a.length - 1 && a[j] == a[j + 1]) ? 2 * a[j++] : a[j]_x000D_
  for (; jj < a.length; jj++)_x000D_
   a[jj] = 0;_x000D_
 }_x000D_
 return M.transform(k, tgrid);_x000D_
}_x000D_
_x000D_
function rand(grid) {_x000D_
 var r = Math.floor(Math.random() * freeCells(grid)),_x000D_
  _r = 0;_x000D_
 for (var i = 0; i < grid.length; i++) {_x000D_
  for (var j = 0; j < grid.length; j++) {_x000D_
   if (!grid[i][j]) {_x000D_
    if (_r == r) {_x000D_
     grid[i][j] = Math.random() < .9 ? 2 : 4_x000D_
    }_x000D_
    _r++;_x000D_
   }_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function equal(grid1, grid2) {_x000D_
 for (var i = 0; i < grid1.length; i++)_x000D_
  for (var j = 0; j < grid1.length; j++)_x000D_
   if (grid1[i][j] != grid2[i][j]) return false;_x000D_
 return true;_x000D_
}_x000D_
_x000D_
function conv44valid(a, b) {_x000D_
 var r = 0;_x000D_
 for (var i = 0; i < 4; i++)_x000D_
  for (var j = 0; j < 4; j++)_x000D_
   r += a[i][j] * b[3 - i][3 - j]_x000D_
 return r_x000D_
}_x000D_
_x000D_
function MatrixTransform(n) {_x000D_
 var g = [],_x000D_
  ig = [];_x000D_
 for (var i = 0; i < n; i++) {_x000D_
  g[i] = [];_x000D_
  ig[i] = [];_x000D_
  for (var j = 0; j < n; j++) {_x000D_
   g[i][j] = [[j, i],[i, n-1-j],[j, n-1-i],[i, j]]; // transformation matrix in the 4 directions g[i][j] = [up, right, down, left]_x000D_
   ig[i][j] = [[j, i],[i, n-1-j],[n-1-j, i],[i, j]]; // the inverse tranformations_x000D_
  }_x000D_
 }_x000D_
 this.transform = function(k, grid) {_x000D_
  return this.transformer(k, grid, g)_x000D_
 }_x000D_
 this.itransform = function(k, grid) { // inverse transform_x000D_
  return this.transformer(k, grid, ig)_x000D_
 }_x000D_
 this.transformer = function(k, grid, mat) {_x000D_
  var newgrid = [];_x000D_
  for (var i = 0; i < grid.length; i++) {_x000D_
   newgrid[i] = [];_x000D_
   for (var j = 0; j < grid.length; j++)_x000D_
    newgrid[i][j] = grid[mat[i][j][k][0]][mat[i][j][k][1]];_x000D_
  }_x000D_
  return newgrid;_x000D_
 }_x000D_
 this.copy = function(grid) {_x000D_
  return this.transform(3, grid)_x000D_
 }_x000D_
}
_x000D_
body {_x000D_
 font-family: Arial;_x000D_
}_x000D_
table, th, td {_x000D_
 border: 1px solid black;_x000D_
 margin: 0 auto;_x000D_
 border-collapse: collapse;_x000D_
}_x000D_
td {_x000D_
 width: 35px;_x000D_
 height: 35px;_x000D_
 text-align: center;_x000D_
}_x000D_
button {_x000D_
 margin: 2px;_x000D_
 padding: 3px 15px;_x000D_
 color: rgba(0,0,0,.9);_x000D_
}_x000D_
.r {_x000D_
 display: flex;_x000D_
 align-items: center;_x000D_
 justify-content: center;_x000D_
 margin: .2em;_x000D_
 position: relative;_x000D_
}_x000D_
#hintvalue {_x000D_
 font-size: 1.4em;_x000D_
 padding: 2px 8px;_x000D_
 display: inline-flex;_x000D_
 justify-content: center;_x000D_
 width: 30px;_x000D_
}
_x000D_
<table title="press arrow keys"></table>_x000D_
<div class="r">_x000D_
    <button id=init>init</button>_x000D_
    <button id=runai>run AI</button>_x000D_
    <span id="hintvalue" title="Best predicted move to do, use your arrow keys" tabindex="-1"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if array element exists or not in javascript?

If elements of array are also simple objects or arrays, you can use some function:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});

Java: Integer equals vs. ==

Besides these given great answers, What I have learned is that:

NEVER compare objects with == unless you intend to be comparing them by their references.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

How to comment out a block of Python code in Vim

I usually sweep out a visual block (<C-V>), then search and replace the first character with:

:'<,'>s/^/#

(Entering command mode with a visual block selected automatically places '<,'> on the command line) I can then uncomment the block by sweeping out the same visual block and:

:'<,'>s/^#//

ip address validation in python using regex

The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:

[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Example:

your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4

Output:

>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>

Calculate age given the birth date in the format YYYYMMDD

I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.

function getAge(birth) {
   var today = new Date();
   var curr_date = today.getDate();
   var curr_month = today.getMonth() + 1;
   var curr_year = today.getFullYear();

   var pieces = birth.split('/');
   var birth_date = pieces[0];
   var birth_month = pieces[1];
   var birth_year = pieces[2];

   if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
   if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
   if (curr_month > birth_month) return parseInt(curr_year-birth_year);
   if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}

var age = getAge('18/01/2011');
alert(age);

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Query scopes may help you to let your code more readable.

http://laravel.com/docs/eloquent#query-scopes

Updating this answer with some example:

In your model, create scopes methods like this:

public function scopeActive($query)
{
    return $query->where('active', '=', 1);
}

public function scopeThat($query)
{
    return $query->where('that', '=', 1);
}

Then, you can call this scopes while building your query:

$users = User::active()->that()->get();

How to get an element by its href in jquery?

var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

GenyMotion Unable to start the Genymotion virtual device

For VIrtual Box 5.x - the settings from above comments are set automatically

Now for the error:

1.Make sure that you have enough Processor(s) and Base Memory - so the PC can support VM configuration(I use 1 procesor and 1024MB for all VM's)

2.Delete any unused VM from Genymotion and Oracle VirtualBox Manager - seems to reserve their configuration, though you use it or not(that specific VM)

How to change workspace and build record Root Directory on Jenkins?

You can modify the path on the config.xml file in the default directory

<projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
<workspaceDir>D:/Workspace/${ITEM_FULL_NAME}</workspaceDir>
<buildsDir>D:/Logs/${ITEM_ROOTDIR}/Build</buildsDir>

HTML5 and frameborder

HTML 5 doesn't support attributes such as frameborder, scrolling, marginwidth, and marginheight (which were supported in HTML 4.01). Instead, the HTML 5 specification has introduced the seamless attribute. The seamless attribute allows the inline frame to appear as though it is being rendered as part of the containing document. For example, borders and scrollbars will not appear.

According to MDN

frameborder Obsolete since HTML5

The value 1 (the default) draws a border around this frame. The value 0 removes the border around this frame, but you should instead use the CSS property border to control borders.

Like the quote above says, you should remove the border with CSS;
either inline (style="border: none;") or in your stylesheet (iframe { border: none; }).

That being said, there doesn't seem to be a single iframe provider that doesn't use frameborder="0". Even YouTube still uses the attribute and doesn't even provide a style attribute to make iframes backwards compatible for when frameborder isn't supported anymore. It's safe to say that the attribute isn't going anywhere soon. This leaves you with 3 options:

  1. Keep using frameborder, just to be sure it works (for now)
  2. Use CSS, to do the "right" thing
  3. Use both. Although this doesn't resolve the incompatibility problem (just like option 1), it does and will work in every browser that has been and will be

As for the previous state of this decade-old answer:

The seamless attribute has been supported for such a short time (or not at all by some browsers), that MDN doesn't even list it as a deprecated feature. Don't use it and don't get confused by the comments below.

INSERT INTO from two different server database

You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.

I found this solution when I faced the same situation. Hope this helps you too.

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell

Cannot open new Jupyter Notebook [Permission Denied]

You don't have to install or uninstall anything. if you are using python 2 use pip to install and upgrade. But if you want to use python3 then follow the steps below:

sudo apt-get install python3-pip python3-dev

then in terminal use this

pip3 install -U jupyter

final step is to launch jupyter notebook so,in terminal just type

jupyter notebook

all the issues or problems of premissions etc will be resolved.

Set multiple system properties Java command line

Instead of passing the properties as an argument, you may use a .properties for storing them.

How do I improve ASP.NET MVC application performance?

Following are things to do

  1. Kernel mode Cache
  2. Pipeline mode
  3. Remove unused modules
  4. runAllManagedModulesForAllRequests
  5. Don't write in wwwroot
  6. Remove unused view engines and language

Displaying unicode symbols in HTML

I think this is a file problem, you simple saved your file in 1-byte encoding like latin-1. Google up your editor and how to set files to utf-8.

I wonder why there are editors that don't default to utf-8.

Modal width (increase)

The following solution will work for Bootstrap 4.

.modal .modal-dialog {
  max-width: 850px;
}

Preloading CSS Images

For preloading background images set with CSS, the most efficient answer i came up with was a modified version of some code I found that did not work:

$(':hidden').each(function() {
  var backgroundImage = $(this).css("background-image");
  if (backgroundImage != 'none') {
    tempImage = new Image();
    tempImage.src = backgroundImage;
  }
});

The massive benefit of this is that you don't need to update it when you bring in new background images in the future, it will find the new ones and preload them!

Count number of rows matching a criteria

  1. mydata$sCode is a vector, it's why nrow output is NULL.
  2. mydata[mydata$sCode == 'CA',] returns data.frame where sCode == 'CA'. sCode includes character. That's why sum gives you the error.
  3. subset(mydata, sCode='CA', select=c(sCode)), you should use sCode=='CA' instead sCode='CA'. Then subset returns you vector where sCode equals CA, so you should use

    length(subset(na.omit(mydata), sCode='CA', select=c(sCode)))

Or you can try this: sum(na.omit(mydata$sCode) == "CA")

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

LinearLayout means you can align views one by one (vertically/ horizontally).

RelativeLayout means based on relation of views from its parents and other views.

ConstraintLayout is similar to a RelativeLayout in that it uses relations to position and size widgets, but has additional flexibility and is easier to use in the Layout Editor.

WebView to load html, static or dynamic pages.

FrameLayout to load child one above another, like cards inside a frame, we can place one above another or anywhere inside the frame.

deprecated - AbsoluteLayout means you have to give exact position where the view should be.

For more information, please check this address https://developer.android.com/guide/topics/ui/declaring-layout#CommonLayouts

Convert timestamp long to normal date format

I tried this and worked for me.

Date = (long)(DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds

How to increment a variable on a for loop in jinja template?

As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

You can defeat this behavior by using an object rather than a scalar for 'count':

{% set count = [1] %}

You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}

LINQ equivalent of foreach for IEnumerable<T>

There is an experimental release by Microsoft of Interactive Extensions to LINQ (also on NuGet, see RxTeams's profile for more links). The Channel 9 video explains it well.

Its docs are only provided in XML format. I have run this documentation in Sandcastle to allow it to be in a more readable format. Unzip the docs archive and look for index.html.

Among many other goodies, it provides the expected ForEach implementation. It allows you to write code like this:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };

numbers.ForEach(x => Console.WriteLine(x*x));

Resource from src/main/resources not found after building with maven

The resources you put in src/main/resources will be copied during the build process to target/classes which can be accessed using:

...this.getClass().getResourceAsStream("/config.txt");

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

I faced a similar issue on Docker for Ubuntu. It's a DNS issue. You will have to add Google Public DNS Settings into your network. Instruction for adding those settings is OS dependant. In my case, I was using Ubuntu so I added via network manager. Visit this site for more info.

enter image description here

ASP.NET Custom Validator Client side & Server Side validation not firing

Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via

 Page.Validate({Insert validation group name here});

Any good, visual HTML5 Editor or IDE?

Topstyle 4 is the only one I've com e across with HTML5 (and CSS3) support. Its early stages but it works enough for the most part.

Print to standard printer from Python?

Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.

You need to detect the OS your program is running on, then:

For Linux -

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)

For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html

More resources:

Print PDF document with python's win32print module?

How do I print to the OS's default printer in Python 3 (cross platform)?

alternatives to REPLACE on a text or ntext datatype

Assuming SQL Server 2000, the following StackOverflow question should address your problem.

If using SQL Server 2005/2008, you can use the following code (taken from here):

select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable

javascript windows alert with redirect function

You could do this:

echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";

Fatal error: Maximum execution time of 30 seconds exceeded

To extend your max_execution_time you can use either ini_set or set_time_limit.

// Set maximum execution time to 10 seconds this way
ini_set('max_execution_time', 10);
// or this way
set_time_limit(10);

!! But be aware that, both functions restarts also counting of time script has already taken to execute

sleep(2);
ini_set('max_execution_time', 5);

register_shutdown_function(function(){
    var_dump(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']);
});

for(;;);

//
// var_dump outputs float(7.1981489658356)
//

so if you want to set exact maximum amount of time script can run, your command must be very first.

Differences between those two functions are

  • set_time_limit does not return info whether it was successful but it will throw a warning on error.
  • ini_set returns old value on success, or false on failure without any warning/error

How can I apply a function to every row/column of a matrix in MATLAB?

I can't comment on how efficient this is, but here's a solution:

applyToGivenRow = @(func, matrix) @(row) func(matrix(row, :))
applyToRows = @(func, matrix) arrayfun(applyToGivenRow(func, matrix), 1:size(matrix,1))'

% Example
myMx = [1 2 3; 4 5 6; 7 8 9];
myFunc = @sum;

applyToRows(myFunc, myMx)

Cross-Origin Request Blocked

@Egidius, when creating an XMLHttpRequest, you should use

var xhr = new XMLHttpRequest({mozSystem: true});

What is mozSystem?

mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Changes to your Manifest

On your manifest, do not forget to include this line on your permissions:

"permissions": {
       "systemXHR" : {},
}

How do I get Flask to run on port 80?

you can easily disable any process running on port 80 and then run this command

flask run --host 0.0.0.0 --port 80

or if u prefer running it within the .py file

if __name__ == "__main__":
    app.run(host=0.0.0.0, port=80)

uint8_t vs unsigned char

As you said, "almost every system".

char is probably one of the less likely to change, but once you start using uint16_t and friends, using uint8_t blends better, and may even be part of a coding standard.

What does ECU units, CPU core and memory mean when I launch a instance

Responding to the Forum Thread for the sake of completeness. Amazon has stopped using the the ECU - Elastic Compute Units and moved on to a vCPU based measure. So ignoring the ECU you pretty much can start comparing the EC2 Instances' sizes as CPU (Clock Speed), number of CPUs, RAM, storage etc.

Every instance families' instance configurations are published as number of vCPU and what is the physical processor. Detailed info and screenshot obstained from here http://aws.amazon.com/ec2/instance-types/#instance-type-matrix

vCPU Count, difference in Clock Speed and Physical Processor

Display Parameter(Multi-value) in Report

I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:

Public Function ShowParmValues(ByVal parm as Parameter) as string
   Dim s as String 

      For i as integer = 0 to parm.Count-1
         s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
      Next
  Return s
End Function  

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

Making an API call in Python with an API that requires a bearer token

It just means it expects that as a key in your header data

import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}

print(requests.post(endpoint, data=data, headers=headers).json())

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

Carousel with Thumbnails in Bootstrap 3.0

Bootstrap 4 (update 2019)

A multi-item carousel can be accomplished in several ways as explained here. Another option is to use separate thumbnails to navigate the carousel slides.

Bootstrap 3 (original answer)

This can be done using the grid inside each carousel item.

       <div id="myCarousel" class="carousel slide">
                <div class="carousel-inner">
                    <div class="item active">
                        <div class="row">
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                        </div>
                        <!--/row-->
                    </div>
                    ...add more item(s)
                 </div>
        </div>

Demo example thumbnail slider using the carousel:
http://www.bootply.com/81478

Another example with carousel indicators as thumbnails: http://www.bootply.com/79859

How to remove the last element added into the List?

The direct answer to this question is:

if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
    rows.RemoveAt(rows.Count - 1);
}

However... in the specific case of this question, it makes more sense not to add the row in the first place:

Row row = new Row();
//...      

if (!row.cell[0].Equals("Something"))
{
    rows.Add(row);
}

TBH, I'd go a step further by testing "Something" against user."", and not even instantiating a Row unless the condition is satisfied, but seeing as user."" won't compile, I'll leave that as an exercise for the reader.

Should a RESTful 'PUT' operation return something

I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)

If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.

How do I fix PyDev "Undefined variable from import" errors?

For code in your project, the only way is adding a declaration saying that you expected that -- possibly protected by an if False so that it doesn't execute (the static code-analysis only sees what you see, not runtime info -- if you opened that module yourself, you'd have no indication that main was expected).

To overcome this there are some choices:

  1. If it is some external module, it's possible to add it to the forced builtins so that PyDev spawns a shell for it to obtain runtime information (see http://pydev.org/manual_101_interpreter.html for details) -- i.e.: mostly, PyDev will import the module in a shell and do a dir(module) and dir on the classes found in the module to present completions and make code analysis.

  2. You can use Ctrl+1 (Cmd+1 for Mac) in a line with an error and PyDev will present you an option to add a comment to ignore that error.

  3. It's possible to create a stub module and add it to the predefined completions (http://pydev.org/manual_101_interpreter.html also has details on that).

Import JSON file in React

Simplest approach is following

// Save this as someJson.js
const someJson = {
  name: 'Name',
  age: 20
}

export default someJson

then

import someJson from './someJson'

How can I backup a Docker-container with its data-volumes?

If you want a complete backup, you will need to perform a few steps:

  1. Commit the container to an image
  2. Save the image
  3. Backup the container's volume by creating a tar file of the volume's mount point in the container.
  4. Repeat steps 1-3 for the database container as well.

Note that doing just a Docker commit of the container to an image does NOT include volumes attached to the container (ref: Docker commit documentation).

"The commit operation will not include any data contained in volumes mounted inside the container."

Command to run a .bat file

"F:\- Big Packets -\kitterengine\Common\Template.bat" maybe prefaced with call (see call /?). Or Cd /d "F:\- Big Packets -\kitterengine\Common\" & Template.bat.


CMD Cheat Sheet

  • Cmd.exe

  • Getting Help

  • Punctuation

  • Naming Files

  • Starting Programs

  • Keys

CMD.exe

First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.

For help on starting CMD type cmd /?. You must start it with either the /k or /c switch unless you just want to type in it.

Getting Help

For general help. Type Help in the command prompt. For each command listed type help <command> (eg help dir) or <command> /? (eg dir /?).

Some commands have sub commands. For example schtasks /create /?.

The NET command's help is unusual. Typing net use /? is brief help. Type net help use for full help. The same applies at the root - net /? is also brief help, use net help.

References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.

WMIC is a multipurpose command. Type wmic /?.


Punctuation

&    seperates commands on a line.

&&    executes this command only if previous command's errorlevel is 0.

||    (not used above) executes this command only if previous command's 
errorlevel is NOT 0

>    output to a file

>>    append output to a file

<    input from a file

2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)

2>&1 Redirects command error output to the same location as command output. 

|    output of one command into the input of another command

^    escapes any of the above, including itself, if needed to be passed 
to a program

"    parameters with spaces must be enclosed in quotes

+ used with copy to concatenate files. E.G. copy file1+file2 newfile

, used with copy to indicate missing parameters. This updates the files 
modified date. E.G. copy /b file1,,

%variablename% a inbuilt or user set environmental variable

!variablename! a user set environmental variable expanded at execution 
time, turned with SelLocal EnableDelayedExpansion command

%<number> (%1) the nth command line parameter passed to a batch file. %0 
is the batchfile's name.

%* (%*) the entire command line.

%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor (from set /?).

%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. 
Single % sign at command prompt and double % sign in a batch file.

\\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.

: (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.

. (win.ini) the LAST dot in a file path separates the name from extension

. (dir .\*.txt) the current directory

.. (cd ..) the parent directory


\\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off. 

Naming Files

< > : " / \ | Reserved characters. May not be used in filenames.



Reserved names. These refer to devices eg, 

copy filename con 

which copies a file to the console window.

CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, 

COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, 

LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9

CONIN$, CONOUT$, CONERR$

--------------------------------

Maximum path length              260 characters
Maximum path length (\\?\)      32,767 characters (approx - some rare characters use 2 characters of storage)
Maximum filename length        255 characters

Starting a Program

See start /? and call /? for help on all three ways.

There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.

If a full path isn't given then Windows looks in

  1. The directory from which the application loaded.

  2. The current directory for the parent process.

  3. Windows NT/2000/XP: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.

  4. Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.

  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.

  6. The directories that are listed in the PATH environment variable.

Specify a program name

This is the standard way to start a program.

c:\windows\notepad.exe

In a batch file the batch will wait for the program to exit. When typed the command prompt does not wait for graphical programs to exit.

If the program is a batch file control is transferred and the rest of the calling batch file is not executed.

Use Start command

Start starts programs in non standard ways.

start "" c:\windows\notepad.exe

Start starts a program and does not wait. Console programs start in a new window. Using the /b switch forces console programs into the same window, which negates the main purpose of Start.

Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try

start shell:cache

Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths can also be typed without specifying a full path.

Also note the first set of quotes, if any, MUST be the window title.

Use Call command

Call is used to start batch files and wait for them to exit and continue the current batch file.

Other Filenames

Typing a non program filename is the same as double clicking the file.


Keys

Ctrl + C exits a program without exiting the console window.

For other editing keys type Doskey /?.

  • ? and ? recall commands

  • ESC clears command line

  • F7 displays command history

  • ALT+F7 clears command history

  • F8 searches command history

  • F9 selects a command by number

  • ALT+F10 clears macro definitions

Also not listed

  • Ctrl + ?or? Moves a word at a time

  • Ctrl + Backspace Deletes the previous word

  • Home Beginning of line

  • End End of line

  • Ctrl + End Deletes to end of line

REST API Best practices: Where to put parameters?

"Pack" and POST your data against the "context" that universe-resource-locator provides, which means #1 for the sake of the locator.

Mind the limitations with #2. I prefer POSTs to #1.

note: limitations are discussed for

POST in Is there a max size for POST parameter content?

GET in Is there a limit to the length of a GET request? and Max size of URL parameters in _GET

p.s. these limits are based on the client capabilities (browser) and server(configuration).

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

How do you append to an already existing string?

thank-you Ignacio Vazquez-Abrams

i adapted slightly for better ease of use :)

placed at top of script

NEW_LINE=$'\n'

then to use easily with other variables

variable1="test1"
variable2="test2"

DESCRIPTION="$variable1$NEW_LINE$variable2$NEW_LINE"

OR to append thank-you William Pursell

DESCRIPTION="$variable1$NEW_LINE"
DESCRIPTION+="$variable2$NEW_LINE"

echo "$DESCRIPTION"

Maven : error in opening zip file when running maven

This error occurs because of some file corruption. But we don't need to delete whole .m2 folder. Instead find which jar files get corrupted by looking at the error message in the console. And delete only the folders which contains those jar files.

Like in the question :

  1. C:\Users\suresh\.m2\repository\org\jdom\jdom\
  2. C:\Users\suresh\.m2\repository\javax\servlet\servlet-api\
  3. C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-rt-bindings-http
  4. C:\Users\suresh\.m2\repository\org\codehaus\jra\jra
  5. C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-api
  6. C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-common-utilities

Delete these folders. Then run.

mvn clean install -U

How to set my default shell on Mac?

You can use chsh to change a user's shell.

Run the following code, for instance, to change your shell to Zsh

chsh -s /bin/zsh

As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells.

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

jQuery ajax success error

You did not provide your validate.php code so I'm confused. You have to pass the data in JSON Format when when mail is success. You can use json_encode(); PHP function for that.

Add json_encdoe in validate.php in last

mail($to, $subject, $message, $headers); 
echo json_encode(array('success'=>'true'));

JS Code

success: function(data){ 
     if(data.success == true){ 
       alert('success'); 
    } 

Hope it works

How to get pandas.DataFrame columns containing specific dtype

There's a new feature in 0.14.1, select_dtypes to select columns by dtype, by providing a list of dtypes to include or exclude.

For example:

df = pd.DataFrame({'a': np.random.randn(1000),
                   'b': range(1000),
                   'c': ['a'] * 1000,
                   'd': pd.date_range('2000-1-1', periods=1000)})


df.select_dtypes(['float64','int64'])

Out[129]: 
            a    b
0    0.153070    0
1    0.887256    1
2   -1.456037    2
3   -1.147014    3
...

Installing jQuery?

There is no installation required. Just add jQuery to your application folder and give a reference to the js file.

<script type="text/javascript" src="jQuery.js"></script>

if jQuery is in the same folder of your referenced file.

Which programming languages can be used to develop in Android?

Java and C:

  • C used for low level functionalities and device connectivities
  • Java used for Framework and Application Level

You may find more information in Android developers site.

Filtering lists using LINQ

I would just use the FindAll method on the List class. i.e.:

List<Person> filteredResults = 
    people.FindAll(p => return !exclusions.Contains(p));

Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Gradle project refresh failed after Android Studio update

This might be too late to answer. But this may help someone.

In my case there was problem of JDK path.

I just set proper JDK path for Android Studio 2.1

File -> Project Structure -> From Left Side Panel "SDK Location" -> JDK Location -> Click to select JDK Path

Truncate Decimal number not Round Off

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.

Delete ActionLink with confirm dialog

Any click event before for update /edit/delete records message box alerts the user and if "Ok" proceed for the action else "cancel" remain unchanged. For this code no need to right separate java script code. it works for me

<a asp-action="Delete" asp-route-ID="@Item.ArtistID" onclick = "return confirm('Are you sure you wish to remove this Artist?');">Delete</a>

HTML input fields does not get focus when clicked

This will also happen anytime a div ends up positioned over controls in another div; like using bootstrap for layout, and having a "col-lg-4" followed by a "col-lg=8" misspelling... the right orphaned/misnamed div covers the left, and captures the mouse events. Easy to blow by that misspelling, - and = next to each other on keyboard. So, pays to examine with inspector and look for 'surprises' to uncover these wild divs.

Is there an unseen window covering the controls and blocking events, and how can that happen? Turns out, fatfingering = for - with bootstrap classnames is one way...

How to increase the Java stack size?

It is hard to give a sensible solution since you are keen to avoid all sane approaches. Refactoring one line of code is the senible solution.

Note: Using -Xss sets the stack size of every thread and is a very bad idea.

Another approach is byte code manipulation to change the code as follows;

public static long fact(int n) { 
    return n < 2 ? n : n > 127 ? 0 : n * fact(n - 1); 
}

given every answer for n > 127 is 0. This avoid changing the source code.