Programs & Examples On #Mpeg 4

MPEG-4 is an ISO/IEC standard for video and audio compression as a successor of MPEG-2. It has much more complex capabilities including arbitrary shaped videos and new ways of synthesis.

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

Downgrade npm to an older version

Just need to add version of which you want

upgrade or downgrade

npm install -g npm@version

Example if you want to downgrade from npm 5.6.0 to 4.6.1 then,

npm install -g [email protected]

It is tested on linux

How to get to a particular element in a List in java?

String[] is an array of Strings. Such an array is internally a class. Like all classes that don't explicitly extend some other class, it extends Object implicitly. The method toString() of class Object, by default, gives you the representation you see: the class name, followed by @, followed by the hash code in hex. Since the String[] class doesn't override the toString() method, you get that as a result.

Create some method that outputs the array elements for you. Iterate over the array and use System.out.print() (not print*ln*) on the elements.

How to access POST form fields

Security concern using express.bodyParser()

While all the other answers currently recommend using the express.bodyParser() middleware, this is actually a wrapper around the express.json(), express.urlencoded(), and express.multipart() middlewares (http://expressjs.com/api.html#bodyParser). The parsing of form request bodies is done by the express.urlencoded() middleware and is all that you need to expose your form data on req.body object.

Due to a security concern with how express.multipart()/connect.multipart() creates temporary files for all uploaded files (and are not garbage collected), it is now recommended not to use the express.bodyParser() wrapper but instead use only the middlewares you need.

Note: connect.bodyParser() will soon be updated to only include urlencoded and json when Connect 3.0 is released (which Express extends).


So in short, instead of ...

app.use(express.bodyParser());

...you should use

app.use(express.urlencoded());
app.use(express.json());      // if needed

and if/when you need to handle multipart forms (file uploads), use a third party library or middleware such as multiparty, busboy, dicer, etc.

extract the date part from DateTime in C#

DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.

code snippet

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

Android: How do I prevent the soft keyboard from pushing my view up?

These answers here didn't help me. So I tried this:

android:windowSoftInputMode="adjustResize"

This worked like a charm, Now the header of my app doesn't disappear. Its smoother.

How do I directly modify a Google Chrome Extension File? (.CRX)

I have read the other answers and found it important to note a few other things:

1.) For Mac users: When you click "Load unpacked extension...", the Library folder is by default hidden and (even if the Show Hidden files option is toggled on your Mac) it might not show up in Chrome's finder window.

2.) The sub folder containing the extension is a random alpha-numeric string named after the extension's ID, which can be found on Chrome's extension page if Developer flag is set to true. (Upper right hand checkbox on the extensions page)

MySQL DROP all tables, ignoring foreign keys

From http://www.devdaily.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys:

SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;

(Note that this answers how to disable foreign key checks in order to be able to drop the tables in arbitrary order. It does not answer how to automatically generate drop-table statements for all existing tables and execute them in a single script. Jean's answer does.)

How can I parse String to Int in an Angular expression?

I prefer to use an angular filter.

app.filter('num', function() {
    return function(input) {
      return parseInt(input, 10);
    };
});

then you can use this in the dom:

{{'10'|num}}

Here is a fiddle.

Hope this helped!

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

Select distinct using linq

Using morelinq you can use DistinctBy:

myList.DistinctBy(x => x.id);

Otherwise, you can use a group:

myList.GroupBy(x => x.id)
      .Select(g => g.First());

Set the value of an input field

The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute

<input type="text" name="text_box_1" placeholder="My Default Value" />

Laravel Eloquent groupBy() AND also return count of each group

Here is a more Laravel way to handle group by without the need to use raw statements.

$sources = $sources->where('age','>', 31)->groupBy('age');

$output = null;
foreach($sources as $key => $source) {
    foreach($source as $item) {
        //get each item in the group
    }
    $output[$key] = $source->count();
}

Jquery post, response in new window

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:

Example:

<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
  <input type="hidden" name="packing_slip" value="35592" />
  <input type="hidden" name="reference" value="0018439" />
  <input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>

Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

What’s the best RESTful method to return total number of items in an object?

You could consider counts as a resource. The URL would then be:

/api/counts/member

How can I get a count of the total number of digits in a number?

Assuming your question was referring to an int, the following works for negative/positive and zero as well:

Math.Floor((decimal) Math.Abs(n)).ToString().Length

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

You can either remove E_STRICT from error_reporting(), or you can simply make your method static, if you need to call it statically. As far as I know, there is no (strict) way to have a method that can be invoked both as static and non-static method. Also, which is more annoying, you cannot have two methods with the same name, one being static and the other non-static.

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

How to get cookie's expire time

To get cookies expire time, use this simple method.

<?php

//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;

//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);

//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){

    return ($sec / 60 / 60 / 24);

}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){

    echo "Cookie is set<br />";
    if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
        echo "Cookie will expire today.";
    }else{
        echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
    }

}else{
    echo "not set...";
}

?>

You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

Return single column from a multi-dimensional array

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 

Creating a search form in PHP to search a database?

You're getting errors 'table liam does not exist' because the table's name is Liam which is not the same as liam. MySQL table names are case sensitive.

How can I clear the terminal in Visual Studio Code?

You can change from settings menu (at least from version 1.30.2 and above)...

On Mac, just hit Code > Preferences > Settings.

Then just search for "clear" and check Clear Previous Output.

Settings - Clear Previous Output

Multiple distinct pages in one HTML file

Let's say you have multiple pages, with id #page1 #page2 and #page3. #page1 is the ID of your start page. The first thing you want to do is to redirect to your start page each time the webpage is loading. You do this with javascript:

document.location.hash = "#page1";

Then the next thing you want to do is place some links in your document to the different pages, like for example:

<a href="#page2">Click here to get to page 2.</a>

Then, lastly, you'd want to make sure that only the active page, or target-page is visible, and all other pages stay hidden. You do this with the following declarations in the <style> element:

<style>
#page1 {display:none}
#page1:target {display:block}
#page2 {display:none}
#page2:target {display:block}
#page3 {display:none}
#page3:target {display:block}
</style>

How do I invoke a Java method when given the method name as a string?

I do this like this:

try {
    YourClass yourClass = new YourClass();
    Method method = YourClass.class.getMethod("yourMethodName", ParameterOfThisMethod.class);
    method.invoke(yourClass, parameter);
} catch (Exception e) {
    e.printStackTrace();
}

Controller not a function, got undefined, while defining controllers globally

Really great advise, except that the SAME error CAN occur simply by missing the critical script include on your root page

example:

page: index.html

   np-app="saleApp"

Missing

<script src="./ordersController.js"></script>

When a Route is told what controller and view to serve up:

 .when('/orders/:customerId', {
     controller: 'OrdersController',
     templateUrl: 'views/orders.html'
 })

So essential the undefined controller issue CAN occur in this accidental mistake of not even referencing the controller!

Is there a real solution to debug cordova apps

If you can use an Android 4.4+ device, then you can use Chrome Remote Debugging even on the app's internal WebView. It's a much better debugger than Weinre, but the key is using the recent Android version.

Recent Cordova builds automatically enable this kind of debugging as long as it's a debug build (it's turned off in --release builds).

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

Create a mocked list by mockito

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

How to assign a value to a TensorFlow variable?

Use Tensorflow eager execution mode which is latest.

import tensorflow as tf
tf.enable_eager_execution()
my_int_variable = tf.get_variable("my_int_variable", [1, 2, 3])
print(my_int_variable)

Regular expression to stop at first match

import regex
text = 'ask her to call Mary back when she comes back'                           
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
    print (match.group(1))

Output: Mary

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

52e 1326 ERROR_LOGON_FAILURE Returns when username is valid but password/credential is invalid. Will prevent most other errors from being displayed as noted.

http://ldapwiki.com/wiki/Common%20Active%20Directory%20Bind%20Errors

PHP cURL, extract an XML response

no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it's up to you what to do with it.

use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML: http://php.net/domxml

What is the http-header "X-XSS-Protection"?

X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting

   X-XSS-Protection: 0

See also http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx

Install Visual Studio 2013 on Windows 7

Visual Studio 2013 System Requirements

Supported Operating Systems:

  • Windows 8.1 (x86 and x64)
  • Windows 8 (x86 and x64)
  • Windows 7 SP1 (x86 and x64)
  • Windows Server 2012 R2 (x64)
  • Windows Server 2012 (x64)
  • Windows Server 2008 R2 SP1 (x64)

