Programs & Examples On #Multiple schema

How to link to apps on the app store

If you have the app store id you are best off using it. Especially if you in the future might change the name of the application.

http://itunes.apple.com/app/id378458261

If you don't have tha app store id you can create an url based on this documentation https://developer.apple.com/library/ios/qa/qa1633/_index.html

+ (NSURL *)appStoreURL
{
    static NSURL *appStoreURL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        appStoreURL = [self appStoreURLFromBundleName:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]];
    });
    return appStoreURL;
}

+ (NSURL *)appStoreURLFromBundleName:(NSString *)bundleName
{
    NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.com/app/%@", [self sanitizeAppStoreResourceSpecifier:bundleName]]];
    return appStoreURL;
}

+ (NSString *)sanitizeAppStoreResourceSpecifier:(NSString *)resourceSpecifier
{
    /*
     https://developer.apple.com/library/ios/qa/qa1633/_index.html
     To create an App Store Short Link, apply the following rules to your company or app name:

     Remove all whitespace
     Convert all characters to lower-case
     Remove all copyright (©), trademark (™) and registered mark (®) symbols
     Replace ampersands ("&") with "and"
     Remove most punctuation (See Listing 2 for the set)
     Replace accented and other "decorated" characters (ü, å, etc.) with their elemental character (u, a, etc.)
     Leave all other characters as-is.
     */
    resourceSpecifier = [resourceSpecifier stringByReplacingOccurrencesOfString:@"&" withString:@"and"];
    resourceSpecifier = [[NSString alloc] initWithData:[resourceSpecifier dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding];
    resourceSpecifier = [resourceSpecifier stringByReplacingOccurrencesOfString:@"[!¡\"#$%'()*+,-./:;<=>¿?@\\[\\]\\^_`{|}~\\s\\t\\n]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, resourceSpecifier.length)];
    resourceSpecifier = [resourceSpecifier lowercaseString];
    return resourceSpecifier;
}

Passes this test

- (void)testAppStoreURLFromBundleName
{
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"Nuclear™"].absoluteString, @"itms-apps://itunes.com/app/nuclear", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"Magazine+"].absoluteString, @"itms-apps://itunes.com/app/magazine", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"Karl & CO"].absoluteString, @"itms-apps://itunes.com/app/karlandco", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"[Fluppy fuck]"].absoluteString, @"itms-apps://itunes.com/app/fluppyfuck", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"Pollos Hérmanos"].absoluteString, @"itms-apps://itunes.com/app/polloshermanos", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"Niños and niñas"].absoluteString, @"itms-apps://itunes.com/app/ninosandninas", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"Trond, MobizMag"].absoluteString, @"itms-apps://itunes.com/app/trondmobizmag", nil);
    STAssertEqualObjects([AGApplicationHelper appStoreURLFromBundleName:@"!__SPECIAL-PLIZES__!"].absoluteString, @"itms-apps://itunes.com/app/specialplizes", nil);
}

Angular routerLink does not navigate to the corresponding component

don't forget this to add this below in your template:

<router-outlet></router-outlet>

.NET - Get protocol, host, and port

Very similar to Holger's answer. If you need to grab the URL can do something like:

Uri uri = Context.Request.Url;         
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number

The Uri class provides a whole range of methods, many which I have not listed.

In my instance, I needed to grab LocalHost along with the Port Number, so this is what I did:

var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; 

Which successfully grabbed: http://localhost:12345

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

Remove leading or trailing spaces in an entire column of data

Without using a formula you can do this with 'Text to columns'.

  • Select the column that has the trailing spaces in the cells.
  • Click 'Text to columns' from the 'Data' tab, then choose option 'Fixed width'.
  • Set a break line so the longest text will fit. If your largest cell has 100 characters you can set the breakline on 200 or whatever you want.
  • Finish the operation.
  • You can now delete the new column Excel has created.

The 'side-effect' is that Excel has removed all trailing spaces in the original column.

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

SQLite Query in Android to count rows

@scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:

Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();

I also like @Dre's answer, with the parameterized query.

PHP mySQL - Insert new record into table with auto-increment on primary key

$query = "INSERT INTO myTable VALUES (NULL,'Fname', 'Lname', 'Website')";

Just leaving the value of the AI primary key NULL will assign an auto incremented value.

Why doesn't [01-12] range work as expected?

The []s in a regex denote a character class. If no ranges are specified, it implicitly ors every character within it together. Thus, [abcde] is the same as (a|b|c|d|e), except that it doesn't capture anything; it will match any one of a, b, c, d, or e. All a range indicates is a set of characters; [ac-eg] says "match any one of: a; any character between c and e; or g". Thus, your match says "match any one of: 0; any character between 1 and 1 (i.e., just 1); or 2.

Your goal is evidently to specify a number range: any number between 01 and 12 written with two digits. In this specific case, you can match it with 0[1-9]|1[0-2]: either a 0 followed by any digit between 1 and 9, or a 1 followed by any digit between 0 and 2. In general, you can transform any number range into a valid regex in a similar manner. There may be a better option than regular expressions, however, or an existing function or module which can construct the regex for you. It depends on your language.

Which version of MVC am I using?

typeof(Controller).Assembly.GetName().Version

Gives the current version programmatically.

Get current time in milliseconds using C++ and Boost

You can use boost::posix_time::time_duration to get the time range. E.g like this

boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();

And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock has milisecond resolution, not microsecond.

An example which is a little dependent on the hardware.

int main(int argc, char* argv[])
{
    boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
    boost::posix_time::time_duration diff = t2 - t1;
    std::cout << diff.total_milliseconds() << std::endl;

    boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
    boost::posix_time::time_duration msdiff = mst2 - mst1;
    std::cout << msdiff.total_milliseconds() << std::endl;
    return 0;
}

On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.

How to use setInterval and clearInterval?

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

How to detect the swipe left or Right in Android?

Detect swipe in four direction

private float x1,x2,y1,y2;
static final int MIN_DISTANCE = 70;

and

switch(pSceneTouchEvent.getAction())
     {
       case MotionEvent.ACTION_DOWN:
           x1 = pSceneTouchEvent.getX();     
           y1 = pSceneTouchEvent.getY();
       break;         
       case MotionEvent.ACTION_UP:
           x2 = pSceneTouchEvent.getX();
           y2 = pSceneTouchEvent.getY();
           float deltaX = x2 - x1;
           float deltaY = y2 - y1;
           if (deltaX > MIN_DISTANCE)
           {
               swipeLeftToRight();
           }
           else if( Math.abs(deltaX) > MIN_DISTANCE)
           {
               swipeRightToLeft();
           } 
           else if(deltaY > MIN_DISTANCE){
               swipeTopToBottom();
           } 
           else if( Math.abs(deltaY) > MIN_DISTANCE){
               swipeBottopmToTop();
           }

       break;   
     }          

How to make java delay for a few seconds?

This is in a mouseEvent btw

If this is in a Swing GUI, then get rid of all calls to Thread.sleep(...) as doing so can put the entire GUI to sleep rendering it useless. Instead use a Swing Timer to produce any delays in the GUI while letting it still update its graphics.

You'll also want to avoid System.out.println(...) calls, except when debugging, and instead display user notifications in the GUI itself, perhaps in a status JLabel or as a message dialog.

Regular Expressions: Search in list

You can create an iterator in Python 3.x or a list in Python 2.x by using:

filter(r.match, list)

To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).

React Router Pass Param to Component

try this.

<Route exact path="/details/:id" render={(props)=>{return(
    <DetailsPage id={props.match.params.id}/>)
}} />

In details page try this...

this.props.id

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I got the same issue and found that it was due to wrong parameters. In views.py, I used:

return render(request, 'demo.html',{'items', items})    

But I found the issue: {'items', items}. Changing to {'items': items} resolved the issue.

Getting an attribute value in xml element

I think I got it. I have to use org.w3c.dom.Element explicitly. I had a different Element field too.

How to change CSS using jQuery?

Just wanted to add that when using numbers for values with the css method you have to add them outside the apostrophe and then add the CSS unit in apostrophes.

$('.block').css('width',50 + '%');

or

var $block = $('.block')    

$block.css({ 'width': 50 + '%', 'height': 4 + 'em', 'background': '#FFDAB9' });

What is Scala's yield?

Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select and has very little to do with Ruby's and Python's yield. Basically, where in C# you would write

from ... select ??? 

in Scala you have instead

for ... yield ???

It's also important to understand that for-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:

  • If your type defines just map, it allows for-expressions consisting of a single generator.
  • If it defines flatMap as well as map, it allows for-expressions consisting of several generators.
  • If it defines foreach, it allows for-loops without yield (both with single and multiple generators).
  • If it defines filter, it allows for-filter expressions starting with an if in the for expression.

array filter in python?

If the order is not important, you should use set.difference. However, if you want to retain order, a simple list comprehension is all it takes.

result = [a for a in A if a not in subset_of_A]

EDIT: As delnan says, performance will be substantially improved if subset_of_A is an actual set, since checking for membership in a set is O(1) as compared to O(n) for a list.

A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = set([6, 9, 12]) # the subset of A

result = [a for a in A if a not in subset_of_A]

psql: FATAL: database "<user>" does not exist

Try using-

psql -d postgres

I was also facing the same issue when I ran psql

How do I get the current date in JavaScript?

Cleaner, simpler version:

new Date().toLocaleString();

Result varies according to the user's locale:

2/27/2017, 9:15:41 AM

Apache: "AuthType not set!" 500 Error

Just remove/comment the following line from your httpd.conf file (etc/httpd/conf)

Require all granted

This is needed till Apache Version 2.2 and is not required from thereon.

PHP strtotime +1 month adding an extra month

today is 29th of January, +1 month means 29th of Fabruary, but because February consists of 28 days this year, it overlaps to the next day which is March 1st

instead try

strtotime('next month')

change <audio> src with javascript

Try this snippet

_x000D_
_x000D_
list.onclick = function(e) {_x000D_
  e.preventDefault();_x000D_
_x000D_
  var elm = e.target;_x000D_
  var audio = document.getElementById('audio');_x000D_
_x000D_
  var source = document.getElementById('audioSource');_x000D_
  source.src = elm.getAttribute('data-value');_x000D_
_x000D_
  audio.load(); //call this to just preload the audio without playing_x000D_
  audio.play(); //call this to play the song right away_x000D_
};
_x000D_
<ul style="list-style: none">_x000D_
  <li>Audio Files_x000D_
    <ul id="list">_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga">Death_Becomes_Fur.oga</a></li>_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4">Death_Becomes_Fur.mp4</a></li>_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/11/rrs006.oga">rrs006.oga</a></li>_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/05/sound/sound_90.mp3">sound_90.mp3</a></li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>_x000D_
_x000D_
<audio id="audio" controls="controls">_x000D_
  <source id="audioSource" src=""></source>_x000D_
  Your browser does not support the audio format._x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFiddle http://jsfiddle.net/jm6ky/2/

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You need to use dynamic SQL to achieve this; something like:

DECLARE
    TYPE cur_type IS REF CURSOR;

    CURSOR client_cur IS
        SELECT DISTING username
        FROM all_users
        WHERE length(username) = 3;

    emails_cur cur_type;
    l_cur_string VARCHAR2(128);
    l_email_id <type>;
    l_name <type>;
BEGIN
    FOR client IN client_cur LOOP
        dbms_output.put_line('Client is '|| client.username);
        l_cur_string := 'SELECT id, name FROM '
            || client.username || '.org';
        OPEN emails_cur FOR l_cur_string;
        LOOP
            FETCH emails_cur INTO l_email_id, l_name;
            EXIT WHEN emails_cur%NOTFOUND;
            dbms_output.put_line('Org id is ' || l_email_id
                || ' org name ' || l_name);
        END LOOP;
        CLOSE emails_cur;
    END LOOP;
END;
/

Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR and an example. Edited to make the inner cursor query a string variable.

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to call Base Class's __init__ method from the child class?

You could use super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

psql: FATAL: Ident authentication failed for user "postgres"

Edit the file /etc/postgresql/8.4/main/pg_hba.conf and replace ident or peer by either md5 or trust, depending on whether you want it to ask for a password on your own computer or not. Then reload the configuration file with:

/etc/init.d/postgresql reload

What does jQuery.fn mean?

fn literally refers to the jquery prototype.

This line of code is in the source code:

jQuery.fn = jQuery.prototype = {
 //list of functions available to the jQuery api
}

But the real tool behind fn is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this will refer to the jquery object.

$.fn.myExtension = function(){
 var currentjQueryObject = this;
 //work with currentObject
 return this;//you can include this if you would like to support chaining
};

So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.

jsFiddle Demo

$.fn.blueBorder = function(){
 this.each(function(){
  $(this).css("border","solid blue 2px");
 });
 return this;
};
$.fn.blueText = function(){
 this.each(function(){
  $(this).css("color","blue");
 });
 return this;
};

Now you can use those against a class like this:

$('.blue').blueBorder().blueText();

(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)

This answer has a good example of a full fledged extension.

How to calculate date difference in JavaScript?

With momentjs it's simple:

moment("2016-04-08").fromNow();

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

Had the same problem, thanks mikej.

In WLS 10.3 this configuration can be found in Services > JTA menu, or if you click on the domain name (first item in the menu) - on the Configuration > JTA tabs.

alt text

Regex pattern inside SQL Replace function?

Instead of stripping out the found character by its sole position, using Replace(Column, BadFoundCharacter, '') could be substantially faster. Additionally, instead of just replacing the one bad character found next in each column, this replaces all those found.

WHILE 1 = 1 BEGIN
    UPDATE dbo.YourTable
    SET Column = Replace(Column, Substring(Column, PatIndex('%[^0-9.-]%', Column), 1), '')
    WHERE Column LIKE '%[^0-9.-]%'
    If @@RowCount = 0 BREAK;
END;

I am convinced this will work better than the accepted answer, if only because it does fewer operations. There are other ways that might also be faster, but I don't have time to explore those right now.

How to try convert a string to a Guid

Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.

Those are:

  • ArgumentNullException
  • FormatException
  • OverflowException

I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.

How to convert a factor to integer\numeric without loss of information?

type.convert(f) on a factor whose levels are completely numeric is another base option.

Performance-wise it's about equivalent to as.numeric(as.character(f)) but not nearly as quick as as.numeric(levels(f))[f].

identical(type.convert(f), as.numeric(levels(f))[f])

[1] TRUE

That said, if the reason the vector was created as a factor in the first instance has not been addressed (i.e. it likely contained some characters that could not be coerced to numeric) then this approach won't work and it will return a factor.

levels(f)[1] <- "some character level"
identical(type.convert(f), as.numeric(levels(f))[f])

[1] FALSE

Setting selected values for ng-options bound select elements

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

<select 
    ng-model="Choice.SelectedOption"                 
    ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>

Updated fiddle http://jsfiddle.net/gFCzV/34/

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

Bootstrap 3 .col-xs-offset-* doesn't work?

Alternatively, you can add an empty div for the xs-offset (would save you having to manage the content in more than one place)

<div class="col-xs-1 visible-xs"></div><div class="col-xs-2">col</div>

The bootstrap devs seem to be refusing to add those xs- ofsets and push/pull classes, see here: https://github.com/twbs/bootstrap/issues/9689

Can you call Directory.GetFiles() with multiple filters?

i don t know what solution is better, but i use this:

String[] ext = "*.ext1|*.ext2".Split('|');

            List<String> files = new List<String>();
            foreach (String tmp in ext)
            {
                files.AddRange(Directory.GetFiles(dir, tmp, SearchOption.AllDirectories));
            }

What's the environment variable for the path to the desktop?

in windows 7 this returns the desktop path:

FOR /F "usebackq tokens=3 " %%i in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop`) DO SET DESKTOPDIR=%%i 
FOR /F "usebackq delims=" %%i in (`ECHO %DESKTOPDIR%`) DO SET DESKTOPDIR=%%i 
ECHO %DESKTOPDIR% 

Changing CSS Values with Javascript

I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.

If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth and element.offsetHeight.

How can I create an observable with a delay

In RxJS 5+ you can do it like this

import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { delay } from "rxjs/operators";

fakeObservable = of('dummy').pipe(delay(5000));

In RxJS 6+

import { of } from "rxjs";
import { delay } from "rxjs/operators";

fakeObservable = of('dummy').pipe(delay(5000));

If you want to delay each emitted value try

from([1, 2, 3]).pipe(concatMap(item => of(item).pipe(delay(1000))));

How to create a drop shadow only on one side of an element?

update on someone else his answer transparant sides instead of white so it works on other color backgrounds too.

_x000D_
_x000D_
body {_x000D_
  background: url(http://s1.picswalls.com/wallpapers/2016/03/29/beautiful-nature-backgrounds_042320876_304.jpg)_x000D_
}_x000D_
_x000D_
div {_x000D_
  background: url(https://www.w3schools.com/w3css/img_avatar3.png) center center;_x000D_
  background-size: contain;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  margin: 50px;_x000D_
  border: 5px solid white;_x000D_
  box-shadow: 0px 0 rgba(0, 0, 0, 0), 0px 0 rgba(0, 0, 0, 0), 0 7px 7px -5px black;_x000D_
}
_x000D_
<div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I authenticate a WebClient request?

You need to give the WebClient object the credentials. Something like this...

 WebClient client = new WebClient();
 client.Credentials = new NetworkCredential("username", "password");

Auto increment primary key in SQL Server Management Studio 2012

Expand your database, expand your table right click on your table and select design from dropdown. ITlooks like this

Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it. enter image description here

How to insert TIMESTAMP into my MySQL table?

Please try CURRENT_TIME() or now() functions

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"

OR

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"

OR you could try with PHP date function here:

$date = date("Y-m-d H:i:s");

Where can I read the Console output in Visual Studio 2015

You can run your program by: Debug -> Start Without Debugging. It will keep a console opened after the program will be finished.

enter image description here

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

I know it is an old question but i faced this error today.

and i found that, this error can be thrown when a database table trigger gets an error.

for your information, you can check your tables triggers too when you get this error.

How to output (to a log) a multi-level array in a format that is human-readable?

If you need to log an error to Apache error log you can try this:

error_log( print_r($multidimensionalarray, TRUE) );

What does enctype='multipart/form-data' mean?

  • enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server.
  • multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.

Retrieving Dictionary Value Best Practices

I imagine that trygetvalue is doing something more like:

if(myDict.ReallyOptimisedVersionofContains(someKey))
{ 
  someVal = myDict[someKey];
  return true;
}
return false;

So hopefully no try/catch anywhere.

I think it is just a method of convenience really. I generally use it as it saves a line of code or two.

Android Studio : unmappable character for encoding UTF-8

A few encoding issues that I had to face couldn't be solved by above solutions. I had to either update my Android Studio or run test cases using following command in the AS terminal.

gradlew clean assembleDebug testDebug

P.S your encoding settings for IDE and project should match.

Hope it helps !

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

In git how is fetch different than pull and how is merge different than rebase?

Fetch vs Pull

Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled

What is the difference between 'git pull' and 'git fetch'?


Merge vs Rebase

from Atlassian SourceTree Blog, Merge or Rebase:

Merging brings two lines of development together while preserving the ancestry of each commit history.

In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.

How do I kill all the processes in Mysql "show processlist"?

We can do it by MySQL Workbench. Just execute this:

kill id;

Example:

kill 13412

That will remove it.

When should I use Kruskal as opposed to Prim (and vice versa)?

One important application of Kruskal's algorithm is in single link clustering.

Consider n vertices and you have a complete graph.To obtain a k clusters of those n points.Run Kruskal's algorithm over the first n-(k-1) edges of the sorted set of edges.You obtain k-cluster of the graph with maximum spacing.

mongodb: insert if not exists

Summary

  • You have an existing collection of records.
  • You have a set records that contain updates to the existing records.
  • Some of the updates don't really update anything, they duplicate what you have already.
  • All updates contain the same fields that are there already, just possibly different values.
  • You want to track when a record was last changed, where a value actually changed.

Note, I'm presuming PyMongo, change to suit your language of choice.

Instructions:

  1. Create the collection with an index with unique=true so you don't get duplicate records.

  2. Iterate over your input records, creating batches of them of 15,000 records or so. For each record in the batch, create a dict consisting of the data you want to insert, presuming each one is going to be a new record. Add the 'created' and 'updated' timestamps to these. Issue this as a batch insert command with the 'ContinueOnError' flag=true, so the insert of everything else happens even if there's a duplicate key in there (which it sounds like there will be). THIS WILL HAPPEN VERY FAST. Bulk inserts rock, I've gotten 15k/second performance levels. Further notes on ContinueOnError, see http://docs.mongodb.org/manual/core/write-operations/

    Record inserts happen VERY fast, so you'll be done with those inserts in no time. Now, it's time to update the relevant records. Do this with a batch retrieval, much faster than one at a time.

  3. Iterate over all your input records again, creating batches of 15K or so. Extract out the keys (best if there's one key, but can't be helped if there isn't). Retrieve this bunch of records from Mongo with a db.collectionNameBlah.find({ field : { $in : [ 1, 2,3 ...}) query. For each of these records, determine if there's an update, and if so, issue the update, including updating the 'updated' timestamp.

    Unfortunately, we should note, MongoDB 2.4 and below do NOT include a bulk update operation. They're working on that.

Key Optimization Points:

  • The inserts will vastly speed up your operations in bulk.
  • Retrieving records en masse will speed things up, too.
  • Individual updates are the only possible route now, but 10Gen is working on it. Presumably, this will be in 2.6, though I'm not sure if it will be finished by then, there's a lot of stuff to do (I've been following their Jira system).

Database Structure for Tree Data Structure

Have a look at Managing Hierarchical Data in MySQL. It discusses two approaches for storing and managing hierarchical (tree-like) data in a relational database.

The first approach is the adjacency list model, which is what you essentially describe: having a foreign key that refers to the table itself. While this approach is simple, it can be very inefficient for certain queries, like building the whole tree.

The second approach discussed in the article is the nested set model. This approach is far more efficient and flexible. Refer to the article for detailed explanation and example queries.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

Using the standard CustomCreationConverter, I was struggling to work how to generate the correct type (Person or Employee), because in order to determine this you need to analyse the JSON and there is no built in way to do this using the Create method.

I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting.

What's required is to subclass JsonConverter, overriding the ReadJson method and creating a new abstract Create method which accepts a JObject.

The JObject class provides a means to load a JSON object and provides access to the data within this object.

The overridden ReadJson method creates a JObject and invokes the Create method (implemented by our derived converter class), passing in the JObject instance.

This JObject instance can then be analysed to determine the correct type by checking existence of certain fields.

Example

string json = "[{
        \"Department\": \"Department1\",
        \"JobTitle\": \"JobTitle1\",
        \"FirstName\": \"FirstName1\",
        \"LastName\": \"LastName1\"
    },{
        \"Department\": \"Department2\",
        \"JobTitle\": \"JobTitle2\",
        \"FirstName\": \"FirstName2\",
        \"LastName\": \"LastName2\"
    },
        {\"Skill\": \"Painter\",
        \"FirstName\": \"FirstName3\",
        \"LastName\": \"LastName3\"
    }]";

List<Person> persons = 
    JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());

...

public class PersonConverter : JsonCreationConverter<Person>
{
    protected override Person Create(Type objectType, JObject jObject)
    {
        if (FieldExists("Skill", jObject))
        {
            return new Artist();
        }
        else if (FieldExists("Department", jObject))
        {
            return new Employee();
        }
        else
        {
            return new Person();
        }
    }

    private bool FieldExists(string fieldName, JObject jObject)
    {
        return jObject[fieldName] != null;
    }
}

public abstract class JsonCreationConverter<T> : JsonConverter
{
    /// <summary>
    /// Create an instance of objectType, based properties in the JSON object
    /// </summary>
    /// <param name="objectType">type of object expected</param>
    /// <param name="jObject">
    /// contents of JSON object that will be deserialized
    /// </param>
    /// <returns></returns>
    protected abstract T Create(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, 
                                    Type objectType, 
                                     object existingValue, 
                                     JsonSerializer serializer)
    {
        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        T target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How do I rename a Git repository?

  • On the server side, just rename the repository with the mv command as usual:

    mv oldName.git newName.git
    
  • Then on the client side, change the value of the [remote "origin"] URL into the new one:

    url=example.com/newName.git
    

It worked for me.

RestSharp JSON Parameter Posting

This is what worked for me, for my case it was a post for login request :

var client = new RestClient("http://www.example.com/1/2");
var request = new RestRequest();

request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", body , ParameterType.RequestBody);

var response = client.Execute(request);
var content = response.Content; // raw content as string  

body :

{
  "userId":"[email protected]" ,
  "password":"welcome" 
}

Generating a random & unique 8 character string using MySQL

If you dont have a id or seed, like its its for a values list in insert:

REPLACE(RAND(), '.', '')

Spring Boot - How to log all requests and responses with exceptions in single place?

After adding Actuators to the spring boot bassed application you have /trace endpoint available with latest requests informations. This endpoint is working based on TraceRepository and default implementation is InMemoryTraceRepository that saves last 100 calls. You can change this by implementing this interface by yourself and make it available as a Spring bean. For example to log all requests to log (and still use default implementation as a basic storage for serving info on /trace endpoint) I'm using this kind of implementation:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.Trace;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


@Component
public class LoggingTraceRepository implements TraceRepository {

  private static final Logger LOG = LoggerFactory.getLogger(LoggingTraceRepository.class);
  private final TraceRepository delegate = new InMemoryTraceRepository();

  @Override
  public List<Trace> findAll() {
    return delegate.findAll();
  }

  @Override
  public void add(Map<String, Object> traceInfo) {
    LOG.info(traceInfo.toString());
    this.delegate.add(traceInfo);
  }
}

This traceInfo map contains basic informations about request and response in this kind of form: {method=GET, path=/api/hello/John, headers={request={host=localhost:8080, user-agent=curl/7.51.0, accept=*/*}, response={X-Application-Context=application, Content-Type=text/plain;charset=UTF-8, Content-Length=10, Date=Wed, 29 Mar 2017 20:41:21 GMT, status=200}}}. There is NO response content here.

EDIT! Logging POST data

You can access POST data by overriding WebRequestTraceFilter, but don't think it is a good idea (e.g. all uploaded file content will go to logs) Here is sample code, but don't use it:

package info.fingo.nuntius.acuate.trace;

import org.apache.commons.io.IOUtils;
import org.springframework.boot.actuate.trace.TraceProperties;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.actuate.trace.WebRequestTraceFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class CustomWebTraceFilter extends WebRequestTraceFilter {

  public CustomWebTraceFilter(TraceRepository repository, TraceProperties properties) {
    super(repository, properties);
}

  @Override
  protected Map<String, Object> getTrace(HttpServletRequest request) {
    Map<String, Object> trace = super.getTrace(request);
    String multipartHeader = request.getHeader("content-type");
    if (multipartHeader != null && multipartHeader.startsWith("multipart/form-data")) {
        Map<String, Object> parts = new LinkedHashMap<>();
        try {
            request.getParts().forEach(
                    part -> {
                        try {
                            parts.put(part.getName(), IOUtils.toString(part.getInputStream(), Charset.forName("UTF-8")));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
        if (!parts.isEmpty()) {
            trace.put("multipart-content-map", parts);
        }
    }
    return trace;
  }
}

How do I programmatically force an onchange event on an input?

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Here is a bare bones version:

Let's say that you have a date in Cell A1 in the format you described. For example: 19760210.

Then this formula will give you the date you want:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).

On my system (Excel 2010) it works with strings or floats.

How to customise file type to syntax associations in Sublime Text?

I put my customized changes in the User package:

*nix: ~/.config/sublime-text-2/Packages/User/Scala.tmLanguage
*Windows: %APPDATA%\Sublime Text 2\Packages\User\Scala.tmLanguage

Which also means it's in JSON format:

{
  "extensions":
  [
    "sbt"
  ]
}

This is the same place the

View -> Syntax -> Open all with current extension as ...

menu item adds it (creating the file if it doesn't exist).

Importing csv file into R - numeric values read as characters

In read.table (and its relatives) it is the na.strings argument which specifies which strings are to be interpreted as missing values NA. The default value is na.strings = "NA"

If missing values in an otherwise numeric variable column are coded as something else than "NA", e.g. "." or "N/A", these rows will be interpreted as character, and then the whole column is converted to character.

Thus, if your missing values are some else than "NA", you need to specify them in na.strings.

blur vs focusout -- any real differences?

As stated in the JQuery documentation

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

Neither code is always better. They do different things, so they are good at different things.

InvariantCultureIgnoreCase uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.

OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

Setting a PHP $_SESSION['var'] using jQuery

You can't do it through jQuery alone; you'll need a combination of Ajax (which you can do with jQuery) and a PHP back-end. A very simple version might look like this:

HTML:

<img class="foo" src="img.jpg" />
<img class="foo" src="img2.jpg" />
<img class="foo" src="img3.jpg" />

Javascript:

$("img.foo").onclick(function()
{
    // Get the src of the image
    var src = $(this).attr("src");

    // Send Ajax request to backend.php, with src set as "img" in the POST data
    $.post("/backend.php", {"img": src});
});

PHP (backend.php):

<?php
    // do any authentication first, then add POST variable to session
    $_SESSION['imgsrc'] = $_POST['img'];
?>

How do I create a copy of an object in PHP?

In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).

You can use the 'clone' operator in PHP5 to copy objects:

$objectB = clone $objectA;

Also, it's just objects that are passed by reference, not everything as you've said in your question...

How do I copy a 2 Dimensional array in Java?

Using java 8 this can be done with

`int[][] destination=Arrays.stream(source)
                    .map(a ->  Arrays.copyOf(a, a.length))
                    .toArray(int[][]::new);