Hardware requirements:

  • 1.6 GHz or faster processor
  • 1 GB of RAM (1.5 GB if running on a virtual machine)
  • 20 GB of available hard disk space
  • 5400 RPM hard disk drive
  • DirectX 9-capable video card that runs at 1024 x 768 or higher display resolution

Additional Requirements for the laptop:

  • Internet Explorer 10
  • KB2883200 (available through Windows Update) is required

And don't forget to reboot after updating your windows

Exiting out of a FOR loop in a batch file?

As jeb noted, the rest of the loop is skipped but evaluated, which makes the FOR solution too slow for this purpose. An alternative:

set F=1
:nextpart
if not exist "%F%" goto :EOF
echo %F%
set /a F=%F%+1
goto nextpart

You might need to use delayed expansion and call subroutines when using this in loops.

Saving image from PHP URL

$img_file='http://www.somedomain.com/someimage.jpg'

$img_file=file_get_contents($img_file);

$file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';

$file_handler=fopen($file_loc,'w');

if(fwrite($file_handler,$img_file)==false){
    echo 'error';
}

fclose($file_handler);

Java Reflection Performance

"Significant" is entirely dependent on context.

If you're using reflection to create a single handler object based on some configuration file, and then spending the rest of your time running database queries, then it's insignificant. If you're creating large numbers of objects via reflection in a tight loop, then yes, it's significant.

In general, design flexibility (where needed!) should drive your use of reflection, not performance. However, to determine whether performance is an issue, you need to profile rather than get arbitrary responses from a discussion forum.

Setting a spinner onClickListener() in Android

Here is a working solution:

Instead of setting the spinner's OnClickListener, we are setting OnTouchListener and OnKeyListener.

spinner.setOnTouchListener(Spinner_OnTouch);
spinner.setOnKeyListener(Spinner_OnKey);

and the listeners:

private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            doWhatYouWantHere();
        }
        return true;
    }
};
private static View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            doWhatYouWantHere();
            return true;
        } else {
            return false;
        }
    }
};

Run text file as commands in Bash

cat /path/* | bash

OR

cat commands.txt | bash

How to know the git username and email saved during configuration?

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

Hide all warnings in ipython

For jupyter lab this should work (@Alasja)

from IPython.display import HTML
HTML('''<script>
var code_show_err = false; 
var code_toggle_err = function() {
 var stderrNodes = document.querySelectorAll('[data-mime-type="application/vnd.jupyter.stderr"]')
 var stderr = Array.from(stderrNodes)
 if (code_show_err){
     stderr.forEach(ele => ele.style.display = 'block');
 } else {
     stderr.forEach(ele => ele.style.display = 'none');
 }
 code_show_err = !code_show_err
} 
document.addEventListener('DOMContentLoaded', code_toggle_err);
</script>
To toggle on/off output_stderr, click <a onclick="javascript:code_toggle_err()">here</a>.''')

What does the "More Columns than Column Names" error mean?

you have have strange characters in your heading # % -- or ,

How to overcome the CORS issue in ReactJS

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

Right way to split an std::string into a vector<string>

You can use getline with delimiter:

string s, tmp; 
stringstream ss(s);
vector<string> words;

while(getline(ss, tmp, ',')){
    words.push_back(tmp);
    .....
}

How to capitalize the first letter of word in a string using Java?

if you only want to capitalize the first letter then the below code can be used

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Check number of arguments passed to a Bash script

There is a lot of good information here, but I wanted to add a simple snippet that I find useful.

How does it differ from some above?

  • Prints usage to stderr, which is more proper than printing to stdout
  • Return with exit code mentioned in this other answer
  • Does not make it into a one liner...
_usage(){
    _echoerr "Usage: $0 <args>"
}

_echoerr(){
    echo "$*" >&2
}

if [ "$#" -eq 0 ]; then # NOTE: May need to customize this conditional
    _usage
    exit 2
fi
main "$@"

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

There's an excellent plugin called ApplySyntax (previously DetectSyntax) that provides certain other niceties for file-syntax matching. allows regex expressions etc.

how to set default culture info for entire c# application

If you use a Language Resource file to set the labels in your application you need to set the its value:

CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

You can use json_decode(Your variable Name):

json_decode($result)

I was getting value from Model.where a column has value like this way

{"dayList":[
            {"day":[1,2,3,4],"time":[{"in_time":"10:00"},{"late_time":"15:00"},{"out_time":"16:15"}]
             },
             {"day":[5,6,7],"time":[{"in_time":"10:00"},{"late_time":"15:00"},{"out_time":"16:15"}]}
           ]
}

so access this value form model. you have to use this code.

$dayTimeListObject = json_decode($settingAttendance->bio_attendance_day_time,1);

 foreach ( $dayTimeListObject['dayList'] as $dayListArr)
 {
     foreach ( $dayListArr['day'] as $dayIndex)
     {
         if( $dayIndex == Date('w',strtotime('2020-02-11')))
         {
             $dayTimeList= $dayListArr['time'];
         }
     }
 }

 return $dayTimeList[2]['out_time'] ;

You can also define caste in your Model file.

 protected $casts = [
    'your-column-name' => 'json'
  ];

so after this no need of this line .

$dayTimeListObject = json_decode($settingAttendance->bio_attendance_day_time,1);

you can directly access this code.

$settingAttendance->bio_attendance_day_time

How to resolve 'unrecognized selector sent to instance'?

A lot of people have given some very technical answers for this and similar questions, but I think it's simpler than that. Sometimes if you're not paying attention a selector that you don't intend to use can be attached to something in the interface. You might be getting this error because the selector's there but you haven't written any code for it.

The easiest way to double-check that this is not the case is to control-click the item so you can see all of the selectors that are associated with it. If there's anything in there that you don't want to be, get rid of it! Hope this helps...

How to format a number 0..9 to display with 2 digits (it's NOT a date)

You can use this:

NumberFormat formatter = new DecimalFormat("00");  
String s = formatter.format(1); // ----> 01

Using Tempdata in ASP.NET MVC - Best practice

Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek method. I would recommend reading this cool article:

MVC Tempdata , Peek and Keep confusion

Generating 8-character only UUIDs

I do not think that it is possible but you have a good workaround.

  1. cut the end of your UUID using substring()
  2. use code new Random(System.currentTimeMillis()).nextInt(99999999); this will generate random ID up to 8 characters long.
  3. generate alphanumeric id:

    char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
    Random r = new Random(System.currentTimeMillis());
    char[] id = new char[8];
    for (int i = 0;  i < 8;  i++) {
        id[i] = chars[r.nextInt(chars.length)];
    }
    return new String(id);
    

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

AngularJS : Why ng-bind is better than {{}} in angular?

Visibility:

While your angularjs is bootstrapping, the user might see your placed brackets in the html. This can be handled with ng-cloak. But for me this is a workaround, that I don't need to use, if I use ng-bind.


Performance:

The {{}} is much slower.

This ng-bind is a directive and will place a watcher on the passed variable. So the ng-bind will only apply, when the passed value does actually change.

The brackets on the other hand will be dirty checked and refreshed in every $digest, even if it's not necessary.


I am currently building a big single page app (~500 bindings per view). Changing from {{}} to strict ng-bind did save us about 20% in every scope.$digest.


Suggestion:

If you use a translation module such as angular-translate, always prefer directives before brackets annotation.

{{'WELCOME'|translate}} => <span ng-translate="WELCOME"></span>

If you need a filter function, better go for a directive, that actually just uses your custom filter. Documentation for $filter service


UPDATE 28.11.2014 (but maybe off the topic):

In Angular 1.3x the bindonce functionality was introduced. Therefore you can bind the value of an expression/attribute once (will be bound when != 'undefined').

This is useful when you don't expect your binding to change.

Usage: Place :: before your binding:

<ul>  
  <li ng-repeat="item in ::items">{{item}}</li>
</ul>  
<a-directive name="::item">
<span data-ng-bind="::value"></span>

Example:

ng-repeat to output some data in the table, with multiple bindings per row. Translation-bindings, filter outputs, which get executed in every scope digest.

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

If you have a view with multiple constrains, a much easier way without having to create multiple outlets would be:

In interface builder, give each constraint you wish to modify an identifier:

enter image description here

Then in code you can modify multiple constraints like so:

for constraint in self.view.constraints {
    if constraint.identifier == "myConstraint" {
       constraint.constant = 50
    }
}
myView.layoutIfNeeded()

You can give multiple constrains the same identifier thus allowing you to group together constrains and modify all at once.

How to do jquery code AFTER page loading?

write the code that you want to be executed inside this. When your document is ready, this will be executed.

$(document).ready(function() { 

});

Why does ANT tell me that JAVA_HOME is wrong when it is not?

FYI, I am using Windows 7 and had to restart Windows in order for the new JAVA_HOME setting to take effect.

ng-repeat finish event

i would like to add another answer, since the preceding answers takes it that the code needed to run after the ngRepeat is done is an angular code, which in that case all answers above give a great and simple solution, some more generic than others, and in case its important the digest life cycle stage you can take a look at Ben Nadel's blog about it, with the exception of using $parse instead of $eval.

but in my experience, as the OP states, its usually running some JQuery plugins or methods on the finnaly compiled DOM, which in that case i found that the most simple solution is to create a directive with a setTimeout, since the setTimeout function gets pushed to the end of the queue of the browser, its always right after everything is done in angular, usually ngReapet which continues after its parents postLinking function

angular.module('myApp', [])
.directive('pluginNameOrWhatever', function() {
  return function(scope, element, attrs) {        
    setTimeout(function doWork(){
      //jquery code and plugins
    }, 0);        
  };
});

for whoever wondering that in that case why not to use $timeout, its that it causes another digest cycle that is completely unnecessary

Android SDK Setup under Windows 7 Pro 64 bit

You can just push back and push next again, and it installs OK.

Magento - How to add/remove links on my account navigation?

Its work 100% i am Sure.

Step 1: Go To ( YourTemplate/customer/account/navigation.phtml )

Step 2: Replace This Line: <?php $_count = count($_links); ?> With:

<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
unset($_links['account']); /* Account Info */     
unset($_links['account_edit']); /* Account Info */            
unset($_links['tags']); /* My Tags */
unset($_links['invitations']); /* My Invitations */
unset($_links['reviews']);  /* Reviews */
unset($_links['wishlist']); /* Wishlist */
unset($_links['newsletter']); /* Newsletter */
unset($_links['orders']); /* My Orders */
unset($_links['address_book']); /* Address */
unset($_links['enterprise_customerbalance']); /* Store Credit */
unset($_links['OAuth Customer Tokens']); /* My Applications */
unset($_links['enterprise_reward']); /* Reward Points */
unset($_links['giftregistry']); /* Gift Registry */
unset($_links['downloadable_products']); /* My Downloadable Products */
unset($_links['recurring_profiles']); /* Recurring Profiles */
unset($_links['billing_agreements']); /* Billing Agreements */
unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */

?>

Accessing a class' member variables in Python?

Implement the return statement like the example below! You should be good. I hope it helps someone..

class Example(object):
    def the_example(self):
        itsProblem = "problem"
        return itsProblem 


theExample = Example()
print theExample.the_example()

__init__() missing 1 required positional argument

If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'

Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)

What is the equivalent of Java's System.out.println() in Javascript?

You can always simply add an alert() prompt anywhere in a function. Especially useful for knowing if a function was called, if a function completed or where a function fails.

alert('start of function x');
alert('end of function y');
alert('about to call function a');
alert('returned from function b');

You get the idea.

App can't be opened because it is from an unidentified developer

Right-click (or control-click) the application in question and choose "Open"

JavaScript implementation of Gzip

Edit There appears to be a better LZW solution that handles Unicode strings correctly at http://pieroxy.net/blog/pages/lz-string/index.html (Thanks to pieroxy in the comments).


I don't know of any gzip implementations, but the jsolait library (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the LGPL.

// LZW-compress a string
function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict[phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            dict[phrase + currChar] = code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
}

// Decompress an LZW-encoded string
function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

How to verify a Text present in the loaded page through WebDriver

Note: Not in boolean

WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");

if(driver.getPageSource().contains("Ur message"))
  {
    System.out.println("Pass");
  }
else
  {
    System.out.println("Fail");
  }

Foreign key referring to primary keys across multiple tables?

Yes, it is possible. You will need to define 2 FKs for 3rd table. Each FK pointing to the required field(s) of one table (ie 1 FK per foreign table).

How to delete a record in Django models?

MyModel.objects.get(pk=1).delete()

this will raise exception if the object with specified primary key doesn't exist because at first it tries to retrieve the specified object.

MyModel.objects.filter(pk=1).delete()

this wont raise exception if the object with specified primary key doesn't exist and it directly produces the query

DELETE FROM my_models where id=1

How can I Remove .DS_Store files from a Git repository?

Remove ignored files:

(.DS_Store)

$ find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

How do you get the cursor position in a textarea?

Here is code to get line number and column position

function getLineNumber(tArea) {

    return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}

function getCursorPos() {
    var me = $("textarea[name='documenttext']")[0];
    var el = $(me).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    var ret = pos - prevLine(me);
    alert(ret);

    return ret; 
}

function prevLine(me) {
    var lineArr = me.value.substr(0, me.selectionStart).split("\n");

    var numChars = 0;

    for (var i = 0; i < lineArr.length-1; i++) {
        numChars += lineArr[i].length+1;
    }

    return numChars;
}

tArea is the text area DOM element

A simple jQuery form validation script

you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

<script type="text/javascript">
$(document).ready(function(){
    $("#formID").validate({
    rules :{
        "data[User][name]" : {
            required : true
        }
    },
    messages :{
        "data[User][name]" : {
            required : 'Enter username'
        }
    }
    });
});
</script>

You can see required : true same there is many more property like for email you can define email : true for number number : true

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

remove None value from a list without removing the 0 value

from operator import is_not
from functools import partial   

filter_null = partial(filter, partial(is_not, None))

# A test case
L = [1, None, 2, None, 3]
L = list(filter_null(L))

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

Import CSV file with mixed data types

Use xlsread, it works just as well on .csv files as it does on .xls files. Specify that you want three outputs:

[num char raw] = xlsread('your_filename.csv')

and it will give you an array containing only the numeric data (num), an array containing only the character data (char) and an array that contains all data types in the same format as the .csv layout (raw).

Why is it OK to return a 'vector' from a function?

This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.

The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.

On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.

So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.

Regex: matching up to the first occurrence of a character

Try /[^;]*/

Google regex character classes for details.

How to update UI from another thread running in another class

Felt the need to add this better answer, as nothing except BackgroundWorker seemed to help me, and the answer dealing with that thus far was woefully incomplete. This is how you would update a XAML page called MainWindow that has an Image tag like this:

<Image Name="imgNtwkInd" Source="Images/network_on.jpg" Width="50" />

with a BackgroundWorker process to show if you are connected to the network or not:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

public partial class MainWindow : Window
{
    private BackgroundWorker bw = new BackgroundWorker();

    public MainWindow()
    {
        InitializeComponent();

        // Set up background worker to allow progress reporting and cancellation
        bw.WorkerReportsProgress = true;
        bw.WorkerSupportsCancellation = true;

        // This is your main work process that records progress
        bw.DoWork += new DoWorkEventHandler(SomeClass.DoWork);

        // This will update your page based on that progress
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

        // This starts your background worker and "DoWork()"
        bw.RunWorkerAsync();

        // When this page closes, this will run and cancel your background worker
        this.Closing += new CancelEventHandler(Page_Unload);
    }

    private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        BitmapImage bImg = new BitmapImage();
        bool connected = false;
        string response = e.ProgressPercentage.ToString(); // will either be 1 or 0 for true/false -- this is the result recorded in DoWork()

        if (response == "1")
            connected = true;

        // Do something with the result we got
        if (!connected)
        {
            bImg.BeginInit();
            bImg.UriSource = new Uri("Images/network_off.jpg", UriKind.Relative);
            bImg.EndInit();
            imgNtwkInd.Source = bImg;
        }
        else
        {
            bImg.BeginInit();
            bImg.UriSource = new Uri("Images/network_on.jpg", UriKind.Relative);
            bImg.EndInit();
            imgNtwkInd.Source = bImg;
        }
    }

    private void Page_Unload(object sender, CancelEventArgs e)
    {
        bw.CancelAsync();  // stops the background worker when unloading the page
    }
}


public class SomeClass
{
    public static bool connected = false;

    public void DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker bw = sender as BackgroundWorker;

        int i = 0;
        do 
        {
            connected = CheckConn();  // do some task and get the result

            if (bw.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                Thread.Sleep(1000);
                // Record your result here
                if (connected)
                    bw.ReportProgress(1);
                else
                    bw.ReportProgress(0);
            }
        }
        while (i == 0);
    }

    private static bool CheckConn()
    {
        bool conn = false;
        Ping png = new Ping();
        string host = "SomeComputerNameHere";

        try
        {
            PingReply pngReply = png.Send(host);
            if (pngReply.Status == IPStatus.Success)
                conn = true;
        }
        catch (PingException ex)
        {
            // write exception to log
        }
        return conn;
    }
}