How do I convert a byte array to Base64 in Java?

Use:

byte[] data = Base64.encode(base64str);

Encoding converts to Base64

You would need to reference commons codec from your project in order for that code to work.

For java8:

import java.util.Base64

How to find out the username and password for mysql database

There are two easy ways:

  1. In your cpanel Go to cpanel/ softaculous/ wordpress, under the current installation, you will see the websites you have installed with the wordpress. Click the "edit detail" of the particular website and you will see your SQL database username and password.

  2. In your server Access your FTP and view the wp-config.php

Set min-width in HTML table's <td>

<table style="border:2px solid #ddedde">
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
</table>

How to conditionally take action if FINDSTR fails to find a string

In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).

There are a couple methods to check that value, but the original one is:

IF ERRORLEVEL value command

Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:

verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%

Findstr command return 0 if the string was found and 1 if not:

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code will copy the file if the string was NOT found in the file.

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code copy the file if the string was found. Try this:

findstr "string" file
if errorlevel 1 (
    echo String NOT found...
) else (
    echo String found
)

Are the decimal places in a CSS width respected?

Elements have to paint to an integer number of pixels, and as the other answers covered, percentages are indeed respected.

An important note is that pixels in this case means css pixels, not screen pixels, so a 200px container with a 50.7499% child will be rounded to 101px css pixels, which then get rendered onto 202px on a retina screen, and not 400 * .507499 ~= 203px.

Screen density is ignored in this calculation, and there is no way to paint* an element to specific retina subpixel sizes. You can't have elements' backgrounds or borders rendered at less than 1 css pixel size, even though the actual element's size could be less than 1 css pixel as Sandy Gifford showed.

[*] You can use some techniques like 0.5 offset box-shadow, etc, but the actual box model properties will paint to a full CSS pixel.

conversion from string to json object android

Using Kotlin

    val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
    
try {
      val jsonObject = JSONObject(data)
      val infoObj = jsonObject.getJSONObject("ApiInfo")
    } catch (e: Exception) {
    }

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Pandas DataFrame to List of Lists

  1. The solutions presented so far suffer from a "reinventing the wheel" approach. Quoting @AMC:

If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.

  1. If you convert a dataframe to a list of lists you will lose information - namely the index and columns names.

My solution: use to_dict()

dict_of_lists = df.to_dict(orient='split')

This will give you a dictionary with three lists: index, columns, data. If you decide you really don't need the columns and index names, you get the data with

dict_of_lists['data']

Git diff against a stash

This works for me on git version 1.8.5.2:

git diff stash HEAD

converting a base 64 string to an image and saving it

I would suggest via Bitmap:

public void SaveImage(string base64)
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
    {
        using (Bitmap bm2 = new Bitmap(ms))
        {
            bm2.Save("SavingPath" + "ImageName.jpg");
        }
    }
}

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

Java: Get month Integer from Date

Joda-Time

Alternatively, with the Joda-Time DateTime class.

//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))

…or…

int month = dateTime.getMonthOfYear();

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

In my case, I had to comment out com.google.firebase.firebase-crash plugin:

apply plugin: 'com.android.application'
// apply plugin: 'com.google.firebase.firebase-crash' <== this plugin causes the error

It is a bug since Android Studio 3.3.0

Generate HTML table from 2D JavaScript array

An es6 version of Daniel Williams' answer:

  function get_table(data) {
    let result = ['<table border=1>'];
    for(let row of data) {
        result.push('<tr>');
        for(let cell of row){
            result.push(`<td>${cell}</td>`);
        }
        result.push('</tr>');
    }
    result.push('</table>');
    return result.join('\n');
  }

HTML5 Email input pattern attribute

In HTML5 you can use the new 'email' type: http://www.w3.org/TR/html-markup/input.email.html

For example:

<input type="email" id="email" />

If the browser implements HTML5 it will make sure that the user has entered a valid email address in the field. Note that if the browser doesn't implement HTML5, it will be treated like a 'text' type, ie:

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

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

Insert value into a string at a certain position?

If you have a string and you know the index you want to put the two variables in the string you can use:

string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);

But if it is a simple line you can use it this way:

string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"

Matching an empty input box using CSS

It worked for me to add a class name to the input and then apply CSS rules to that:

<input type="text" name="product" class="product" />

<style>
input[value=""].product {
    display: none;
}
</style>

img tag displays wrong orientation

If you have access to Linux, then open a terminal, cd to the directory containing your images and then run

mogrify -auto-orient *

This should permanently fix the orientation issues on all the images.

What is the best way to create a string array in python?

strlist =[{}]*10
strlist[0] = set()
strlist[0].add("Beef")
strlist[0].add("Fish")
strlist[1] = {"Apple", "Banana"}
strlist[1].add("Cherry")
print(strlist[0])
print(strlist[1])
print(strlist[2])
print("Array size:", len(strlist))
print(strlist)

git remove merge commit from history

To Just Remove a Merge Commit

If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows

git rebase --onto <sha of 1> <sha of 2> <blue branch>

And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.

Could not commit JPA transaction: Transaction marked as rollbackOnly

Save sub object first and then call final repository save method.

@PostMapping("/save")
    public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
        Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
        if (existingShortcode != null) {
            result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
        }
        if (result.hasErrors()) {
            return "redirect:/shortcode/create";
        }
        **shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
        shortcodeService.save(shortcode);
        return "redirect:/shortcode/create?success";
    }

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

Java difference between FileWriter and BufferedWriter

You are right. Here is how write() method of BufferedWriter looks:

public void write(int c) throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (nextChar >= nChars)
            flushBuffer();
        cb[nextChar++] = (char) c;
    }
}

As you can see it indeed checks whether the buffer is full (if (nextChar >= nChars)) and flushes the buffer. Then it adds new character to buffer (cb[nextChar++] = (char) c;).

Update R using RStudio

If you're using a Mac computer, you can use the new updateR package to update the R version from RStudio: http://www.andreacirillo.com/2018/02/10/updater-package-update-r-version-with-a-function-on-mac-osx/

In summary, you need to perform this:

To update your R version from within Rstudio using updateR you just have to run these five lines of code:

install.packages('devtools') #assuming it is not already installed
library(devtools)
install_github('andreacirilloac/updateR')
library(updateR)
updateR(admin_password = 'Admin user password')

at the end of installation process a message is going to confirm you the happy end:

everything went smoothly
open a Terminal session and run 'R' to assert that latest version was installed

How to add multiple values to a dictionary key in python?

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.

Error : ORA-01704: string literal too long

What are you using when operate with CLOB?

In all events you can do it with PL/SQL

DECLARE
  str varchar2(32767);
BEGIN
  str := 'Very-very-...-very-very-very-very-very-very long string value';
  update t1 set col1 = str;
END;
/

Proof link on SQLFiddle

Redirect output of mongo query to a csv file

I use the following technique. It makes it easy to keep the column names in sync with the content:

var cursor = db.getCollection('Employees.Details').find({})

var header = []
var rows = []

var firstRow = true
cursor.forEach((doc) => 
{
    var cells = []
    
    if (firstRow) header.push("employee_number")
    cells.push(doc.EmpNum.valueOf())

    if (firstRow) header.push("name")
    cells.push(doc.FullName.valueOf())    

    if (firstRow) header.push("dob")
    cells.push(doc.DateOfBirth.valueOf())   
    
    row = cells.join(',')
    rows.push(row)    

    firstRow =  false
})

print(header.join(','))
print(rows.join('\n'))

Merge two (or more) lists into one, in C# .NET

You could use the Concat extension method:

var result = productCollection1
    .Concat(productCollection2)
    .Concat(productCollection3)
    .ToList();

How can I shuffle an array?

You could use the Fisher-Yates Shuffle (code adapted from this site):

function shuffle(array) {
    let counter = array.length;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        let index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        let temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

What is sr-only in Bootstrap 3?

.sr-only is a class name specifically used for screen readers. You can use any class name, but .sr-only is pretty commonly used. If you don't care about developing with compliance in mind, then it can be removed. It will not affect UI in any way if removed because the CSS for this class is not visible to desktop and mobile device browsers.

There seems to be some information missing here about the use of .sr-only to explain its purpose and being for screen readers. First and foremost, it is very important to always keep impaired users in mind. Impairment is the purpose of 508 compliance: https://www.section508.gov/, and it is great that bootstrap takes this into consideration. However, the use of .sr-only is not all that needs to be taken into consideration for 508 compliance. You have the use of color, size of fonts, accessibility via navigation, descriptors, use of aria and so much more.

But as for .sr-only - what does the CSS actually do? There are several slightly different variants of the CSS used for .sr-only. One of the few I use is below:

.sr-only {
    position: absolute;
    margin: -1px 0 0 -1px;
    padding: 0;
    display: block;
    width: 1px;
    height: 1px;
    font-size: 1px;
    line-height: 1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
    outline: 0;
    }

The above CSS hides content in desktop and mobile browsers wrapped with this class, but is seen by a screen reader like JAWS: http://www.freedomscientific.com/Products/Blindness/JAWS. Example markup is as follows:

<a href="#" target="_blank">
    Click to Open Site
    <span class="sr-only">This is an external link</span>
</a>

Additionally, if a DOM element has a width and height of 0, the element is not seen by the DOM. This is why the above CSS uses width: 1px; height: 1px;. By using display: none and setting your CSS to height: 0 and width: 0, the element is not seen by the DOM and is thus problematic. The above CSS using width: 1px; height: 1px; is not all you do to make the content invisible to desktop and mobile browsers (without overflow: hidden, your content would still show on the screen), and visible to screen readers. Hiding the content from desktop and mobile browsers is done by adding an offset from width: 1px and height: 1px previously mentioned by using:

position: absolute;
margin: -1px 0 0 -1px; 
overflow: hidden;

Lastly, to have a very good idea of what a screen reader sees and relays to its impaired user, turn off page styling for your browser. For Firefox, you can do this by going to:

View > Page Style > No Style

I hope the information I provided here is of further use to someone in addition to the other responses.

How to set timer in android?

ok since this isn't cleared up yet there are 3 simple ways to handle this. Below is an example showing all 3 and at the bottom is an example showing just the method I believe is preferable. Also remember to clean up your tasks in onPause, saving state if necessary.


import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class main extends Activity {
    TextView text, text2, text3;
    long starttime = 0;
    //this  posts a message to the main thread from our timertask
    //and updates the textfield
   final Handler h = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text.setText(String.format("%d:%02d", minutes, seconds));
            return false;
        }
    });
   //runs without timer be reposting self
   Handler h2 = new Handler();
   Runnable run = new Runnable() {

        @Override
        public void run() {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text3.setText(String.format("%d:%02d", minutes, seconds));

           h2.postDelayed(this, 500);
        }
    };

   //tells handler to send a message
   class firstTask extends TimerTask {

        @Override
        public void run() {
            h.sendEmptyMessage(0);
        }
   };

   //tells activity to run on ui thread
   class secondTask extends TimerTask {

        @Override
        public void run() {
            main.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   long millis = System.currentTimeMillis() - starttime;
                   int seconds = (int) (millis / 1000);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;

                   text2.setText(String.format("%d:%02d", minutes, seconds));
                }
            });
        }
   };


   Timer timer = new Timer();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView)findViewById(R.id.text);
        text2 = (TextView)findViewById(R.id.text2);
        text3 = (TextView)findViewById(R.id.text3);

        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button)v;
                if(b.getText().equals("stop")){
                    timer.cancel();
                    timer.purge();
                    h2.removeCallbacks(run);
                    b.setText("start");
                }else{
                    starttime = System.currentTimeMillis();
                    timer = new Timer();
                    timer.schedule(new firstTask(), 0,500);
                    timer.schedule(new secondTask(),  0,500);
                    h2.postDelayed(run, 0);
                    b.setText("stop");
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        timer.purge();
        h2.removeCallbacks(run);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }
}


the main thing to remember is that the UI can only be modified from the main ui thread so use a handler or activity.runOnUIThread(Runnable r);

Here is what I consider to be the preferred method.


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TestActivity extends Activity {

    TextView timerTextView;
    long startTime = 0;

    //runs without a timer by reposting this handler at the end of the runnable
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {

        @Override
        public void run() {
            long millis = System.currentTimeMillis() - startTime;
            int seconds = (int) (millis / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;

            timerTextView.setText(String.format("%d:%02d", minutes, seconds));

            timerHandler.postDelayed(this, 500);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);

        timerTextView = (TextView) findViewById(R.id.timerTextView);

        Button b = (Button) findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().equals("stop")) {
                    timerHandler.removeCallbacks(timerRunnable);
                    b.setText("start");
                } else {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                    b.setText("stop");
                }
            }
        });
    }

  @Override
    public void onPause() {
        super.onPause();
        timerHandler.removeCallbacks(timerRunnable);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }

}


How to change the window title of a MATLAB plotting figure?

You need to set figure properties.

At the very beginning of the script, call

figure('name','something else')

Calling figure is a good thing, anyway, because without it, you always plot into the same window, and sometimes you may want to compare two windows side-by-side.

Alternatively, you can store the figure's handle by calling

figH = figure;

so that you can later change the figure properties to your liking (the 'numberTitle' property setting eliminates the "figure X" text)

set(figH,'Name','something else','NumberTitle','off')

Have a look at the figure properties in the MATLAB documentation to see what else you can change if you want.

PHP new line break in emails

When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be

str_replace("\n","<br/>",$str);

after adding this code you wont have to use pre tag for all the output oparation.

copyed this ans from this website :

C++ pointer to objects

No, you can have pointers to stack allocated objects:

MyClass *myclass;
MyClass c;
myclass = & c;
myclass->DoSomething();

This is of course common when using pointers as function parameters:

void f( MyClass * p ) {
    p->DoSomething();
}

int main() {
    MyClass c;
    f( & c );
}

One way or another though, the pointer must always be initialised. Your code:

MyClass *myclass;
myclass->DoSomething();

leads to that dreaded condition, undefined behaviour.

Is Java a Compiled or an Interpreted programming language ?

Kind of both. Firstly java compiled(some would prefer to say "translated") to bytecode, which then either compiled, or interpreted depending on mood of JIT.

resize font to fit in a div (on one line)

I had a similar issue, which made me write my own plugin for this. Have a look at jquery-quickfit (which is quite similar to Robert Koritnik's solution, which I really like).

In order to prevent the headline to span multiple lines, just add a css style of:

white-space:nowrap;

to the element.

After including jquery and quickfit in the header. You can trigger quickfit with:

$('h1').quickfit();

It meassures and calculates a size invariant meassure for each letter of the text to fit and uses this to calculate the next best font-size which fits the text into the container.

The calculations are cached, which makes it very fast when dealing having to fit multiple text or having to fit a text multiple times, like e.g., on window resize (there is almost no performance penalty on resize).

Demo for a similar situation as yours

Further documentation, examples and source code are on the project page.

get unique machine id

Yes, We could get a code which is combination of Physical Address, Unique Drive ID, Hard Drive ID (Volume Serial), CPU ID and BIOS ID. Example (Full example):

//Main physical hard drive ID
    private static string diskId()
    {
        return identifier("Win32_DiskDrive", "Model")
        + identifier("Win32_DiskDrive", "Manufacturer")
        + identifier("Win32_DiskDrive", "Signature")
        + identifier("Win32_DiskDrive", "TotalHeads");
    }
    //Motherboard ID
    private static string baseId()
    {
        return identifier("Win32_BaseBoard", "Model")
        + identifier("Win32_BaseBoard", "Manufacturer")
        + identifier("Win32_BaseBoard", "Name")
        + identifier("Win32_BaseBoard", "SerialNumber");
    }

How can I use different certificates on specific connections?

I read through LOTS of places online to solve this thing. This is the code I wrote to make it work:

ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());

app.certificateString is a String that contains the Certificate, for example:

static public String certificateString=
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
        "BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
        ... a bunch of characters...
        "5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
        "-----END CERTIFICATE-----";

I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.

How to store an output of shell script to a variable in Unix?

export a=$(script.sh)

Hope this helps. Note there are no spaces between variable and =. To echo the output

echo $a

Flask-SQLalchemy update a row's information

Just assigning the value and committing them will work for all the data types but JSON and Pickled attributes. Since pickled type is explained above I'll note down a slightly different but easy way to update JSONs.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    data = db.Column(db.JSON)

def __init__(self, name, data):
    self.name = name
    self.data = data

Let's say the model is like above.

user = User("Jon Dove", {"country":"Sri Lanka"})
db.session.add(user)
db.session.flush()
db.session.commit()

This will add the user into the MySQL database with data {"country":"Sri Lanka"}

Modifying data will be ignored. My code that didn't work is as follows.

user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
db.session.merge(user)
db.session.flush()
db.session.commit()

Instead of going through the painful work of copying the JSON to a new dict (not assigning it to a new variable as above), which should have worked I found a simple way to do that. There is a way to flag the system that JSONs have changed.

Following is the working code.

from sqlalchemy.orm.attributes import flag_modified
user = User.query().filter(User.name=='Jon Dove')
data = user.data
data["province"] = "south"
user.data = data
flag_modified(user, "data")
db.session.merge(user)
db.session.flush()
db.session.commit()

This worked like a charm. There is another method proposed along with this method here Hope I've helped some one.

Efficiently sorting a numpy array in descending order?

For short arrays I suggest using np.argsort() by finding the indices of the sorted negatived array, which is slightly faster than reversing the sorted array:

In [37]: temp = np.random.randint(1,10, 10)

In [38]: %timeit np.sort(temp)[::-1]
100000 loops, best of 3: 4.65 µs per loop

In [39]: %timeit temp[np.argsort(-temp)]
100000 loops, best of 3: 3.91 µs per loop

GCD to perform task in main thread

As the other answers mentioned, dispatch_async from the main thread is fine.

However, depending on your use case, there is a side effect that you may consider a disadvantage: since the block is scheduled on a queue, it won't execute until control goes back to the run loop, which will have the effect of delaying your block's execution.

For example,

NSLog(@"before dispatch async");
dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"inside dispatch async block main thread from main thread");
});
NSLog(@"after dispatch async");

Will print out:

before dispatch async
after dispatch async
inside dispatch async block main thread from main thread

For this reason, if you were expecting the block to execute in-between the outer NSLog's, dispatch_async would not help you.

Cannot start session without errors in phpMyAdmin

There appears to be two common causes for this error, one is to do with the server configuration and the session.save_path and the other is the browser cache.

If you encounter this error try using a different browser or machine before you attempt to alter your Apache and PHP configurations on the server!

Note that clearing the Cookies for the server is not enough, you need to clear the cache.

In Firefox clearing all history and cookies is easy, but you may not want to get rid of everything. Clearing the cache is hidden away in Firefox:

Tools > Options > Advanced > Network: Cached Web Content - Clear Now

Is there a way to automatically build the package.json file for Node.js projects

npm add <package-name>

The above command will add the package to the node modules and update the package.json file

Getting selected value of a combobox

The problem you have with the SelectedValue is not converting into integer. This is the main problem so usinge the following code snippet will help you:

int selectedValue;
bool parseOK = Int32.TryParse(cmb.SelectedValue.ToString(), out selectedValue);

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

convert a char* to std::string

const char* charPointer = "Hello, World!\n";
std::string strFromChar;
strFromChar.append(charPointer);
std::cout<<strFromChar<<std::endl;

How to check if a string is numeric?

Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric

One more is

public boolean isNumeric(String s) {  
    return s != null && s.matches("[-+]?\\d*\\.?\\d+");  
}  

Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.

Use '=' or LIKE to compare strings in SQL?

LIKE is used for pattern matching and = is used for equality test (as defined by the COLLATION in use).

= can use indexes while LIKE queries usually require testing every single record in the result set to filter it out (unless you are using full text search) so = has better performance.

Divide a number by 3 without using *, /, +, -, % operators

Good 'ol bc:

$ num=1337; printf "scale=5;${num}\x2F3;\n" | bc
445.66666

How to get the selected radio button’s value?

 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 1">
 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 2">
 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 3">
 <input type=radio name=rdbExampleInfo id=rdbExamples value="select 4"> 

etc then use just

  $("#rdbExamples:checked").val()

Or

   $('input[name="rdbExampleInfo"]:checked').val();

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

How to save username and password with Mercurial?

A simple hack is to add username and password to the push url in your project's .hg/hgrc file:

[paths]
default = http://username:[email protected]/myproject

(Note that in this way you store the password in plain text)

If you're working on several projects under the same domain, you might want to add a rewrite rule in your ~/.hgrc file, to avoid repeating this for all projects:

[rewrite]
http.//mydomain.com = http://username:[email protected]

Again, since the password is stored in plain text, I usually store just my username.

If you're working under Gnome, I explain how to integrate Mercurial and the Gnome Keyring here:

http://aloiroberto.wordpress.com/2009/09/16/mercurial-gnome-keyring-integration/

Multiple REPLACE function in Oracle

I have created a general multi replace string Oracle function by a table of varchar2 as parameter. The varchar will be replaced for the position rownum value of table.

For example:

Text: Hello {0}, this is a {2} for {1}
Parameters: TABLE('world','all','message')

Returns:

Hello world, this is a message for all.

You must create a type:

CREATE OR REPLACE TYPE "TBL_VARCHAR2" IS TABLE OF VARCHAR2(250);

The funcion is:

CREATE OR REPLACE FUNCTION FN_REPLACETEXT(
    pText IN VARCHAR2, 
    pPar IN TBL_VARCHAR2
) RETURN VARCHAR2
IS
    vText VARCHAR2(32767);
    vPos INT;
    vValue VARCHAR2(250);

    CURSOR cuParameter(POS INT) IS
    SELECT VAL
        FROM
            (
            SELECT VAL, ROWNUM AS RN 
            FROM (
                  SELECT COLUMN_VALUE VAL
                  FROM TABLE(pPar)
                  )
            )
        WHERE RN=POS+1;
BEGIN
    vText := pText;
    FOR i IN 1..REGEXP_COUNT(pText, '[{][0-9]+[}]') LOOP
        vPos := TO_NUMBER(SUBSTR(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i),2, LENGTH(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i)) - 2));

        OPEN cuParameter(vPos);
        FETCH cuParameter INTO vValue;
        IF cuParameter%FOUND THEN
            vText := REPLACE(vText, REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i), vValue);
        END IF;
        CLOSE cuParameter;
    END LOOP;

    RETURN vText;

EXCEPTION
      WHEN OTHERS
      THEN
         RETURN pText;
END FN_REPLACETEXT;
/

Usage:

TEXT_RETURNED := FN_REPLACETEXT('Hello {0}, this is a {2} for {1}', TBL_VARCHAR2('world','all','message'));

Using ADB to capture the screen

https://stackoverflow.com/a/37191719/75579 answer stopped working for me in Android 7 somehow. So I have to do it the manual way, so I want to share it.


How to install

  1. Put this snippet of code in your ~/.bash_profile or ~/.profile file:

    snap_screen() {
      if [ $# -eq 0 ]
      then
        name="screenshot.png"
      else
        name="$1.png"
      fi
      adb shell screencap -p /sdcard/$name
      adb pull /sdcard/$name
      adb shell rm /sdcard/$name
      curr_dir=pwd
      echo "save to `pwd`/$name"
    }
    
  2. Run source ~/.bash_profile or source ~/.profile command,


How to use

Usage without specifying filename:

$ snap_screen
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/screenshot.png

Usage with a filename:

$ snap_screen mega_screen_capture
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/mega_screen_capture.png

Hope it helps!

** This will not work if multiple devices are plugged in

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

How can I remove the string "\n" from within a Ruby string?

If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip method.

"    hello    ".strip   #=> "hello"   
"\tgoodbye\r\n".strip   #=> "goodbye"

as mentioned here.

edit The original title for this question was different. My answer is for the original question.

Create a custom callback in JavaScript

If you want to execute a function when something is done. One of a good solution is to listen to events. For example, I'll implement a Dispatcher, a DispatcherEvent class with ES6,then:

let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)

const loadSuccessCallback = (data) =>{
   ...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')

Dispatcher:

class Dispatcher{
  constructor(){
    this.events = {}
  }

  dispatch(eventName, data){
    const event = this.events[eventName]
    if(event){
      event.fire(data)
    }
  }

  //start listen event
  on(eventName, callback){
    let event = this.events[eventName]
    if(!event){
      event = new DispatcherEvent(eventName)
      this.events[eventName] = event
    }
    event.registerCallback(callback)
  }

  //stop listen event
  off(eventName, callback){
    const event = this.events[eventName]
    if(event){
      delete this.events[eventName]
    }
  }
}

DispatcherEvent:

class DispatcherEvent{
  constructor(eventName){
    this.eventName = eventName
    this.callbacks = []
  }

  registerCallback(callback){
    this.callbacks.push(callback)
  }

  fire(data){
    this.callbacks.forEach((callback=>{
      callback(data)
    }))
  }
}

Happy coding!

p/s: My code is missing handle some error exceptions

Java URLConnection Timeout

Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket

How to input matrix (2D list) in Python?

If the input is formatted like this,

1 2 3
4 5 6
7 8 9

a one liner can be used

mat = [list(map(int,input().split())) for i in range(row)]

How to select clear table contents without destroying the table?

Try just clearing the data (not the entire table including headers):

ACell.ListObject.DataBodyRange.ClearContents

Do I commit the package-lock.json file created by npm 5?

Yes, it's a standard practice to commit package-lock.json.

The main reason for committing package-lock.json is that everyone in the project is on the same package version.

Pros:

  • If you follow strict versioning and don't allow updating to major versions automatically to save yourself from backward-incompatible changes in third-party packages committing package-lock helps a lot.
  • If you update a particular package, it gets updated in package-lock.json and everyone using the repository gets updated to that particular version when they take the pull of your changes.

Cons:

  • It can make your pull requests look ugly :)