For more information: https://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx

Use of Greater Than Symbol in XML

Use &gt; and &lt; for 'greater-than' and 'less-than' respectively

What does Ruby have that Python doesn't, and vice versa?

I would like to mention Python descriptor API that allows one customize object-to-attribute "communication". It is also noteworthy that, in Python, one is free to implement an alternative protocol via overriding the default given through the default implementation of the __getattribute__ method. Let me give more details about the aforementioned. Descriptors are regular classes with __get__, __set__ and/or __delete__ methods. When interpreter encounters something like anObj.anAttr, the following is performed:

  • __getattribute__ method of anObj is invoked
  • __getattribute__ retrieves anAttr object from the class dict
  • it checks whether abAttr object has __get__, __set__ or __delete__ callable objects
  • the context (i.e., caller object or class, and value, instead of the latter, if we have setter) is passed to the callable object
  • the result is returned.

As was mentioned, this is the default behavior. One is free to change the protocol by re-implementing __getattribute__.

This technique is lot more powerful than decorators.

How to increase icons size on Android Home Screen?

If you want to change settings in the launcher, change icon size, or grid size just hold down on an empty part of your home screen. Tap the three Dots and there you go.

From https://forums.oneplus.net/threads/how-to-change-icon-and-grid-size-trebuchet-settings.84820/

When configuring the phone for first time I saw something about a grid somewhere, but couldn't find it again. Luckily I found the answer on the link above.

How to specify the bottom border of a <tr>?

tr td 
{
    border-bottom: 2px solid silver;
}

or if you want the border inside the TR tag, you can do this:

tr td {
    box-shadow: inset 0px -2px 0px silver;
}

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Just to document my trouble with this issue even though it just appears to be a specific example of other answers; as a relative newbie I feel like this might help others.

Solution:

I added '/usr/bin' to the beginning of PATH for a single session using PATH='/usr/path/:$PATH' and everything started to work fine.

I used gedit to update the PATH permanently, after ensuring it wouldn't break my regular toolchains.

Explanation:

I have multiple toolchains installed on Ubuntu 14.04LTS and I use just a couple on a regular basis. When I tried to use gcc from the command line I got the issue describe by the OP. '/usr/bin' is in the PATH but it is behind the other toolchain locations. Turns out the cc1 for those other toolchains is incompatible with gcc.

Child element click event trigger the parent click event

I faced the same problem and solve it by this method. html :

<div id="parentDiv">
   <div id="childDiv">
     AAA
   </div>
    BBBB
</div>

JS:

$(document).ready(function(){
 $("#parentDiv").click(function(e){
   if(e.target.id=="childDiv"){
     childEvent();
   } else {
     parentEvent();
   }
 });
});

function childEvent(){
    alert("child event");
}

function parentEvent(){
    alert("paren event");
}

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

Finding the average of a list

In terms of efficiency and speed, these are the results that I got testing the other answers:

# test mean caculation

import timeit
import statistics
import numpy as np
from functools import reduce
import pandas as pd

LIST_RANGE = 10000000000
NUMBERS_OF_TIMES_TO_TEST = 10000

l = list(range(10))

def mean1():
    return statistics.mean(l)


def mean2():
    return sum(l) / len(l)


def mean3():
    return np.mean(l)


def mean4():
    return np.array(l).mean()


def mean5():
    return reduce(lambda x, y: x + y / float(len(l)), l, 0)

def mean6():
    return pd.Series(l).mean()



for func in [mean1, mean2, mean3, mean4, mean5, mean6]:
    print(f"{func.__name__} took: ",  timeit.timeit(stmt=func, number=NUMBERS_OF_TIMES_TO_TEST))

and the results:

mean1 took:  0.17030245899968577
mean2 took:  0.002183011999932205
mean3 took:  0.09744236000005913
mean4 took:  0.07070840100004716
mean5 took:  0.022754742999950395
mean6 took:  1.6689282460001778

so clearly the winner is: sum(l) / len(l)

Finding all possible permutations of a given string in python

why do you not simple do:

from itertools import permutations
perms = [''.join(p) for p in permutations(['s','t','a','c','k'])]
print perms
print len(perms)
print len(set(perms))

you get no duplicate as you can see :

 ['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc', 
'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta',
 'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack', 
'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks', 
'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac', 
'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt', 
'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk', 
'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs', 
'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak', 
'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks', 
'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac', 
'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs', 
'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta', 
'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats']
    120
    120
    [Finished in 0.3s]

UIButton Image + Text IOS

Make UIImageView and UILabel, and set image and text to both of this....then Place a custom button over imageView and Label....

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.png"]];
    imageView.frame = CGRectMake(x, y, imageView.frame.size.width, imageView.frame.size.height);
    [self.view addSubview:imageView];

UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y,a,b)];
yourLabel.text = @"raj";
[self.view addSubview:yourLabel];

UIButton * yourBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setFrame:CGRectMake(x, y,c,d)];
[yourBtn addTarget:self action:@selector(@"Your Action") forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];  

How to find all positions of the maximum value in a list?

Here is the max value and the indexes it appears at:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> for i, x in enumerate(a):
...     d[x].append(i)
... 
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]

Later: for the satisfaction of @SilentGhost

>>> from itertools import takewhile
>>> import heapq
>>> 
>>> def popper(heap):
...     while heap:
...         yield heapq.heappop(heap)
... 
>>> a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>> 
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]

How to download and save an image in Android

As Google tells, for now, don't forget to add also readable on external storage in the manifest :

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Source : http://developer.android.com/training/basics/data-storage/files.html#GetWritePermission

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

How to get error message when ifstream open fails

The std::system_error example above is slightly incorrect. std::system_category() will map the error codes from system's native error code facility. For *nix, this is errno. For Win32, it is GetLastError(). ie, on Windows, the above example will print

failed to open C:\path\to\forbidden: The data is invalid

because EACCES is 13 which is the Win32 error code ERROR_INVALID_DATA

To fix it, either use the system's native error code facility, eg on Win32

throw new std::system_error(GetLastError(), std::system_category(), "failed to open"+ filename);

Or use errno and std::generic_category(), eg

throw new std::system_error(errno, std::generic_category(), "failed to open"+ filename);

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

Convert a video to MP4 (H.264/AAC) with ffmpeg

http://handbrake.fr is a nice high level tool with a lot of useful presets for mp4 for iPod, PS3, ... with both GUI and CLI interfaces for Linux, Windows and Mac OS X.

It comes with its own dependencies as a single statically linked fat binary so you have all the x264 / aac codecs included.

  $ HandBrakeCLI -Z Universal -i myinputfile.mov -o myoutputfile.mp4

To list all the available presets:

  $ HandBrakeCLI -z

Determining if Swift dictionary contains key and obtaining any of its values

Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

Changing capitalization of filenames in Git

This Python snippet will git mv --force all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force.

Modify it to your liking. I just figured I'd share :)

import os
import re

searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)

for root, dirs, files in os.walk(searchDir):
    dirs[:] = [d for d in dirs if d not in exclude]
    for f in files:
        if re.match(r'[A-Z]', f):
            fullPath = os.path.join(root, f)
            fullPathLower = os.path.join(root, f[0].lower() + f[1:])
            command = 'git mv --force ' + fullPath + ' ' + fullPathLower
            print(command)
            os.system(command)

Map implementation with duplicate keys

This problem can be solved with a list of map entry List<Map.Entry<K,V>>. We don't need to use neither external libraries nor new implementation of Map. A map entry can be created like this: Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<String, Integer>("key", 1);

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

Set Focus After Last Character in Text Box

<script type="text/javascript">
    $(function(){
        $('#areaCode,#firstNum,#secNum').keyup(function(e){
            if($(this).val().length==$(this).attr('maxlength'))
                $(this).next(':input').focus()
        })
    })
    </script>

<body>

<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />- 
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />- 
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />

</body>

How to unstash only certain files?

If you git stash pop (with no conflicts) it will remove the stash after it is applied. But if you git stash apply it will apply the patch without removing it from the stash list. Then you can revert the unwanted changes with git checkout -- files...

Is there any "font smoothing" in Google Chrome?

I had the same problem, and I found the solution in this post of Sam Goddard,

The solution if to defined the call to the font twice. First as it is recommended, to be used for all the browsers, and after a particular call only for Chrome with a special media query:

@font-face {
  font-family: 'chunk-webfont';
  src: url('../../includes/fonts/chunk-webfont.eot');
  src: url('../../includes/fonts/chunk-webfont.eot?#iefix') format('eot'),
  url('../../includes/fonts/chunk-webfont.woff') format('woff'),
  url('../../includes/fonts/chunk-webfont.ttf') format('truetype'),
  url('../../includes/fonts/chunk-webfont.svg') format('svg');
  font-weight: normal;
  font-style: normal;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: 'chunk-webfont';
    src: url('../../includes/fonts/chunk-webfont.svg') format('svg');
  }
}

enter image description here

With this method the font will render good in all browsers. The only negative point that I found is that the font file is also downloaded twice.

You can find an spanish version of this article in my page

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

The "pre" and "post" nature of increment and decrement operators can tend to be confusing for those who are not familiar with them; that's one way in which they can be tricky.

What does "Use of unassigned local variable" mean?

There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.

Specifically, you are not validating the user input for creditPlan - if the user enters a value of anything else than "0","1","2" or "3", then none of the branches indicated will be executed (and creditPlan will not be defaulted to zero as per your user prompt).

As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else statement).

I would however like to point out other potential improvements:

  • Validate user input before you trust it for use in your code.
  • Model the parameters as a whole - there are several properties and calculations applicable to each plan.
  • Use more appropriate types for data. e.g. CreditPlan appears to have a finite domain and is better suited to an enumeration or Dictionary than a string. Financial data and percentages should always be modelled as decimal, not double to avoid rounding issues, and 'status' appears to be a boolean.
  • DRY up repetitive code. The calculation, monthlyCharge = balance * annualRate * (1/12)) is common to more than one branch. For maintenance reasons, do not duplicate this code.
  • Possibly more advanced, but note that Functions are now first class citizens of C#, so you can assign a function or lambda as a property, field or parameter!.

e.g. here is an alternative representation of your model:

    // Keep all Credit Plan parameters together in a model
    public class CreditPlan
    {
        public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
        public decimal AnnualRate { get; set; }
        public Func<bool, Decimal> LateFee { get; set; }
    }

    // DRY up repeated calculations
    static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
    { 
       return balance * annualRate / 12;
    }

    public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
    {
        { 0, new CreditPlan
            {
                AnnualRate = .35M, 
                LateFee = _ => 0.0M, 
                MonthlyCharge = StandardMonthlyCharge
            }
        },
        { 1, new CreditPlan
            {
                AnnualRate = .30M, 
                LateFee = late => late ? 0 : 25.0M,
                MonthlyCharge = StandardMonthlyCharge
            }
        },
        { 2, new CreditPlan
            {
                AnnualRate = .20M, 
                LateFee = late => late ? 0 : 35.0M,
                MonthlyCharge = (balance, annualRate) => balance > 100 
                    ? balance * annualRate / 12
                    : 0
            }
        },
        { 3, new CreditPlan
            {
                AnnualRate = .15M, 
                LateFee = _ => 0.0M,
                MonthlyCharge = (balance, annualRate) => balance > 500 
                    ? (balance - 500) * annualRate / 12
                    : 0
            }
        }
    };

DateTimePicker time picker in 24 hour but displaying in 12hr?

I know it's been quite some time since the question was asked. However, if it helps anyone this worked for me.

 $(function() {
    $('.datetimepicker').datetimepicker({
        format: 'MM-DD-YYYY HH:mm '
    });
});

How to get all columns' names for all the tables in MySQL?

Similar to the answer posted by @suganya this doesn't directly answer the question but is a quicker alternative for a single table:

DESCRIBE column_name;

If/else else if in Jquery for a condition

A few more things in addition to the existing answers. Have a look at this:

var seatsValid = true;
// cache the selector
var seatsVal = $("#seats").val();
if(seatsVal!=''){
    seatsValid = false;
    alert("Not a valid character")
    // convert seatsVal to an integer for comparison
}else if(parseInt(seatsVal) < 99999){
    seatsValid = false;
    alert("Not a valid Number");
}

The variable name setFlag is very generic, if your only using it in conjunction with the number of seats you should rename it (I called it seatsValid). I also initialized it to true which gets rid of the need for the final else in your original code. Next, I put the selector and call to .val() in a variable. It's good practice to cache your selectors so jquery doesn't need to traverse the DOM more than it needs to. Lastly when comparing two values you should try to make sure they are the same type, in this case seatsVal is a string so in order to properly compare it to 99999 you should use parseInt() on it.

Simpler way to check if variable is not equal to multiple string values?

For your first code, you can use a short alteration of the answer given by @ShankarDamodaran using in_array():