npm install won't make sure that everyone in the project is on the same package version. npm ci will help with this.

Setting Java heap space under Maven 2 on Windows

On the Mac: Instead of JAVA_OPTS and MAVEN_OPTS, use _JAVA_OPTIONS instead. This works!

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

Java, return if trimmed String in List contains String

You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
    if(str.trim().contains(search))
       return true;
}
return false;

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop
if(str.trim().toLowerCase().contains(search))

SimpleXml to string

Sometimes you can simply typecast:

// this is the value of my $xml
object(SimpleXMLElement)#10227 (1) {
  [0]=>
  string(2) "en"
}

$s = (string) $xml; // returns "en";

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I got similar error (org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15) while using aspectj 1.8.13. Solution was to align all compilation into jdk 8 and being careful not to put aspectj library's (1.6.13 for instance) other versions to buildpath/classpath.

Laravel assets url

You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

Ex. you can retrieve assets/images/image.png in your view as following:

<img src="{{asset('assets/images/image.png')}}">

Java method to swap primitives

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)

Why do we use web.xml?

It says all the requests to go through WicketFilter


Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level


This is what you need really, http://wicket.apache.org/learn/examples/helloworld.html

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

How to install plugins to Sublime Text 2 editor?

  1. Install the Package Manager as directed on https://packagecontrol.io/installation

  2. Open the Package Manager using Ctrl+Shift+P

  3. Type Package Control to show related commands (Install Package, Remove Package etc.) with packages

Enjoy it!

enter image description here

How can strip whitespaces in PHP's variable?

There are some special types of whitespace in the form of tags. You need to use

$str=strip_tags($str);

to remove redundant tags, error tags, to get to a normal string first.

And use

$str=preg_replace('/\s+/', '', $str);

It's work for me.

How to split a string in shell and get the last field

for x in `echo $str | tr ";" "\n"`; do echo $x; done

How to assign a heredoc value to a variable in Bash?

An array is a variable, so in that case mapfile will work

mapfile y <<'z'
abc'asdf"
$(dont-execute-this)
foo"bar"''
z

Then you can print like this

printf %s "${y[@]}"

Make div stay at bottom of page's content all the time even when there are scrollbars

I realise it says not to use this for 'responding to other answers' but unfortunately I don't have enough rep to add a comment onto the appropriate answer (!) but ...

If you are having problems in asp.net with the answer from 'My Head Hurts' - you need to add 'height : 100%' to the main generated FORM tag as well as HTML and BODY tags in order for this to work.

Convert string into integer in bash script - "Leading Zero" number error

In Short: In order to deal with "Leading Zero" numbers (any 0 digit that comes before the first non-zero) in bash - Use bc An arbitrary precision calculator language

Example:

a="000001"
b=$(echo $a | bc)
echo $b

Output: 1

From Bash manual:

"bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming lan- guage. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)"

Python __call__ special method practical example

The function call operator.

class Foo:
    def __call__(self, a, b, c):
        # do something

x = Foo()
x(1, 2, 3)

The __call__ method can be used to redefined/re-initialize the same object. It also facilitates the use of instances/objects of a class as functions by passing arguments to the objects.

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

UNIX export command

Unix

The commands env, set, and printenv display all environment variables and their values. env and set are also used to set environment variables and are often incorporated directly into the shell. printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.

In Unix, the following commands can also be used, but are often dependent on a certain shell.

export VARIABLE=value  # for Bourne, bash, and related shells
setenv VARIABLE value  # for csh and related shells

You can have a look at this at

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

Text border using css (border around text)

I don't like that much solutions based on multiplying text-shadows, it's not really flexible, it may work for a 2 pixels stroke where directions to add are 8, but with just 3 pixels stroke directions became 16, and so on... Not really confortable to manage.

The right tool exists, it's SVG <text> The browsers' support problem worth nothing in this case, 'cause the usage of text-shadow has its own support problem too, filter: progid:DXImageTransform can be used or IE < 10 but often doesn't work as expected.

To me the best solution remains SVG with a fallback in not-stroked text for older browser:

This kind of approuch works on pratically all versions of Chrome and Firefox, Safari since version 3.04, Opera 8, IE 9

Compared to text-shadow whose supports are: Chrome 4.0, FF 3.5, IE 10, Safari 4.0, Opera 9, it results even more compatible.

_x000D_
_x000D_
.stroke {_x000D_
  margin: 0;_x000D_
  font-family: arial;_x000D_
  font-size:70px;_x000D_
  font-weight: bold;_x000D_
  }_x000D_
  _x000D_
  svg {_x000D_
    display: block;_x000D_
  }_x000D_
  _x000D_
  text {_x000D_
    fill: black;_x000D_
    stroke: red;_x000D_
    stroke-width: 3;_x000D_
  }
_x000D_
<p class="stroke">_x000D_
  <svg xmlns="http://www.w3.org/2000/svg" width="700" height="72" viewBox="0 0 700 72">_x000D_
    <text x="0" y="70">Stroked text</text>_x000D_
  </svg>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to get all registered routes in Express?

Just use this npm package, it will give the web-output as well as terminal output in nice formatted table view.

enter image description here

https://www.npmjs.com/package/express-routes-catalogue

How do I add one month to current date in Java?

Java 8

LocalDate futureDate = LocalDate.now().plusMonths(1);

Append text to input field

_x000D_
_x000D_
 // Define appendVal by extending JQuery_x000D_
 $.fn.appendVal = function( TextToAppend ) {_x000D_
  return $(this).val(_x000D_
   $(this).val() + TextToAppend_x000D_
  );_x000D_
 };_x000D_
//______________________________________________x000D_
_x000D_
 // And that's how to use it:_x000D_
 $('#SomeID')_x000D_
  .appendVal( 'This text was just added' )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<textarea _x000D_
          id    =  "SomeID"_x000D_
          value =  "ValueText"_x000D_
          type  =  "text"_x000D_
>Current NodeText_x000D_
</textarea>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Well when creating this example I somehow got a little confused. "ValueText" vs >Current NodeText< Isn't .val() supposed to run on the data of the value attribute? Anyway I and you me may clear up this sooner or later.

However the point for now is:

When working with form data use .val().

When dealing with the mostly read only data in between the tag use .text() or .append() to append text.

Find the directory part (minus the filename) of a full path in access 97

You can do something simple like: Left(path, InStrRev(path, "\"))

Example:

Function GetDirectory(path)
   GetDirectory = Left(path, InStrRev(path, Application.PathSeparator))
End Function

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

SQL is null and = null

In SQL, a comparison between a null value and any other value (including another null) using a comparison operator (eg =, !=, <, etc) will result in a null, which is considered as false for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).

The reasoning is that a null means "unknown", so the result of any comparison to a null is also "unknown". So you'll get no hit on rows by coding where my_column = null.

SQL provides the special syntax for testing if a column is null, via is null and is not null, which is a special condition to test for a null (or not a null).

Here's some SQL showing a variety of conditions and and their effect as per above.

create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);

select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);

returns only 1 row (as expected):

TEST    X   Y
x = y   1   1

See this running on SQLFiddle

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Passing arguments to "make run"

for standard make you can pass arguments by defining macros like this

make run arg1=asdf

then use them like this

run: ./prog $(arg1)
   etc

References for make Microsoft's NMake

Escaping Double Quotes in Batch Script

The escape character in batch scripts is ^. But for double-quoted strings, double up the quotes:

"string with an embedded "" character"

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I +1'd Miro's answer for the link to the header-checker site http://www.webconfs.com/http-header-check.php. It pops up an obnoxious ad every time you use it, but it is, nevertheless, very useful for verifying the presence of the Access-Control-Allow-Origin header.

I'm reading a .json file from the javascript on my web page. I found that adding the following to my .htaccess file fixed the problem when viewing my web page in IE 11 (version 11.447.14393.0):

<FilesMatch "\.(json)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