if ( !in_array($some_variable, array('uk','in'), true ) ) {

or even shorter with [] notation available since php 5.4 as pointed out by @Forty in the comments

if ( !in_array($some_variable, ['uk','in'], true ) ) {

is the same as:

if ( $some_variable !== 'uk' && $some_variable !== 'in' ) {

... but shorter. Especially if you compare more than just 'uk' and 'in'. I do not use an additional variable (Shankar used $os) but instead define the array in the if statement. Some might find that dirty, i find it quick and neat :D

The problem with your second code is that it can easily be exchanged with just TRUE since:

if (true) {

equals

if ( $some_variable !== 'uk' || $some_variable !== 'in' ) {

You are asking if the value of a string is not A or Not B. If it is A, it is definitely not also B and if it is B it is definitely not A. And if it is C or literally anything else, it is also not A and not B. So that statement always (not taking into account schrödingers law here) returns true.

Copy Data from a table in one Database to another separate database

It's db1.dbo.TempTable and db2.dbo.TempTable

The four-part naming scheme goes:

ServerName.DatabaseName.Schema.Object

How to alert using jQuery

Don't do this, but this is how you would do it:

$(".overdue").each(function() { 
    alert("Your book is overdue"); 
});

The reason I say "don't do it" is because nothing is more annoying to users, in my opinion, than repeated pop-ups that cannot be stopped. Instead, just use the length property and let them know that "You have X books overdue".

Getting the class name from a static method in Java

If you are using reflection, you can get the Method object and then:

method.getDeclaringClass().getName()

To get the Method itself, you can probably use:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)

Javascript : array.length returns undefined

It looks as though it's not an array but an arbitrary object. If you have control over the PHP serialization, you might be able to change that.

As raina77ow pointed out, one way to do this in PHP would be by replacing something like this:

json_encode($something) 

with something like:

json_encode(array_values($something))

But don't ignore the other answers here about Object.keys. They should also accomplish what you want if you don't have the ability or the desire to change the serialization of your object.

htmlentities() vs. htmlspecialchars()

One small example, I needed to have 2 client names indexed in a function:

[1] => Altisoxxce Soluxxons S.à r.l.
[5] => Joxxson & Joxxson

I originally $term = get_term_by('name', htmlentities($name), 'client'); which resulted in term names that only included the ampersand array item (&) but not the accented item. But when I changed the variable setting to htmlspecialchars both were able to run through the function. Hope this helps!

MongoDB or CouchDB - fit for production?

I am using CouchDB in production. Currently it stores all those 'optional' fields that weren't in the original DB schema. And right now I am thinking about moving all data to CouchDB.

It's quite a risky step, I admit. Firstly, because it's not v1.0 yet. And secondly, because it is drivespace-hungry. By my calculations, CouchDB file (with indexes) is ~30 times larger than MySQL database with the same rows. But I am pretty sure it will work out just fine.

Module not found: Error: Can't resolve 'core-js/es6'

I found possible answer. You have core-js version 3.0, and this version doesn't have separate folders for ES6 and ES7; that's why the application cannot find correct paths.

To resolve this error, you can downgrade the core-js version to 2.5.7. This version produces correct catalogs structure, with separate ES6 and ES7 folders.

To downgrade the version, simply run:

npm i -S [email protected]

In my case, with Angular, this works ok.

Showing line numbers in IPython/Jupyter Notebooks

You can also find Toggle Line Numbers under View on the top toolbar of the Jupyter notebook in your browser. This adds/removes the lines numbers in all notebook cells.

For me, Esc+l only added/removed the line numbers of the active cell.

Pandas - How to flatten a hierarchical index in columns

A general solution that handles multiple levels and mixed types:

df.columns = ['_'.join(tuple(map(str, t))) for t in df.columns.values]

Initializing a list to a known number of elements in Python

Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.

import array
verts=array.array('i',(0,)*1000)

For the non-pythonistas, the (0,)*1000 term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0) as a tuple, otherwise it would be evaluated as 0.

I've used a tuple instead of a list because they are generally have lower overhead.

Passing a variable to a powershell script via command line

Declare the parameter in test.ps1:

 Param(
                [Parameter(Mandatory=$True,Position=1)]
                [string]$input_dir,
                [Parameter(Mandatory=$True)]
                [string]$output_dir,
                [switch]$force = $false
                )

Run the script from Run OR Windows Task Scheduler:

powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

or,

 powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

WCF on IIS8; *.svc handler mapping doesn't work

We managed to solve the error under Windows Server 2012 by:

  1. Removing from "Remove Roles and Features Wizard" .NET Framework 4.5 Features/ASP.NET 4.5 and all its dependent features
  2. Re-installing the removed features.

It seems the order of installation is the cause.

Also, make sure you have HTTP Activation installed under WCF Services.

How do I force "git pull" to overwrite local files?

This worked for me very well!

git fetch --all
git reset --hard origin/master

Altering column size in SQL Server

ALTER TABLE [Employee]
ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL

Bootstrap Datepicker - Months and Years Only

Why not call the $('.input-group.date').datepicker("remove"); when the select statement is changed then set your datepicker view then call the $('.input-group.date').datepicker("update");

Meaning of - <?xml version="1.0" encoding="utf-8"?>

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
 </body>
</html>

Please refer to the W3 standards for XML.

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

The page you linked states

If an explicit array size is specified, but an shorter initiliazation list is specified, the unspecified elements are set to zero.

Speed issue: Any differences would be negligible for arrays this small. If you work with large arrays and speed is much more important than size, you can have a const array of the default values (initialized at compile time) and then memcpy them to the modifiable array.

How to print an exception in Python 3?

I've use this :

except (socket.timeout, KeyboardInterrupt) as e:
    logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
    break

Let me know if it does not work for you !!

How to stop event propagation with inline onclick attribute?

Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:

e.stopPropagation();

If you want to get fancy, you can do this:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    //IE8 and Lower
    else {
      e.cancelBubble = true;
    }
}

How do I refresh a DIV content?

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

link_to method and click event in Rails

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

java.lang.ClassNotFoundException: org.apache.log4j.Level

In my environment, I just added the two files to class path. And is work fine.

slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

jQuery toggle animation

onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 

onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"

Just put two stops -- one onmouseover and one onmouseout.

Is there a better jQuery solution to this.form.submit();?

In JQuery you can call

$("form:first").trigger("submit")

Don't know if that is much better. I think form.submit(); is pretty universal.

Display HTML form values in same page after submit using Ajax

One more way to do it (if you use form), note that input type is button

<input type="button" onclick="showMessage()" value="submit" />

Complete code is:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

But you can do it even without form:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

Here you can use either submit or button:

<input type="submit" onclick="showMessage()" value="submit" />

No need to set

return false;

from JavaScript function for neither of those two examples.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Just in case of someone has the same problem. I'am using vim with YouCompleteMe, failed to start ycmd with this error message, what I did is: export LC_CTYPE="en_US.UTF-8", the problem is gone.

connecting MySQL server to NetBeans

  1. Download XAMPP
  2. Run XAMPP server. Click on Start button in front of MY SQL. Now you can see that color is changed to green. Now, Click on Admin.The new browser window will be open. Copy the link from browser and paste to the Admin properties as shown in below. Set path in the admin properties of database connection. Click on OK. Now your database is connected. enter image description here

Find out who is locking a file on a network share

On Windows 2008 R2 servers you have two means of viewing what files are open and closing those connections.

Via Share and Storage Management

Server Manager > Roles > File Services > Share and Storage Management > right-click on SaSM > Manage Open File

Via OpenFiles

CMD > Openfiles.exe /query /s SERVERNAME

See http://technet.microsoft.com/en-us/library/bb490961.aspx.

How to query a MS-Access Table from MS-Excel (2010) using VBA

The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0 if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0 only works for the older MDB format.

You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).

You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")

Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.

Public Sub foo()
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Access\webforums\whiteboard2003.mdb"
    strSql = "SELECT Count(*) FROM MyTable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.fields(0) & " rows in MyTable"
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As mentioned by Dan Abramov

Do it right inside render

We actually use that approach with memoise one for any kind of proxying props to state calculations.

Our code looks this way

// ./decorators/memoized.js  
import memoizeOne from 'memoize-one';

export function memoized(target, key, descriptor) {
  descriptor.value = memoizeOne(descriptor.value);
  return descriptor;
}

// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';

class ExampleComponent extends React.Component {
  buildValuesFromProps() {
    const {
      watchedProp1,
      watchedProp2,
      watchedProp3,
      watchedProp4,
      watchedProp5,
    } = this.props
    return {
      value1: buildValue1(watchedProp1, watchedProp2),
      value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
      value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
    }
  }

  @memoized
  buildValue1(watchedProp1, watchedProp2) {
    return ...;
  }

  @memoized
  buildValue2(watchedProp1, watchedProp3, watchedProp5) {
    return ...;
  }

  @memoized
  buildValue3(watchedProp3, watchedProp4, watchedProp5) {
    return ...;
  }

  render() {
    const {
      value1,
      value2,
      value3
    } = this.buildValuesFromProps();

    return (
      <div>
        <Component1 value={value1}>
        <Component2 value={value2}>
        <Component3 value={value3}>
      </div>
    );
  }
}

The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps or componentWillReceiveProps and you can skip copy-paste initialization inside a constructor.

NOTE:

This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

Making an array of integers in iOS

C array:

NSInteger array[6] = {1, 2, 3, 4, 5, 6};

Objective-C Array:

NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers

Swift Array:

var array = [1, 2, 3, 4, 5, 6]

This is correct too:

var array = Array(1...10)

NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:

var array: [Int] = [1, 2, 3, 4, 5, 6]

If you wanted an array of Doubles, you would use :

var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference

or:

var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type

Catch checked change event of a checkbox

$(document).ready(function(){
    checkUncheckAll("#select_all","[name='check_boxes[]']");
});

var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
  // in IE, the event object is a property of the window object
  // in Mozilla, event object is passed to event handlers as a parameter
  event = event || window.event;

  var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
  if (event.shiftKey && last != -1) {
    var di = num > last ? 1 : -1;
    for (var i = last; i != num; i += di)
      document.forms.boxes['box[' + i + ']'].checked = true;
  }
  last = num;
}
function init() {
  for (var i = 0; i < NUM_BOXES; i++)
    document.forms.boxes['box[' + i + ']'].onclick = check;
}

HTML:

<body onload="init()">
  <form name="boxes">
    <input name="box[0]" type="checkbox">
    <input name="box[1]" type="checkbox">
    <input name="box[2]" type="checkbox">
    <input name="box[3]" type="checkbox">
    <input name="box[4]" type="checkbox">
    <input name="box[5]" type="checkbox">
    <input name="box[6]" type="checkbox">
    <input name="box[7]" type="checkbox">
    <input name="box[8]" type="checkbox">
    <input name="box[9]" type="checkbox">
  </form>
</body>

Div table-cell vertical align not working

In my case, I wanted to center in a parent container with position: absolute.

<div class="absolute-container">
    <div class="parent-container">
        <div class="centered-content">
            My content
        </div>
    </div>
</div>

I had to add some positioning for top, bottom, left & right.

.absolute-container {
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

.parent-container {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}

.centered-content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

I fixed this problem employing the two procedures of :

  1. In Eclipse->'Project' menu -> 'Java Compiler' -> set 'Compiler compliance level' = 1.6 check on 'Use default compliance settings' Set 'Generated .class compatibility' = 1.6 Set 'Source compatibilty' = 1.6

  2. Then go to 'Windows' menu --> 'Preferences' -->'Java' , expand 'Java' --> 'Compiler' -->Set 'Compiler compliance level' = 1.6

Hint: Source compatibility must be equal to or less than compliance level.

How to get access token from FB.login method in javascript SDK

_x000D_
_x000D_
window.fbAsyncInit = function () {_x000D_
    FB.init({_x000D_
        appId: 'Your-appId',_x000D_
        cookie: false,  // enable cookies to allow the server to access _x000D_
        // the session_x000D_
        xfbml: true,  // parse social plugins on this page_x000D_
        version: 'v2.0' // use version 2.0_x000D_
    });_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
    var js, fjs = d.getElementsByTagName(s)[0];_x000D_
    if (d.getElementById(id)) return;_x000D_
    js = d.createElement(s); js.id = id;_x000D_
    js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
    fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
   _x000D_
function fb_login() {_x000D_
    FB.login(function (response) {_x000D_
_x000D_
        if (response.authResponse) {_x000D_
            console.log('Welcome!  Fetching your information.... ');_x000D_
            //console.log(response); // dump complete info_x000D_
            access_token = response.authResponse.accessToken; //get access token_x000D_
            user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
            FB.api('/me', function (response) {_x000D_
                var email = response.email;_x000D_
                var name = response.name;_x000D_
                window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
                // used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);          _x000D_
            });_x000D_
_x000D_
        } else {_x000D_
            //user hit cancel button_x000D_
            console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
        }_x000D_
    }, {_x000D_
        scope: 'email'_x000D_
    });_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
                </fb:login-button>
_x000D_
_x000D_
_x000D_

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

Bulk insert with SQLAlchemy ORM

SQLAlchemy introduced that in version 1.0.0:

Bulk operations - SQLAlchemy docs

With these operations, you can now do bulk inserts or updates!

For instance (if you want the lowest overhead for simple table INSERTs), you can use Session.bulk_insert_mappings():

loadme = [(1, 'a'),
          (2, 'b'),
          (3, 'c')]
dicts = [dict(bar=t[0], fly=t[1]) for t in loadme]

s = Session()
s.bulk_insert_mappings(Foo, dicts)
s.commit()

Or, if you want, skip the loadme tuples and write the dictionaries directly into dicts (but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).

Git fatal: protocol 'https' is not supported

Just add this git config --global http.sslVerify false , so that it doesn't check the certificate and it should work just fine

Algorithm to find Largest prime factor of a number

    //this method skips unnecessary trial divisions and makes 
    //trial division more feasible for finding large primes

    public static void main(String[] args) 
    {
        long n= 1000000000039L; //this is a large prime number 
        long i = 2L;
        int test = 0;

        while (n > 1)
        {
            while (n % i == 0)
            {
                n /= i;     
            }

            i++;

            if(i*i > n && n > 1) 
            {
                System.out.println(n); //prints n if it's prime
                test = 1;
                break;
            }
        }

        if (test == 0)  
            System.out.println(i-1); //prints n if it's the largest prime factor
    }

C read file line by line

readLine() returns pointer to local variable, which causes undefined behaviour.

To get around you can:

  1. Create variable in caller function and pass its address to readLine()
  2. Allocate memory for line using malloc() - in this case line will be persistent
  3. Use global variable, although it is generally a bad practice

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

just put all apache comons jar and file upload jar in lib folder of tomcat

How do I read a text file of about 2 GB?

EmEditor works quite well for me. It's shareware IIRC but doesn't stop working after the license expires..

Bash loop ping successful

I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.

echo "Testing..."

PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"

eval $PING_CMD

if [[ $? -eq 0 ]]; then
    echo "Already connected."
else
    echo -n "Waiting for connection..."

    while true; do
        eval $PING_CMD

        if [[ $? -eq 0 ]]; then
            echo
            echo Connected.
            break
        else
            sleep 0.5
            echo -n .
        fi
    done
fi

I also have a Gist of this script which I'll update with fixes and improvements as needed.

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

How to use Git?

I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.

pip installing in global site-packages instead of virtualenv

I also encountered this problem, it troubled me for a long time, until I solved it according to @Chase Ries method.

The key to solving the problem is:

Try checking your bin/pip and bin/activate scripts. In bin/pip, look at the shebang. Is it correct? If not, correct it. Then on line ~42 in your bin/activate, check to see if your virtualenv path is right. It'll look something like this

VIRTUAL_ENV="/Users/me/path/to/virtual/environment"

If it's wrong, correct it, deactivate, then . bin/activate, and if our mutual problem had the same cause, it should work.

Below, I will explain this process in detail in the Ubuntu environment, the same is true for Windows and MacOS.

The meaning of this sentence is that we need to check whether the first line #!/path/python of the bin/pip file in the virtual environment is correct.

As originally shown in my file:

#!/home/banni/dai/.venv/bin/python3

Run pip in terminal(absolute path):

/home/banni/dai/.venv/bin/pip

Will find an error:

bash: ./pip: /home/banni/dai/.venv/bin/python3: bad interpreter: No such file or directory

Now I am confused why I can't find this python3, because python3 exists in the folder .venv/bin where the virtual environment is located.

I check the absolute path of the folder .venv/bin. After executing the pwd command, it displays:

/home/banni/Research/dai/.venv/bin

Carefully observe that the path of the .venv folder has changed. Change the first line of the /bin/pip file to

#!/home/banni/Research/dai/.venv/bin/python3

In the same way, check and modify the bin/activate file.

I changed VIRTUAL_ENV="/home/banni/dai/.venv" to VIRTUAL_ENV="/home/banni/Research/dai/.venv"

At this point, after activating the virtual environment, the pip command can be executed normally.

So, for me, the reason for this problem is that the path of the folder where the virtual environment is located has changed (a secret problem that was left when the folders were organized before).

However, due to the change in the location of the folder where the virtual environment is located, there may be many path errors, so the easiest way is to restore the folder where the virtual environment is located to the original location.

How to join entries in a set into one string?

I wrote a method that handles the following edge-cases:

  • Set size one. A ", ".join({'abc'}) will return "a, b, c". My desired output was "abc".
  • Set including integers.
  • Empty set should returns ""
def set_to_str(set_to_convert, separator=", "):
        set_size = len(set_to_convert)
        if not set_size:
            return ""
        elif set_size == 1:
            (element,) = set_to_convert
            return str(element)
        else:
            return separator.join(map(str, set_to_convert))

SQL Server - Convert date field to UTC

If they're all local to you, then here's the offset:

SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime

and you should be able to update all the data using:

UPDATE SomeTable
   SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)

Would that work, or am I missing another angle of this problem?

Function stoi not declared

Install the latest version of TDM-GCC here is the link-http://wiki.codeblocks.org/index.php/MinGW_installation

TypeError: 'NoneType' object is not iterable in Python

For me it was a case of having my Groovy hat on instead of the Python 3 one.

Forgot the return keyword at the end of a def function.

Had not been coding Python 3 in earnest for a couple of months. Was thinking last statement evaluated in routine was being returned per the Groovy (or Rust) way.

Took a few iterations, looking at the stack trace, inserting try: ... except TypeError: ... block debugging/stepping thru code to figure out what was wrong.

The solution for the message certainly did not make the error jump out at me.

ssh-copy-id no identities found error

FWIW, the -i option was a red herring for me. ssh-copy-id will use ~/.ssh/id_rsa.pub by default.

What was keeping it from working for me was the permissions on the ~ directory, the ~/.ssh directory, and the ~/.ssh/authorized_keys file on the remote computer.

All three need to be set with chmod 755 ~ ~/.ssh ~/.ssh/authorized_keys, then ssh-copy-id your-remote-server.com will work.

How to get javax.comm API?

Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html

Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html

In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way

1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"

password was also updated successfully.

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

Find by key deep in a nested array

I'd like to suggest an amendment to Zach/RegularMike's answer (but don't have the "reputation" to be able to comment!). I found there solution a very useful basis, but suffered in my application because if there are strings within arrays it would recursively call the function for every character in the string (which caused IE11 & Edge browsers to fail with "out of stack space" errors). My simple optimization was to add the same test used in the "object" clause recursive call to the one in the "array" clause:

if (arrayElem instanceof Object || arrayElem instanceof Array) {

Thus my full code (which is now looking for all instances of a particular key, so slightly different to the original requirement) is:

// Get all instances of specified property deep within supplied object
function getPropsInObject(theObject, targetProp) {
    var result = [];
    if (theObject instanceof Array) {
        for (var i = 0; i < theObject.length; i++) {
            var arrayElem = theObject[i];
            if (arrayElem instanceof Object || arrayElem instanceof Array) {
                result = result.concat(getPropsInObject(arrayElem, targetProp));
            }
        }
    } else {
        for (var prop in theObject) {
            var objProp = theObject[prop];
            if (prop == targetProp) {
                return theObject[prop];
            }
            if (objProp instanceof Object || objProp instanceof Array) {
                result = result.concat(getPropsInObject(objProp, targetProp));
            }
        }
    }
    return result;
}

Chosen Jquery Plugin - getting selected values

If anyone wants to get only the selected value on click to an option, he can do the follow:

$('.chosen-select').on('change', function(evt, params) {
    var selectedValue = params.selected;
    console.log(selectedValue);
});

Sort dataGridView columns in C# ? (Windows Form)

dataGridView1.Sort(dataGridView1.Columns[0],ListSortDirection.Ascending);

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

Use string in switch case in java

String value = someMethod();
switch(0) {
default:
    if ("apple".equals(value)) {
        method1();
        break;
    }
    if ("carrot".equals(value)) {
        method2();
        break;
    }
    if ("mango".equals(value)) {
        method3();
        break;
    }
    if ("orance".equals(value)) {
        method4();
        break;
    }
}

Laravel 5.4 redirection to custom url after login

you can add method in LoginController add line use App\User; on Top, after this add method, it is work for me wkwkwkwkw , but you must add {{ csrf_field() }} on view admin and user

protected function authenticated(Request $request, $user){

$user=User::where('email',$request->input('email'))->pluck('jabatan');
$c=" ".$user." ";
$a=strcmp($c,' ["admin"] ');

if ($a==0) {
    return redirect('admin');

}else{
    return redirect('user');

}}

RegEx for valid international mobile phone number

After stripping all characters except '+' and digits from your input, this should do it:

^\+[1-9]{1}[0-9]{3,14}$

If you want to be more exact with the country codes see this question on List of phone number country codes

However, I would try to be not too strict with my validation. Users get very frustrated if they are told their valid numbers are not acceptable.

Django - after login, redirect user to his custom page --> mysite.com/username

Yes! In your settings.py define the following

LOGIN_REDIRECT_URL = '/your-path'

And have '/your-path' be a simple View that looks up self.request.user and does whatever logic it needs to return a HttpResponseRedirect object.

A better way might be to define a simple URL like '/simple' that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

How to access to a child method from the parent in vue.js

You can use ref.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {}
  },
  template: `
  <div>
     <ChildForm :item="item" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.$refs.form.submit()
    }
  },
  components: { ChildForm },
})

If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {},
    bus: new Vue(),
  },
  template: `
  <div>
     <ChildForm :item="item" :bus="bus" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.bus.$emit('submit')
    }
  },
  components: { ChildForm },
})