I also added the following to /etc/httpd.conf (Apache's configuration file):

AllowOverride All

The header-checker site verified that the Access-Control-Allow-Origin header is now being sent (thanks, Miro!).

However, Firefox 50.0.2, Opera 41.0.2353.69, and Edge 38.14393.0.0 all fetch the file anyhow, even without the Access-Control-Allow-Origin header. (Note: they might be checking IP addresses, since the two domains I was using are both hosted on the same server, at the same IPv4 address.)

However, Chrome 54.0.2840.99 m (64-bit) ignores the Access-Control-Allow-Origin header and fails anyhow, erroneously reporting:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{mydomain}' is therefore not allowed access.

I think this has got to be some sort of "first." IE is working correctly; Chrome, Firefox, Opera and Edge are all buggy; and Chrome is the worst. Isn't that the exact opposite of the usual case?

Hibernate Group by Criteria Object

If you have to do group by using hibernate criteria use projections.groupPropery like the following,

@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
            .add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list(); 
return result;  

How to use MySQLdb with Python and Django in OSX 10.6?

Running Ubuntu, I had to do:

sudo apt-get install python-mysqldb

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

For those still having this issue, my issue was resolved in the AndroidManifest.xml file. Where it says <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar">, you need to remove NoActionBar, making it <activity android:name=".MainActivity" android:theme="@style/AppTheme">, because with NoActionBar set the app doesnt know whether or not it wants an action bar when you call one up inside of MainActivity.java

Finding an elements XPath using IE Developer tool

Are you trying to find some work around getting xpath in IE?

There are many add-ons for other browsers like xpather for Chrome or xpather, xpath-checker and firebug for FireFox that will give you the xpath of an element in a second. But sadly there is no add-on or tool available that will do this for IE. For most cases you can get the xpath of the elements that fall in your script using the above tools in Firefox and tweak them a little (if required) to make them work in IE.

But if you are testing an application that will work only in IE or the specific scenario or page that has this element will open-up/play-out only in IE then you cannot use any of the above mention tools to find the XPATH. Well the only thing that works in this case is the Bookmarklets that were coded just for this purpose. Bookmarklets are JavaScript code that you will add in IE as bookmarks and later use to get the XPATH of the element you desire. Using these you can get the XPATH as easily as you get using xpather or any other firefox addon.

STEPS TO INSTALL BOOKMARKLETS

1)Open IE

2)Type about:blank in the address bar and hit enter

3)From Favorites main menu select ---> Add favorites

4) In the Add a favorite popup window enter name GetXPATH1.

5)Click add button in the add a favorite popup window.

6)Open the Favorites menu and right click the newly added favorite and select properties option.

7)GetXPATH1 Properties will open up. Select the web Document Tab.

8)Enter the following in the URL field.

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

12)Enter the following in the URL field for GetXPATH2

javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();

13)Repeat Step 9.

You are all done!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At this point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

Vue.js: Conditional class style binding

Use the object syntax.

v-bind:class="{'fa-checkbox-marked': content['cravings'],  'fa-checkbox-blank-outline': !content['cravings']}"

When the object gets more complicated, extract it into a method.

v-bind:class="getClass()"

methods:{
    getClass(){
        return {
            'fa-checkbox-marked': this.content['cravings'],  
            'fa-checkbox-blank-outline': !this.content['cravings']}
    }
}

Finally, you could make this work for any content property like this.

v-bind:class="getClass('cravings')"

methods:{
  getClass(property){
    return {
      'fa-checkbox-marked': this.content[property],
      'fa-checkbox-blank-outline': !this.content[property]
    }
  }
}

html5 - canvas element - Multiple layers

You might also checkout http://www.concretejs.com which is a modern, lightweight, Html5 canvas framework that enables hit detection, layering, and lots of other peripheral things. You can do things like this:

var wrapper = new Concrete.Wrapper({
  width: 500,
  height: 300,
  container: el
});

var layer1 = new Concrete.Layer();
var layer2 = new Concrete.Layer();

wrapper.add(layer1).add(layer2);

// draw stuff
layer1.sceneCanvas.context.fillStyle = 'red';
layer1.sceneCanvas.context.fillRect(0, 0, 100, 100);

// reorder layers
layer1.moveUp();

// destroy a layer
layer1.destroy();

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

If you want a customized option then you should not rely on the default dialog provided by android for this action.

What you need to do instead is roll out your own. You will need to query the PackageManager on which packages handle the action you require and then based on the reply, you apply filtering and customized text.

Specifically, take a look at the method queryIntentActivities of the PackageManager class. You build the intent that would launch the default dialog (the ACTION_SEND intent), pass that to this method and you will receive a list of objects that contain info on the activities that can handle that intent. Using that, you can choose the ones you want.

Once you build your list of packages you want to present, you need to build your own list dialog (preferably an activity with the dialog theme) which will display that list.

One thing to note though is that it's very hard to make that custom dialog look like the default one. The problem is that the theme used in that dialog is an internal theme and cannot be used by your application. You can either try to make it as similar to the native one as you want or go for a completely custom look (many apps do that like the gallery app etc)

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

MySQL CURRENT_TIMESTAMP on create and on update

Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

I had the same question and I finally found the answer:

You need to handle BOTH the SelectionChanged event and the DropDownClosed like this:

In XAML:

<ComboBox Name="cmbSelect" SelectionChanged="ComboBox_SelectionChanged" DropDownClosed="ComboBox_DropDownClosed">
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
    <ComboBoxItem>3</ComboBoxItem>
</ComboBox>

In C#:

private bool handle = true;
private void ComboBox_DropDownClosed(object sender, EventArgs e) {
  if(handle)Handle();
  handle = true;
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
  ComboBox cmb = sender as ComboBox;
  handle = !cmb.IsDropDownOpen;
  Handle();
}

private void Handle() {
  switch (cmbSelect.SelectedItem.ToString().Split(new string[] { ": " }, StringSplitOptions.None).Last())
  { 
      case "1":
          //Handle for the first combobox
          break;
      case "2":
          //Handle for the second combobox
          break;
      case "3":
          //Handle for the third combobox
          break;
  }
}

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

Looping through dictionary object

One way is to loop through the keys of the dictionary, which I recommend:

foreach(int key in sp.Keys)
    dynamic value = sp[key];

Another way, is to loop through the dictionary as a sequence of pairs:

foreach(KeyValuePair<int, dynamic> pair in sp)
{
    int key = pair.Key;
    dynamic value = pair.Value;
}

I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x) helps you retrieve the items in ascending order of the key. Note that Dictionary uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.

Update (01 Dec 2016): replaced vars with actual types to make the answer more clear.

Add custom buttons on Slick Carousel

That's because they use an icon font for the buttons. They use "Slick" font as you can see in this image:

enter image description here

Basically, the make the letter "A" the form of an icon, the letter "B" the form of another one and so on.

For example:

enter image description here

If you want to know more about icon fonts click here

If you want to change the icons, you need to replace the whole button code or you can go to www.fontastic.me and create your own icon font. After that, replace the font file for the current one and you'll have your own icon.

Git update submodules recursively

In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:

git submodule update --recursive --remote --merge

You may add --init to initialize any uninitialized submodules and use --rebase if you want to rebase instead of merge.

You need to commit the changes afterwards:

git add . && git commit -m 'Update submodules to latest revisions'

How to SELECT the last 10 rows of an SQL table which has no ID field?

If you know how many rows to expect, I would create a separate temporary table in your database of the expected structure, append into that, then check the count... Once you are good with that, then you can massage that data before appending it into your final production table.

Could not autowire field in spring. why?

I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

Oracle get previous day records

I think you can also execute this command:

select (sysdate-1) PREVIOUS_DATE from dual;

Maximum number of threads in a .NET app?

Jeff Richter in CLR via C#:

"With version 2.0 of the CLR, the maximum number of worker threads default to 25 per CPU in the machine and the maximum number of I/O threads defaults to 1000. A limit of 1000 is effectively no limit at all."

Note this is based on .NET 2.0. This may have changed in .NET 3.5.

[Edit] As @Mitch pointed out, this is specific to the CLR ThreadPool. If you're creating threads directly see the @Mitch and others comments.

No notification sound when sending notification from firebase in android

In the notification payload of the notification there is a sound key.

From the official documentation its use is:

Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.

Eg:

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",

    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon",
      "sound" : "mySound"
    }
  }

If you want to use default sound of the device, you should use: "sound": "default".

See this link for all possible keys in the payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

For those who don't know firebase handles notifications differently when the app is in background. In this case the onMessageReceived function is not called.

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default. This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

"Line contains NULL byte" in CSV reader (Python)

I've solved a similar problem with an easier solution:

import codecs
csvReader = csv.reader(codecs.open('file.csv', 'rU', 'utf-16'))

The key was using the codecs module to open the file with the UTF-16 encoding, there are a lot more of encodings, check the documentation.

How to use Typescript with native ES6 Promises

As of TypeScript 2.0 you can include typings for native promises by including the following in your tsconfig.json

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

This will include the promise declarations that comes with TypeScript without having to set the target to ES6.

Run Command Prompt Commands

None of the above answers helped for some reason, it seems like they sweep errors under the rug and make troubleshooting one's command difficult. So I ended up going with something like this, maybe it will help someone else:

var proc = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = @"C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE\tf.exe",
        Arguments = "checkout AndroidManifest.xml",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        WorkingDirectory = @"C:\MyAndroidApp\"
    }
};

proc.Start();

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

react button onClick redirect page

Don't use a button as a link. Instead, use a link styled as a button.

<Link to="/signup" className="btn btn-primary">Sign up</Link>

Unzipping files in Python

import os 
zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
    x = zip_file_path+'\\'+a
    print x
    abs_path.append(x)
for f in abs_path:
    zip=zipfile.ZipFile(f)
    zip.extractall(zip_file_path)

This does not contain validation for the file if its not zip. If the folder contains non .zip file it will fail.