Code of component.

<template>
 ...
</template>

<script>
export default {
  name: 'NowForm',
  props: ['item', 'bus'],
  methods: {
    submit() {
        ...
    }
  },
  mounted() {
    this.bus.$on('submit', this.submit)
  },  
}
</script>

https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

No submodule mapping found in .gitmodule for a path that's not a submodule

Usually, git creates a hidden directory in project's root directory (.git/)

When you're working on a CMS, its possible you install modules/plugins carrying .git/ directory with git's metadata for the specific module/plugin

Quickest solution is to find all .git directories and keep only your root git metadata directory. If you do so, git will not consider those modules as project submodules.

Ruby 'require' error: cannot load such file

First :

$ sudo gem install colored2

And,you should input your password

Then :

$ sudo gem update --system  

Appear Updating rubygems-update ERROR: While executing gem ... (OpenSSL::SSL::SSLError) hostname "gems.ruby-china.org" does not match the server certificate

Then:

$  rvm -v
$ rvm get head

Last What language do you want to use?? [ Swift / ObjC ]

ObjC

Would you like to include a demo application with your library? [ Yes / No ]

Yes

Which testing frameworks will you use? [ Specta / Kiwi / None ]

None

Would you like to do view based testing? [ Yes / No ]

No

What is your class prefix?

XMG

Running pod install on your new library.

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

jQuery check/uncheck radio button onclick

DiegoP,

I was having the same trouble, until I realized that the check on the box doesnt go off until the attribute is removed. That means even if checked value is made false, it will remain there.

Hence use the removeAttr() function and remove the checked attrib and it WILL DEFINITELY WORK.

Use success() or complete() in AJAX call

complete executes after either the success or error callback were executed.

Maybe you should check the second parameter complete offers too. It's a String holding the type of success the ajaxCall had.

The different callbacks are described a little more in detail here jQuery.ajax( options )


I guess you missed the fact that the complete and the success function (I know inconsistent API) get different data passed in. success gets only the data, complete gets the whole XMLHttpRequest object. Of course there is no responseText property on the data string.

So if you replace complete with success you also have to replace data.responseText with data only.

success

The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.

complete

The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.

If you need to have access to the whole XMLHttpRequest object in the success callback I suggest trying this.

var myXHR = $.ajax({
    ...
    success: function(data, status) {
        ...do whatever with myXHR; e.g. myXHR.responseText...
    },
    ...
});

What does void do in java?

The reason the code will not work without void is because the System.out.println(String string) method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void keyword in its signature.

You can see the documentation of the System.out.println here:

http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29

To press the issue further, println is a classic example of a method which is performing computation as a "side effect."

How to format a date using ng-model?

I've created a simple directive to enable standard input[type="date"] form elements to work correctly with AngularJS ~1.2.16.

Look here: https://github.com/betsol/angular-input-date

And here's the demo: http://jsfiddle.net/F2LcY/1/

React-Router open Link in new tab

target="_blank" is enough to open in a new tab, when you are using react-router

eg: <Link to={/admin/posts/error-post-list/${this.props.errorDate}} target="_blank"> View Details </Link>

Disable Laravel's Eloquent timestamps

Add this line into your model:

Overwrite existing variable $timestamps true to false

/**
 * Indicates if the model should be timestamped.
 *
 * @var bool
 */

public $timestamps = false;

<input type="file"> limit selectable files by extensions

Easy way of doing it would be:

<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">

Works with all browsers, except IE9. I haven't tested it in IE10+.

Remove pattern from string with gsub

The following code works on your example :

gsub(".*_", "", a)

Using two values for one switch case statement

The fallthrough answers by others are good ones.

However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

In the example below, both case 'text1' and case 'text4' behave the same:

switch (name) {
        case text1: {
            method1();
            break;
        }
        case text2: {
            method2();
            break;
        }
        case text3: {
            method3();
            break;
        }
        case text4: {
            method1();
            break;
        }

I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

How to detect if URL has changed after hash in JavaScript

Although an old question, the Location-bar project is very useful.

var LocationBar = require("location-bar");
var locationBar = new LocationBar();

// listen to all changes to the location bar
locationBar.onChange(function (path) {
  console.log("the current url is", path);
});

// listen to a specific change to location bar
// e.g. Backbone builds on top of this method to implement
// it's simple parametrized Backbone.Router
locationBar.route(/some\-regex/, function () {
  // only called when the current url matches the regex
});

locationBar.start({
  pushState: true
});

// update the address bar and add a new entry in browsers history
locationBar.update("/some/url?param=123");

// update the address bar but don't add the entry in history
locationBar.update("/some/url", {replace: true});

// update the address bar and call the `change` callback
locationBar.update("/some/url", {trigger: true});

Dark theme in Netbeans 7 or 8

Netbeans 8

Tools -> Options -> Appearance (Look & Feel Tab)

(NetBeans -> Preferences -> Appearance (Look & Feel Tab) on OS X)

Netbeans 7.x

Tools -> Plugins -> Available -> Dark Look and Feel - Install this plugin.

Once this plugin is installed, restarting netbeans should automatically switch to Dark Metal.

There are 2 themes that comes with this plugin - Dark Metal & Dark Nimbus

In order to switch themes, use the below option :

Tools -> Options -> Miscellaneous -> Windows -> Preferred Look & Feel option

enter image description here

How to use Google Translate API in my Java application?

I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com

import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;

public class Main {

    public static void main(String[] args) throws IOException, ParseException {

        ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
        Configuration.startMaximized = true;
        open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
        String[] strings = /some strings to translate
        for (String data: strings) {
            $x("//textarea[@id='source']").clear();
            $x("//textarea[@id='source']").sendKeys(data);
            String translation = $x("//span[@class='tlid-translation translation']").getText();
        }
    }
}

Configure WAMP server to send email

Install Fake Sendmail (download sendmail.zip). Then configure C:\wamp\sendmail\sendmail.ini:

smtp_server=smtp.gmail.com
smtp_port=465
[email protected]
auth_password=your_password

The above will work against a Gmail account. And then configure php.ini:

sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

Now, restart Apache, and that is basically all you need to do.

Suppress output of a function

In case anyone's arriving here looking for a solution applicable to RMarkdown, this will suppress all output:

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({

# Your code goes here
2 * 2
# etc
# etc


})})
```

The code will run, but the output will not be printed to the HTML document

Parse Json string in C#

json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

c# code: to take only a single value, for example the word "bike".

//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

         dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
         string Text = stuff1[0].hws[2];
         Console.WriteLine(Text);

output:

bike