Programs & Examples On #Resig

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

I think nt86's solution is the most appropriate because it leverages the underlying Windows infrastructure (certificate store). But it doesn't explain how to install python-certifi-win32 to start with since pip is non functional.

The trick is to use --trustedhost to install python-certifi-win32 and then after that, pip will automatically use the windows certificate store to load the certificate used by the proxy.

So in a nutshell, you should do:

pip install python-certifi-win32 -trustedhost pypi.org

and after that you should be good to go

docker container ssl certificates

Mount the certs onto the Docker container using -v:

docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"

How to hide keyboard in swift on pressing return key?

Another way of doing this which mostly uses the storyboard and easily allows you to have multiple text fields is:

@IBAction func resignKeyboard(sender: AnyObject) {
    sender.resignFirstResponder()
}

Connect all your text fields for that view controller to that action on the Did End On Exit event of each field.

Add swipe to delete UITableViewCell

I used tableViewCell to show multiple data, after swipe () right to left on a cell it will show two buttons Approve And reject, there are two methods, the first one is ApproveFunc which takes one argument, and the another one is RejectFunc which also takes one argument. enter image description here

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let Approve = UITableViewRowAction(style: .normal, title: "Approve") { action, index in

        self.ApproveFunc(indexPath: indexPath)
    }
    Approve.backgroundColor = .green

    let Reject = UITableViewRowAction(style: .normal, title: "Reject") { action, index in

        self.rejectFunc(indexPath: indexPath)
    }
    Reject.backgroundColor = .red



    return [Reject, Approve]
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

func ApproveFunc(indexPath: IndexPath) {
    print(indexPath.row)
}
func rejectFunc(indexPath: IndexPath) {
    print(indexPath.row)
}

How to dismiss keyboard iOS programmatically when pressing return

Since the tags only say iOS i will post the answer for Swift 1.2 and iOs 8.4, add these in your view controller swift class:

// MARK: - Close keyboard when touching somewhere else
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    self.view.endEditing(true)

}

// MARK: - Close keyboard when return pressed
func textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()

    return true
}
// MARK: -

Also do not forget to add UITextFieldDelegate in the class declaration and set your text fields delegate to self (the view).

Parse an HTML string with JS

EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.


For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.

For example try parsing <td>Test</td>. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.

Only jQuery handles that case well.

So the future solution (MS Edge 13+) is to use template tag:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content.cloneNode(true);
}

var documentFragment = parseHTML('<td>Test</td>');

For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99

How to pass object with NSNotificationCenter

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

On the receiving end you can access the userInfo dictionary as follows:

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

Re-sign IPA (iPhone)

With Fastlane sigh's resign option you can do this very easily.

sigh resign -p <path-to-profile-with-mobileprovision-ext> -i <code-sighning-identity-of-your-app>

You can download the profile using sigh also, just before the command.

Using Custom Domains With IIS Express

I tried all of above, nothing worked. What resolved the issue was adding IPv6 bindings in the hosts file. In step 5 of @David Murdochs answer, add two lines instead of one, i.e.:

127.0.0.1 dev.example.com
::1 dev.example.com

I figured it out by checking $ ping localhost from command line, which used to return:

Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Instead, it now returns:

Reply from ::1: time<1ms

I don't know why, but for some reason IIS Express started using IPv6 instead of IPv4.

Should I use past or present tense in git commit messages?

does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!

iPhone keyboard, Done button and resignFirstResponder

I used this method to change choosing Text Field

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

if ([textField isEqual:self.emailRegisterTextField]) {

    [self.usernameRegisterTextField becomeFirstResponder];

} else if ([textField isEqual:self.usernameRegisterTextField]) {

    [self.passwordRegisterTextField becomeFirstResponder];

} else {

    [textField resignFirstResponder];

    // To click button for registration when you clicking button "Done" on the keyboard
    [self createMyAccount:self.registrationButton];
}

return YES;

}

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

What's the best way to get the current URL in Spring MVC?

If you need the URL till hostname and not the path use Apache's Common Lib StringUtil, and from URL extract the substring till third indexOf /.

public static String getURL(HttpServletRequest request){
   String fullURL = request.getRequestURL().toString();
   return fullURL.substring(0,StringUtils.ordinalIndexOf(fullURL, "/", 3)); 
}

Example: If fullURL is https://example.com/path/after/url/ then Output will be https://example.com

Easy way to dismiss keyboard?

Subclass your textfields... and also textviews

In the subclass put this code..

-(void)conformsToKeyboardDismissNotification{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyBoard) name:KEYBOARD_DISMISS object:nil];
}

-(void)deConformsToKeyboardDismissNotification{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:KEYBOARD_DISMISS object:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self resignFirstResponder];
}

In the textfield delegates (similarly for textview delegates)

-(void)textFieldDidBeginEditing:(JCPTextField *)textField{
     [textField conformsToKeyboardDismissNotification];
}


- (void)textFieldDidEndEditing:(JCPTextField *)textField{
    [textField deConformsToKeyboardDismissNotification];
}

All set.. Now just post the notification from anywhere in your code. It will resign any keyboard.

How to dismiss keyboard for UITextView with return key?

The question asks how to do it with the return key but I think this could help someone with the intent to just make keyboard disappear when using UITextView:

private func addToolBarForTextView() {
    let textViewToolbar: UIToolbar = UIToolbar()
    textViewToolbar.barStyle = .default
    textViewToolbar.items = [
        UIBarButtonItem(title: "Cancel", style: .done,
                  target: self, action: #selector(cancelInput)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                  target: self, action: nil),
        UIBarButtonItem(title: "Post Reply", style: .done,
                  target: self, action: #selector(doneInput))
    ]
    textViewToolbar.sizeToFit()
    yourTextView.inputAccessoryView = textViewToolbar
}

@objc func cancelInput() { print("cancel") }
@objc func doneInput() { print("done") }

override func viewDidLoad() {
    super.viewDidLoad()
    addToolBarForTextView()
}

Call addToolBarForTextView() in the viewDidLoad or some other life cycle method.

It seems that was the perfect solution for me.

Cheers,

Murat

How do you clone an Array of Objects in Javascript?

The issue with your shallow copy is that all the objects aren't cloned. While the references to each object are unique in each array, once you ultimately grab onto it you're dealing with the same object as before. There is nothing wrong with the way you cloned it... the same result would occur using Array.slice().

The reason your deep copy is having problems is because you're ending up with circular object references. Deep will go as deep as it can go, and if you've got a circle, it'll keep going infinitely until the browser faints.

If the data structure cannot be represented as a directed acyclic graph, then I'm not sure you're going to be able to find an all-purpose method for deep cloning. Cyclic graphs provide many tricky corner cases, and since it's not a common operation I doubt anyone has written a full solution (if it's even possible - it might not be! But I have no time to try to write a rigorous proof now.). I found some good comments on the issue on this page.

If you need a deep copy of an Array of Objects with circular references I believe you're going to have to code your own method to handle your specialized data structure, such that it is a multi-pass clone:

  1. On round one, make a clone of all objects that don't reference other objects in the array. Keep a track of each object's origins.
  2. On round two, link the objects together.

Is JavaScript's "new" keyword considered harmful?

I wrote a post on how to mitigate the problem of calling a constructor without the new keyword.
It's mostly didactic, but it shows how you can create constructors that work with or without new and doesn't require you to add boilerplate code to test this in every constructor.

http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html

Here's the gist of the technique:

/**
 * Wraps the passed in constructor so it works with
 * or without the new keyword
 * @param {Function} realCtor The constructor function.
 *    Note that this is going to be wrapped
 *    and should not be used directly 
 */
function ctor(realCtor){
  // This is going to be the actual constructor
  return function wrapperCtor(){
    var obj; // object that will be created
    if (this instanceof wrapperCtor) {
      // Called with new
      obj = this;
    } else {
      // Called without new. Create an empty object of the
      // correct type without running that constructor
      surrogateCtor.prototype = wrapperCtor.prototype;
      obj = new surrogateCtor();
    }
    // Call the real constructor function
    realCtor.apply(obj, arguments);
    return obj;
  }

  function surrogateCtor() {}
}

Here's how to use it:

// Create our point constructor
Point = ctor(function(x,y){
  this.x = x;
  this.y = y;
});

// This is good
var pt = new Point(20,30);
// This is OK also
var pt2 = Point(20,30);

How do you dismiss the keyboard when editing a UITextField

You will notice that the method "textFieldShouldReturn" provides the text-field object that has hit the DONE key. If you set the TAG you can switch on that text field. Or you can track and compare the object's pointer with some member value stored by its creator.

My approach is like this for a self-study:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"%s", __FUNCTION__);

    bool fDidResign = [textField resignFirstResponder];

    NSLog(@"%s: did %resign the keyboard", __FUNCTION__, fDidResign ? @"" : @"not ");

    return fDidResign;
}

Meanwhile, I put the "validation" test that denies the resignation follows. It is only for illustration, so if the user types NO! into the field, it will not dismiss. The behavior was as I wanted, but the sequence of output was not as I expected.

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    NSLog(@"%s", __FUNCTION__);

    if( [[textField text] isEqualToString:@"NO!"] ) {
        NSLog(@"%@", textField.text);
        return NO;
    } else {
        return YES;
    }
}

Following is my NSLog output for this denial followed by the acceptance. You will notice that I am returning the result of the resign, but I expected it to return FALSE to me to report back to the caller?! Other than that, it has the necessary behavior.

13.313 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]
13.320 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]
13.327 StudyKbd[109:207] NO!
13.333 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard
59.891 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]
59.897 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldEndEditing:]
59.917 StudyKbd[109:207] -[StudyKbdViewController doneEditText]: NO
59.928 StudyKbd[109:207] -[StudyKbdViewController textFieldShouldReturn:]: did resign the keyboard

Convert string to title case with JavaScript

Another approach to achieve something similar can be as follows.

formatName(name) {
    let nam = '';
    name.split(' ').map((word, index) => {
        if (index === 0) {
            nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
        } else {
            nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
        }
    });
    return nam;
}

jQuery location href

There's no need of jQuery.

window.location.href = 'http://example.com';

Which programming language for cloud computing?

That is a very interesting question.

On the Lang.Next conference there was a very interesting discussion about this topic, in which authors of several programming languages participate (Scala, Dart, C#). There was not a clear consensus at the end, but from my point of view there is one message:

The ideal language for this "cloud age" should be object oriented (because that is how we understand and are able to model the world) and also embrace functional programming.

The code in "cloud age" is almost always distributed: running on several cores/machines (in the cloud center) or just the client/server separation. And it is also asynchronous. We do not block the code when waiting for WS response. The callbacks come in any time.

When using standard imperative programming languages, handling the asynchrony and the distribution really complicated. You have to always take care of the "current state" and when the callbacks come in, you have to decide what to do, in dependences of this state.

Functional programming helps to eliminate the "state" and is much better suited for this new situation.

So I would say: In cloud computing the code is distributed, state-less, asynchronous. Functional programming can help you with that. Object oriented is almost a must to be able to model the world.

I have wrote a blog post about it, if you are interested. I like C#, but actually I would say Scala, Clojure, F# might fit even better.

On the other hand C++ will always be there, and lately is being modernized and getting more attention.

Storing data into list with class

One way(in one line) to do it is like this:

listemail.Add(new EmailData {FirstName = "John", LastName = "Smith", Location = "Los Angeles"});

JQuery, setTimeout not working

This accomplishes the same thing but is much simpler:

$(document).ready(function() {  
   $("#board").delay(1000).append(".");
});

You can chain a delay before almost any jQuery method.

Add a new item to a dictionary in Python

default_data['item3'] = 3

Easy as py.

Another possible solution:

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.

How to var_dump variables in twig templates?

So I got it working, partly a bit hackish:

  1. Set twig: debug: 1 in app/config/config.yml
  2. Add this to config_dev.yml

    services:
        debug.twig.extension:
            class: Twig_Extensions_Extension_Debug
            tags: [{ name: 'twig.extension' }]
    
  3. sudo rm -fr app/cache/dev

  4. To use my own debug function instead of print_r(), I opened vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php and changed print_r( to d(

PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.

Spring Boot + JPA : Column name annotation ignored

For hibernate5 I solved this issue by puting next lines in my application.properties file:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

How can I pass variable to ansible playbook in the command line?

For some reason none of the above Answers worked for me. As I need to pass several extra vars to my playbook in Ansbile 2.2.0, this is how I got it working (note the -e option before each var):

ansible-playbook site.yaml -i hostinv -e firstvar=false -e second_var=value2

python how to "negate" value : if true return false, if false return true

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

How can I convert a DateTime to the number of seconds since 1970?

You probably want to use DateTime.UtcNow to avoid timezone issue

TimeSpan span= DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0)); 

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";

Start systemd service after specific service?

After= dependency is only effective when service including After= and service included by After= are both scheduled to start as part of your boot up.

Ex:

a.service
[Unit]
After=b.service

This way, if both a.service and b.service are enabled, then systemd will order b.service after a.service.

If I am not misunderstanding, what you are asking is how to start b.service when a.service starts even though b.service is not enabled.

The directive for this is Wants= or Requires= under [Unit].

website.service
[Unit]
Wants=mongodb.service
After=mongodb.service

The difference between Wants= and Requires= is that with Requires=, a failure to start b.service will cause the startup of a.service to fail, whereas with Wants=, a.service will start even if b.service fails. This is explained in detail on the man page of .unit.

Check mySQL version on Mac 10.8.5

You should be able to open terminal and just type

mysql -v

.aspx vs .ashx MAIN difference

For folks that have programmed in nodeJs before, particularly using expressJS. I think of .ashx as a middleware that calls the next function. While .aspx will be the controller that actually responds to the request either around res.redirect, res.send or whatever.

Implementing a HashMap in C

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

How to force a UIViewController to Portrait orientation in iOS 6

I have a relatively complex universal app using UISplitViewController and UISegmentedController, and have a few views that must be presented in Landscape using presentViewController. Using the methods suggested above, I was able to get iPhone ios 5 & 6 to work acceptably, but for some reason the iPad simply refused to present as Landscape. Finally, I found a simple solution (implemented after hours of reading and trial and error) that works for both devices and ios 5 & 6.

Step 1) On the controller, specify the required orientation (more or less as noted above)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

-(BOOL)shouldAutorotate
{
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations
{
    NSInteger mask = UIInterfaceOrientationMaskLandscape;
    return mask;

}

Step 2) Create a simple UINavigationController subclass and implement the following methods

-(BOOL)shouldAutorotate {
        return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
        return UIInterfaceOrientationMaskLandscape;
}

Step 3) Present your viewController

vc = [[MyViewController alloc]init];
MyLandscapeNavigationController *myNavigationController = [[MyLandscapeNavigationController alloc] initWithRootViewController:vc];
[self myNavigationController animated:YES completion:nil];

Hope this is helpful to someone.

How do I get the scroll position of a document?

$(document).height() //returns window height

$(document).scrollTop() //returns scroll position from top of document

set value of input field by php variable's value

One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -

<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
    $value1=$_POST['value1'];
    $value2=$_POST['value2'];
    $sign=$_POST['sign'];
    ...
        //Adding to $result variable
    if($sign=='-') {
      $result = $value1-$value2;
    }
    //Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">

Can you change a path without reloading the controller in AngularJS?

Add following inside head tag

  <script type="text/javascript">
    angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
  </script>

This will prevent the reload.

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

How to convert UTC timestamp to device local time in android

The answer from @prgDevelop returns 0 on my Android Marsmallow. Must return 7200000. These changes make it work fine:

int offset = TimeZone.getTimeZone(Time.getCurrentTimezone()).getRawOffset() + TimeZone.getTimeZone(Time.getCurrentTimezone()).getDSTSavings();

How to redirect to the same page in PHP

I just tried using header("Location: "); (without any value) and it redirected to the current page.

Embedding VLC plugin on HTML page

test.html is will be helpful for how to use VLC WebAPI.

test.html is located in the directory where VLC was installed.

e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html

The following code is a quote from the test.html.

HTML:

<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
  <param name="MRL" value="" />
  <param name="ShowDisplay" value="True" />
  <param name="AutoLoop" value="False" />
  <param name="AutoPlay" value="False" />
  <param name="Volume" value="50" />
  <param name="toolbar" value="true" />
  <param name="StartTime" value="0" />
  <EMBED pluginspage="http://www.videolan.org"
    type="application/x-vlc-plugin"
    version="VideoLAN.VLCPlugin.2"
    width="640"
    height="360"
    toolbar="true"
    loop="false"
    text="Waiting for video"
    name="vlc">
  </EMBED>
</object>

JavaScript:

You can get vlc object from getVLC().
It works on IE 10 and Chrome.

function getVLC(name)
{
    if (window.document[name])
    {
        return window.document[name];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1)
    {
        if (document.embeds && document.embeds[name])
            return document.embeds[name];
    }
    else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
    {
        return document.getElementById(name);
    }
}

var vlc = getVLC("vlc");

// do something.
// e.g. vlc.playlist.play();

Centering a Twitter Bootstrap button

Question is a bit old, but easy way is to apply .center-block to button.

What is the difference between for and foreach?

You can use the foreach for an simple array like

int[] test = { 0, 1, 2, 3, ...};

And you can use the for when you have a 2D array

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

Exception: Can't bind to 'ngFor' since it isn't a known native property

In angular 7 got this fixed by adding these lines to .module.ts file:

import { CommonModule } from '@angular/common'; imports: [CommonModule]

Default argument values in JavaScript functions

You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

struct in class

I declared class B inside class A, how do I access it?

Just because you declare your struct B inside class A does not mean that an instance of class A automatically has the properties of struct B as members, nor does it mean that it automatically has an instance of struct B as a member.

There is no true relation between the two classes (A and B), besides scoping.


struct A { 
  struct B { 
    int v;
  };  

  B inner_object;
};

int
main (int argc, char *argv[]) {
  A object;
    object.inner_object.v = 123;
}

Make a link in the Android browser start up my app?

Here's my recipe:

Create a static HTML that redirects to your requested app URL, put that page on the web.

That way, the links you share are 'real' links as far as Android is concerned ( they will be 'clickable').

You 'share' a regular HTTP link, www.your.server.com/foo/bar.html This URL returns a simple 8 line HTML that redirects to your app's URI (window.location = "blah://kuku") (note that 'blah' doesn't have to be HTTP or HTTPS any more).

Once you get this up and running, you can augment the HTML with all the fancy capabilities as suggested above.

This works with the built-in browser, Opera, and Firefox (haven't tested any other browser). Firefox asks 'This link needs to be opened with an application' (ok, cancel). Other browsers apparently don't worry about security that much, they just open the app, no questions asked.

set dropdown value by text using jquery

$("#HowYouKnow option[value='" + theText + "']").attr('selected', 'selected'); // added single quotes

CMD what does /im (taskkill)?

It tells taskkill that the next parameter something.exe is an image name, a.k.a executable name

C:\>taskkill /?

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

Maven: add a dependency to a jar by relative path

I want the jar to be in a 3rdparty lib in source control, and link to it by relative path from the pom.xml file.

If you really want this (understand, if you can't use a corporate repository), then my advice would be to use a "file repository" local to the project and to not use a system scoped dependency. The system scoped should be avoided, such dependencies don't work well in many situation (e.g. in assembly), they cause more troubles than benefits.

So, instead, declare a repository local to the project:

<repositories>
  <repository>
    <id>my-local-repo</id>
    <url>file://${project.basedir}/my-repo</url>
  </repository>
</repositories>

Install your third party lib in there using install:install-file with the localRepositoryPath parameter:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<myGroup> \ 
                         -DartifactId=<myArtifactId> -Dversion=<myVersion> \
                         -Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>

Update: It appears that install:install-file ignores the localRepositoryPath when using the version 2.2 of the plugin. However, it works with version 2.3 and later of the plugin. So use the fully qualified name of the plugin to specify the version:

mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file \
                         -Dfile=<path-to-file> -DgroupId=<myGroup> \ 
                         -DartifactId=<myArtifactId> -Dversion=<myVersion> \
                         -Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>

maven-install-plugin documentation

Finally, declare it like any other dependency (but without the system scope):

<dependency>
  <groupId>your.group.id</groupId>
  <artifactId>3rdparty</artifactId>
  <version>X.Y.Z</version>
</dependency>

This is IMHO a better solution than using a system scope as your dependency will be treated like a good citizen (e.g. it will be included in an assembly and so on).

Now, I have to mention that the "right way" to deal with this situation in a corporate environment (maybe not the case here) would be to use a corporate repository.

Wait .5 seconds before continuing code VB.net

I've had better results by checking the browsers readystate before continuing to the next step. This will do nothing until the browser is has a "complete" readystate

Do While WebBrowser1.ReadyState <> 4
''' put anything here. 
Loop

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

Show Hide div if, if statement is true

Use show/hide method as below

$("div").show();//To Show

$("div").hide();//To Hide

JQuery Find #ID, RemoveClass and AddClass

corrected Code:

jQuery('#testID2').addClass('test3').removeClass('test2');

Read user input inside a loop

Read from the controlling terminal device:

read input </dev/tty

more info: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

How to Calculate Execution Time of a Code Snippet in C++

#include <boost/progress.hpp>

using namespace boost;

int main (int argc, const char * argv[])
{
  progress_timer timer;

  // do stuff, preferably in a 100x loop to make it take longer.

  return 0;
}

When progress_timer goes out of scope it will print out the time elapsed since its creation.

UPDATE: Here's a version that works without Boost (tested on macOS/iOS):

#include <chrono>
#include <string>
#include <iostream>
#include <math.h>
#include <unistd.h>

class NLTimerScoped {
private:
    const std::chrono::steady_clock::time_point start;
    const std::string name;

public:
    NLTimerScoped( const std::string & name ) : name( name ), start( std::chrono::steady_clock::now() ) {
    }


    ~NLTimerScoped() {
        const auto end(std::chrono::steady_clock::now());
        const auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>( end - start ).count();

        std::cout << name << " duration: " << duration_ms << "ms" << std::endl;
    }

};

int main(int argc, const char * argv[]) {

    {
        NLTimerScoped timer( "sin sum" );

        float a = 0.0f;

        for ( int i=0; i < 1000000; i++ ) {
            a += sin( (float) i / 100 );
        }

        std::cout << "sin sum = " << a << std::endl;
    }



    {
        NLTimerScoped timer( "sleep( 4 )" );

        sleep( 4 );
    }



    return 0;
}

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

For me I had multiple versions of the same library included in /app/libs. I was using Parse and I had both ParseFacebookUtilsV3-1.9.0.jar and ParseFacebookUtilsV4-1.9.0.jar.

Deleting the V3 jar solves the problem.

How to convert a command-line argument to int?

As WhirlWind has pointed out, the recommendations to use atoi aren't really very good. atoi has no way to indicate an error, so you get the same return from atoi("0"); as you do from atoi("abc");. The first is clearly meaningful, but the second is a clear error.

He also recommended strtol, which is perfectly fine, if a little bit clumsy. Another possibility would be to use sscanf, something like:

if (1==sscanf(argv[1], "%d", &temp))
    // successful conversion
else
    // couldn't convert input

note that strtol does give slightly more detailed results though -- in particular, if you got an argument like 123abc, the sscanf call would simply say it had converted a number (123), whereas strtol would not only tel you it had converted the number, but also a pointer to the a (i.e., the beginning of the part it could not convert to a number).

Since you're using C++, you could also consider using boost::lexical_cast. This is almost as simple to use as atoi, but also provides (roughly) the same level of detail in reporting errors as strtol. The biggest expense is that it can throw exceptions, so to use it your code has to be exception-safe. If you're writing C++, you should do that anyway, but it kind of forces the issue.

Mongoose (mongodb) batch insert?

Sharing working and relevant code from our project:

//documentsArray is the list of sampleCollection objects
sampleCollection.insertMany(documentsArray)  
    .then((res) => {
        console.log("insert sampleCollection result ", res);
    })
    .catch(err => {
        console.log("bulk insert sampleCollection error ", err);
    });

How to loop an object in React?

You can use map function

{Object.keys(tifs).map(key => (
    <option value={key}>{tifs[key]}</option>
))}

jquery/javascript convert date string to date

var stringDate = "Sunday, February 28, 2010";

var months = ["January", "February", "March"]; // You add the rest  :-)

var m = /(\w+) (\d+), (\d+)/.exec(stringDate);

var date = new Date(+m[3], months.indexOf(m[1]), +m[2]);

The indexOf method on arrays is only supported on newer browsers (i.e. not IE). You'll need to do the searching yourself or use one of the many libraries that provide the same functionality.

Also the code is lacking any error checking which should be added. (String not matching the regular expression, non existent months, etc.)

Difference between DOM parentNode and parentElement

there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.

Run Button is Disabled in Android Studio

My solution was to go to that multiselect button, then "Edit Configurations" -> Go to "+" and select the module (in this case it would be an app if you do not have a multiproject -> then apply and OK

Git commit -a "untracked files"?

  1. First you need to add all untracked files. Use this command line:

    git add *

  2. Then commit using this command line :

    git commit -a

New Array from Index Range Swift

One more variant using extension and argument name range

This extension uses Range and ClosedRange

extension Array {

    subscript (range r: Range<Int>) -> Array {
        return Array(self[r])
    }


    subscript (range r: ClosedRange<Int>) -> Array {
        return Array(self[r])
    }
}

Tests:

func testArraySubscriptRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1..<arr.count] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

func testArraySubscriptClosedRange() {
    //given
    let arr = ["1", "2", "3"]

    //when
    let result = arr[range: 1...arr.count - 1] as Array

    //then
    XCTAssertEqual(["2", "3"], result)
}

LINQ to read XML

Here are a couple of complete working examples that build on the @bendewey & @dommer examples. I needed to tweak each one a bit to get it to work, but in case another LINQ noob is looking for working examples, here you go:

//bendewey's example using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ1
{
    static void Main( )
    {
        //Load xml
        XDocument xdoc = XDocument.Load(@"c:\\data.xml"); //you'll have to edit your path

        //Run query
        var lv1s = from lv1 in xdoc.Descendants("level1")
           select new 
           { 
               Header = lv1.Attribute("name").Value,
               Children = lv1.Descendants("level2")
            };

        StringBuilder result = new StringBuilder(); //had to add this to make the result work
        //Loop through results
        foreach (var lv1 in lv1s)
        {
            result.AppendLine("  " + lv1.Header);
            foreach(var lv2 in lv1.Children)
            result.AppendLine("    " + lv2.Attribute("name").Value);
        }
        Console.WriteLine(result.ToString()); //added this so you could see the output on the console
    }
}

And next:

//Dommer's example, using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ
{
static void Main( )
    {
        XElement rootElement = XElement.Load(@"c:\\data.xml"); //you'll have to edit your path
        Console.WriteLine(GetOutline(0, rootElement));  
    }

static private string GetOutline(int indentLevel, XElement element)
    {
        StringBuilder result = new StringBuilder();
        if (element.Attribute("name") != null)
        {
            result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
        }
        foreach (XElement childElement in element.Elements())
        {
            result.Append(GetOutline(indentLevel + 1, childElement));
        }
        return result.ToString();
    }
}

These both compile & work in VS2010 using csc.exe version 4.0.30319.1 and give the exact same output. Hopefully these help someone else who's looking for working examples of code.

EDIT: added @eglasius' example as well since it became useful to me:

//@eglasius example, still using data.xml from OP
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

class loadXMLToLINQ2
{
    static void Main( )
    {
        StringBuilder result = new StringBuilder(); //needed for result below
        XDocument xdoc = XDocument.Load(@"c:\\deg\\data.xml"); //you'll have to edit your path
        var lv1s = xdoc.Root.Descendants("level1"); 
        var lvs = lv1s.SelectMany(l=>
             new string[]{ l.Attribute("name").Value }
             .Union(
                 l.Descendants("level2")
                 .Select(l2=>"   " + l2.Attribute("name").Value)
              )
            );
        foreach (var lv in lvs)
        {
           result.AppendLine(lv);
        }
        Console.WriteLine(result);//added this so you could see the result
    }
}

Execute command without keeping it in history

An extension of @John Doe & @user3270492's answer. But, this seems to work for me.

<your_secret_command>; history -d $((HISTCMD-1))

You should not see the entry of the command in your history.

Here's the explanation..

The 'history -d' deletes the mentioned entry from the history.

The HISTCMD stores the command_number of the one to be executed next. So, (HISTCMD-1) refers to the last executed command.

Remove a certain line from Bash history file

Postman: How to make multiple requests at the same time

I guess there's no such feature in postman as to run concurrent tests.

If i were you i would consider Apache jMeter which is used exactly for such scenarios.

Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. enter image description here There you can specify the details:

  • number of iterations,
  • upload csv file with data for different test runs, etc.

The runs won't be concurrent, only consecutive.

Hope that helps. But do consider jMeter (you'll love it).

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

I had the same issue, the following commands can resolve:

sudo yum install  glibc-common glibc  (mutual dependency)
sudo yum install  glibc.i686  (the missing version)

Unexpected token ILLEGAL in webkit

When in doubt... use JSLint to get it out!

http://www.jslint.com

I just ran into a similar problem whilst copying this from JFiddle;

$('input[name=MeetAll]').change(function (e) {
  $('#MeetMost').attr('checked', !$('#MeetAll').attr('checked'));
});
$('input[name=MeetMost]').change(function (e) {
  $('#MeetAll').attr('checked', !$('#MeetMost').attr('checked'));
});?

Jslint told me i had a random "." Charachter...

Things that make you go "hmmmmmm"

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

Auto submit form on page load

Add the following to Body tag,

<body onload="document.forms['member_signup'].submit()">

and give name attribute to your Form.

<form method="POST" action="" name="member_signup">

How to upgrade safely php version in wamp server

One important step is missing in all answers. I successfully upgraded with following steps:

  • stop apache service with wamp stack manager.
  • rename your wampstack/php dir to wampstack/php_old
  • copy new php dir to wampstack/
  • replace wampstack/php/php.ini by wampstack/php_old/php.ini
  • test and fix any error with php -v (for example missing extensions)
  • [optional] update php version in wampstack/properties.ini
  • Replace wampstack/apache/bin/php7ts.dll by wampstack/php/php7ts.dll
    • This is not mentioned in the other answers but you need this to use the right php version in apache!
  • start apache service

linux execute command remotely

I think this article explains well:

Running Commands on a Remote Linux / UNIX Host

Google is your best friend ;-)

Rails Object to hash

not sure if that's what you need but try this in ruby console:

h = Hash.new
h["name"] = "test"
h["post_number"] = 20
h["active"] = true
h

obviously it will return you a hash in console. if you want to return a hash from within a method - instead of just "h" try using "return h.inspect", something similar to:

def wordcount(str)
  h = Hash.new()
  str.split.each do |key|
    if h[key] == nil
      h[key] = 1
    else
      h[key] = h[key] + 1
    end
  end
  return h.inspect
end

commons httpclient - Adding query string parameters to GET/POST request

The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.

new HttpGet(url + "key1=" + value1 + ...);

Remember to encode the values first (using URLEncoder).

What is the instanceof operator in JavaScript?

There's an important facet to instanceof that does not seem to be covered in any of the comments thus far: inheritance. A variable being evaluated by use of instanceof could return true for multiple "types" due to prototypal inheritance.

For example, let's define a type and a subtype:

function Foo(){ //a Foo constructor
    //assign some props
    return this;
}

function SubFoo(){ //a SubFoo constructor
    Foo.call( this ); //inherit static props
    //assign some new props
    return this;
}

SubFoo.prototype = Object.create(Foo.prototype); // Inherit prototype
SubFoo.prototype.constructor = SubFoo;

Now that we have a couple of "classes" lets make some instances, and find out what they're instances of:

var 
    foo = new Foo()
,   subfoo = new SubFoo()
;

alert( 
    "Q: Is foo an instance of Foo? "
+   "A: " + ( foo instanceof Foo ) 
); // -> true

alert( 
    "Q: Is foo an instance of SubFoo? " 
+   "A: " + ( foo instanceof SubFoo ) 
); // -> false

alert( 
    "Q: Is subfoo an instance of Foo? "
+   "A: " + ( subfoo instanceof Foo ) 
); // -> true

alert( 
    "Q: Is subfoo an instance of SubFoo? "
+   "A: " + ( subfoo instanceof SubFoo ) 
); // -> true

alert( 
    "Q: Is subfoo an instance of Object? "
+   "A: " + ( subfoo instanceof Object ) 
); // -> true

See that last line? All "new" calls to a function return an object that inherits from Object. This holds true even when using object creation shorthand:

alert( 
    "Q: Is {} an instance of Object? "
+   "A: " + ( {} instanceof Object ) 
); // -> true

And what about the "class" definitions themselves? What are they instances of?

alert( 
    "Q: Is Foo an instance of Object? "
+   "A:" + ( Foo instanceof Object) 
); // -> true

alert( 
    "Q: Is Foo an instance of Function? "
+   "A:" + ( Foo instanceof Function) 
); // -> true

I feel that understanding that any object can be an instance of MULTIPLE types is important, since you my (incorrectly) assume that you could differentiate between, say and object and a function by use of instanceof. As this last example clearly shows a function is an object.

This is also important if you are using any inheritance patterns and want to confirm the progeny of an object by methods other than duck-typing.

Hope that helps anyone exploring instanceof.

How to create a pivot query in sql server without aggregate function

Check this out as well: using xml path and pivot

SQLFIDDLE DEMO

| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
|   Asset |  205 |  142 |  421 |
|  Equity |  365 |  214 |  163 |
|  Profit |  524 |  421 |  325 |

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period) 
            FROM demo c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account, ' + @cols + ' from 
            (
                select account
                    , value
                    , period
                from demo
           ) x
            pivot 
            (
                 max(value)
                for period in (' + @cols + ')
            ) p '


execute(@query)

How to add meta tag in JavaScript

$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');

or

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

Though I'm not certain it will have an affect as it will be generated after the page is loaded

If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx

This may allow other meta tags, if you're lucky

Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx

Vue.js getting an element within a component

Vue 2.x

For Official information:

https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced

A simple Example:

On any Element you have to add an attribute ref with a unique value

<input ref="foo" type="text" >

To target that elemet use this.$refs.foo

this.$refs.foo.focus(); // it will focus the input having ref="foo"

Select entries between dates in doctrine 2

You can do either…

$qb->where('e.fecha BETWEEN :monday AND :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

or…

$qb->where('e.fecha > :monday')
   ->andWhere('e.fecha < :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

How to duplicate a whole line in Vim?

Do this:

First, yy to copy the current line, and then p to paste.

Iterator invalidation rules

It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator, std::front_insert_iterator, std::insert_iterator) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.

For example, when you are performing a series of insertion operations into a std::vector by using std::insert_iterator it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.

This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.

For example, this code

std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);

for (unsigned n = 20; n > 0; --n)
  *it_ins++ = rand();

is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it will obviously become invalid, but it_ins will continue to remain valid.

Is there a way to remove unused imports and declarations from Angular 2+?

Edit (as suggested in comments and other people), Visual Studio Code has evolved and provides this functionality in-built as the command "Organize imports", with the following default keyboard shortcuts:

option+Shift+O for Mac

Alt + Shift + O for Windows


Original answer:

I hope this visual studio code extension will suffice your need: https://marketplace.visualstudio.com/items?itemName=rbbit.typescript-hero

It provides following features:

  • Add imports of your project or libraries to your current file
  • Add an import for the current name under the cursor
  • Add all missing imports of a file with one command
  • Intellisense that suggests symbols and automatically adds the needed imports "Light bulb feature" that fixes code you wrote
  • Sort and organize your imports (sort and remove unused)
  • Code outline view of your open TS / TSX document
  • All the cool stuff for JavaScript as well! (experimental stage though, better description below.)

For Mac: control+option+o

For Win: Ctrl+Alt+o

get unique machine id

I second Blindy's suggestion to use the MAC address of the (first?) network adapter. Yes, the MAC address can be spoofed, but this has side effects (you don't want two PCs with the same MAC address in the same network), and it's something that "your average pirate" won't do just to be able to use your software. Considering that there's no 100% solution against software piracy, the MAC address is a good compromise, IMO.

Note, however, that the address will change when the user adds, replaces or removes a network card (or replaces his old PC altogether), so be prepared to help your customers and give them a new key when they change their hardware configuration.

How to make background of table cell transparent

You can do it setting the transparency via style right within the table tag:

<table id="Main table" style="background-color:rgba(0, 0, 0, 0);">

The last digit in the rgba function is for transparency. 1 means 100% opaque, while 0 stands for 100% transparent.

Inline SVG in CSS

I've forked a CodePen demo that had the same problem with embedding inline SVG into CSS. A solution that works with SCSS is to build a simple url-encoding function.

A string replacement function can be created from the built-in str-slice, str-index functions (see css-tricks, thanks to Hugo Giraudel).

Then, just replace %,<,>,",', with the %xxcodes:

@function svg-inline($string){
  $result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  $result: str-replace($result, '%', '%25');
  $result: str-replace($result, '"', '%22');
  $result: str-replace($result, "'", '%27');
  $result: str-replace($result, ' ', '%20');
  $result: str-replace($result, '<', '%3C');
  $result: str-replace($result, '>', '%3E');
  @return "data:image/svg+xml;utf8," + $result;
}

$mySVG: svg-inline("<svg>...</svg>");

html {
  height: 100vh;
  background: url($mySVG) 50% no-repeat;
}

There is also a image-inline helper function available in Compass, but since it is not supported in CodePen, this solution might probably be useful.

Demo on CodePen: http://codepen.io/terabaud/details/PZdaJo/

Get MAC address using shell script

oh, if you want only the mac ether mac address, you can use that:

ifconfig | grep "ether*" | tr -d ' ' | tr -d '\t' | cut -c 6-42

(work on macintosh)

  • ifconfig -- get all info
  • grep -- keep the line with address
  • tr -- clean all
  • cut -- remove the "ether" to have only the address

Capture iOS Simulator video for App Preview

Taking a Screenshot or Recording a Video Using the Command Line

You can take a screenshot or record a video of the simulator window using the xcrun command-line utility.

  1. Launch your app in Simulator.

  2. Launch Terminal (located in /Applications/Utilities), and enter the appropriate command:

    • To take a screenshot, use the screenshot operation:

      xcrun simctl io booted screenshot
      

      You can specify an optional filename at the end of the command.

    • To record a video, use the recordVideo operation:

      xcrun simctl io booted recordVideo <filename>.<extension>
      

      To stop recording, press Control-C in Terminal.

      Note: You must specify a filename for recordVideo.

    The default location for the created file is the current directory.

    For more information on simctl, run this command in Terminal:

    xcrun simctl help
    

    For more information on the io subcommand of simctl, run this command:

    xcrun simctl io help
    

From Apple Documentation.

How do I configure the proxy settings so that Eclipse can download new plugins?

For me, I go to \eclipse\configuration.settings\org.eclipse.core.net.prefs set the property systemProxiesEnabled to true manually and restart eclipse.

Static nested class in Java, why?

The Sun page you link to has some key differences between the two:

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
...

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

There is no need for LinkedList.Entry to be top-level class as it is only used by LinkedList (there are some other interfaces that also have static nested classes named Entry, such as Map.Entry - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.

As Jon Skeet points out, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.

How do I detect if a user is already logged in Firebase?

First import the following

import Firebase
import FirebaseAuth

Then

    // Check if logged in
    if (Auth.auth().currentUser != null) {
      // User is logged in   
    }else{
      // User is not logged in
    }

Get selected option text with JavaScript

Plain JavaScript

var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;

jQuery:

$("#box1 option:selected").text();

C# Convert List<string> to Dictionary<string, string>

Use this:

var dict = list.ToDictionary(x => x);

See MSDN for more info.

As Pranay points out in the comments, this will fail if an item exists in the list multiple times.
Depending on your specific requirements, you can either use var dict = list.Distinct().ToDictionary(x => x); to get a dictionary of distinct items or you can use ToLookup instead:

var dict = list.ToLookup(x => x);

This will return an ILookup<string, string> which is essentially the same as IDictionary<string, IEnumerable<string>>, so you will have a list of distinct keys with each string instance under it.

Fundamental difference between Hashing and Encryption algorithms

when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key

when it comes to authorization you use hashing.There is no key in hashing

Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password

why is hashing irreversible :

Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.

Use custom build output folder when using create-react-app

Windows Powershell Script

//package.json
"scripts": {
    "postbuildNamingScript": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./powerShellPostBuildScript.ps1",


// powerShellPostBuildScript.ps1
move build/static/js build/new-folder-name 
(Get-Content build/index.html).replace('static/js', 'new-folder-name') | Set-Content 
build/index.html
"Finished Running BuildScript"

Running npm run postbuildNamingScript in powershell will move the JS files to build/new-folder-name and point to the new location from index.html.

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

Test if number is odd or even

Try this,

$number = 10;
 switch ($number%2)
 {
 case 0:
 echo "It's even";
 break;
 default:
 echo "It's odd";
 }

Difference between `constexpr` and `const`

As @0x499602d2 already pointed out, const only ensures that a value cannot be changed after initialization where as constexpr (introduced in C++11) guarantees the variable is a compile time constant.
Consider the following example(from LearnCpp.com):

cout << "Enter your age: ";
int age;
cin >> age;

const int myAge{age};        // works
constexpr int someAge{age};  // error: age can only be resolved at runtime

bootstrap responsive table content wrapping

_x000D_
_x000D_
.table td.abbreviation {_x000D_
  max-width: 30px;_x000D_
}_x000D_
.table td.abbreviation p {_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
_x000D_
}
_x000D_
<table class="table">_x000D_
<tr>_x000D_
 <td class="abbreviation"><p>ABC DEF</p></td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Uncaught TypeError: (intermediate value)(...) is not a function

Error Case:

var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Output:

TypeError: (intermediate value)(intermediate value) is not a function

Fix: You are missing a semi-colon (;) to separate the expressions

userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Binary Search Tree - Java Implementation

This program has a functions for

  1. Add Node
  2. Display BST(Inorder)
  3. Find Element
  4. Find Successor

    class BNode{
        int data;
        BNode left, right;
    
        public BNode(int data){
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }
    
    public class BST {
        static BNode root;
    
        public int add(int value){
            BNode newNode, current;
    
            newNode = new BNode(value);
            if(root == null){
                root = newNode;
                current = root;
            }
            else{
                current = root;
                while(current.left != null || current.right != null){
                    if(newNode.data < current.data){
                        if(current.left != null)
                            current = current.left;
                        else
                            break;
                    }                   
                    else{
                        if(current.right != null)
                            current = current.right;
                        else
                            break;
                    }                                           
                }
                if(newNode.data < current.data)
                    current.left = newNode;
                else
                    current.right = newNode;
            }
    
            return value;
        }
    
        public void inorder(BNode root){
            if (root != null) {
                inorder(root.left);
                System.out.println(root.data);
                inorder(root.right);
            }
        }
    
        public boolean find(int value){
            boolean flag = false;
            BNode current;
            current = root;
            while(current!= null){
                if(current.data == value){
                    flag = true;
                    break;
                }   
                else if(current.data > value)
                    current = current.left;
                else
                    current = current.right;
            }
            System.out.println("Is "+value+" present in tree? : "+flag);
            return flag;
        }
    
        public void successor(int value){
            BNode current;
            current = root;
    
            if(find(value)){
                while(current.data != value){
                    if(value < current.data && current.left != null){
                        System.out.println("Node is: "+current.data);
                        current = current.left;
                    }
                    else if(value > current.data && current.right != null){
                        System.out.println("Node is: "+current.data);
                        current = current.right;
                    }                   
                }
            }
            else
                System.out.println(value+" Element is not present in tree");
        }
    
        public static void main(String[] args) {
    
            BST b = new BST();
            b.add(50);
            b.add(30);
            b.add(20);
            b.add(40);
            b.add(70);
            b.add(60);
            b.add(80);
            b.add(90);
    
            b.inorder(root);
            b.find(30);
            b.find(90);
            b.find(100);
            b.find(50);
    
            b.successor(90);
            System.out.println();
            b.successor(70);
        }
    
    }
    

jQuery: load txt file and insert into div

Try

$(".text").text(data);

Or to convert the data received to a string.

Is a DIV inside a TD a bad idea?

Using a div instide a td is not worse than any other way of using tables for layout. (Some people never use tables for layout though, and I happen to be one of them.)

If you use a div in a td you will however get in a situation where it might be hard to predict how the elements will be sized. The default for a div is to determine its width from its parent, and the default for a table cell is to determine its size depending on the size of its content.

The rules for how a div should be sized is well defined in the standards, but the rules for how a td should be sized is not as well defined, so different browsers use slightly different algorithms.

How do I include negative decimal numbers in this regular expression?

If you have this val="-12XXX.0abc23" and you want to extract only the decimal number, in this case this regex (^-?[0-9]\d*(\.\d+)?$) will not help you to achieve it.
this is the proper code with the correct detection regex:

_x000D_
_x000D_
var val="-12XXX.0abc23";_x000D_
val = val.replace(/^\.|[^-?\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');_x000D_
console.log(val);
_x000D_
_x000D_
_x000D_

How can I parse a string with a comma thousand separator to a number?

If you want to avoid the problem that David Meister posted and you are sure about the number of decimal places, you can replace all dots and commas and divide by 100, ex.:

var value = "2,299.00";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/100;

or if you have 3 decimals

var value = "2,299.001";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/1000;

It's up to you if you want to use parseInt, parseFloat or Number. Also If you want to keep the number of decimal places you can use the function .toFixed(...).

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

jQuery onclick toggle class name

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>

jQuery UI - Close Dialog When Clicked Outside

Forget using another plugin:

Here are 3 methods to close a jquery UI dialog when clicking outside popin:

If the dialog is modal/has background overlay: http://jsfiddle.net/jasonday/6FGqN/

jQuery(document).ready(function() {
    jQuery("#dialog").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 100,
        modal: true,
        open: function(){
            jQuery('.ui-widget-overlay').bind('click',function(){
                jQuery('#dialog').dialog('close');
            })
        }
    });
}); 

If dialog is non-modal Method 1: method 1: http://jsfiddle.net/jasonday/xpkFf/

 // Close Pop-in If the user clicks anywhere else on the page
                     jQuery('body')
                      .bind(
                       'click',
                       function(e){
                        if(
                         jQuery('#dialog').dialog('isOpen')
                         && !jQuery(e.target).is('.ui-dialog, a')
                         && !jQuery(e.target).closest('.ui-dialog').length
                        ){
                         jQuery('#dialog').dialog('close');
                        }
                       }
                      );

Non-Modal dialog Method 2: http://jsfiddle.net/jasonday/eccKr/

  $(function() {
            $( "#dialog" ).dialog({
                autoOpen: false, 
                minHeight: 100,
                width: 342,
                draggable: true,
                resizable: false,
                modal: false,
                closeText: 'Close',
                  open: function() {
                      closedialog = 1;
                      $(document).bind('click', overlayclickclose);
                  },
                  focus: function() {
                      closedialog = 0;
                  },
                  close: function() {
                      $(document).unbind('click');
                  }



        });

         $('#linkID').click(function() {
            $('#dialog').dialog('open');
            closedialog = 0;
        });

         var closedialog;

          function overlayclickclose() {
              if (closedialog) {
                  $('#dialog').dialog('close');
              }

              //set to one because click on dialog box sets to zero
              closedialog = 1;
          }


  });

How to add anything in <head> through jquery/javascript?

Try a javascript pure:

Library JS:

appendHtml = function(element, html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    while (div.children.length > 0) {
        element.appendChild(div.children[0]);
    }
}

Type: appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');

or jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

Calculate difference between two dates (number of days)?

The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:

(EndDate.Date - StartDate.Date).Days

Again assuming StartDate and EndDate are of type DateTime.

Why are #ifndef and #define used in C++ header files?

Those are called #include guards.

Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.

When the code is included again, the first ifndef fails, resulting in a blank file.

That prevents double declaration of any identifiers such as types, enums and static variables.

How to destroy JWT Tokens on logout?

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client-side upon log out

  • Query provided token against The Blacklist on every authorized request

Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

For more information, see How to log out when using JWT. by Arpy Vanyan

Convert bytes to bits in python

Here how to do it using format()

print "bin_signedDate : ", ''.join(format(x, '08b') for x in bytevector)

It is important the 08b . That means it will be a maximum of 8 leading zeros be appended to complete a byte. If you don't specify this then the format will just have a variable bit length for each converted byte.

Launch an app on OS X with command line

In case your app needs to work on files (what you would normally expect to pass as: ./myApp *.jpg), you would do it like this:

open *.jpg -a myApp

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.


Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

What is the simplest SQL Query to find the second largest value?

MSSQL

SELECT  *
  FROM [Users]
    order by UserId desc OFFSET 1 ROW 
FETCH NEXT 1 ROW ONLY;

MySQL

SELECT  *
  FROM Users
    order by UserId desc LIMIT 1 OFFSET 1

No need of sub queries ... just skip one row and select second rows after order by descending

How do I concatenate two strings in Java?

"+" not "."

But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.

jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;
    }
}

I hope this helps!

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


If the file you try to recover has Content-Encoding: gzip in the header section, and you are using linux (or as in my case, you have Cygwin installed) you can do the following:

  1. visit chrome://view-http-cache/ and click the page you want to recover
  2. copy the last (fourth) section of the page verbatim to a text file (say: a.txt)
  3. xxd -r a.txt| gzip -d

Note that other answers suggest passing -p option to xxd - I had troubles with that presumably because the fourth section of the cache is not in the "postscript plain hexdump style" but in a "default style".

It also does not seem necessary to replace double spaces with a single space, as chrome_xxd.py is doing (in case it is necessary you can use sed 's/ / /g' for that).

Remove white space below image

.youtube-thumb img {display:block;} or .youtube-thumb img {float:left;}

In Unix, how do you remove everything in the current directory and below it?

Practice safe computing. Simply go up one level in the hierarchy and don't use a wildcard expression:

cd ..; rm -rf -- <dir-to-remove>

The two dashes -- tell rm that <dir-to-remove> is not a command-line option, even when it begins with a dash.

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

When I had this problem, I installed 'Remote Tools for Visual Studio 2015' from MSDN. I attached my local VS to the server to debug.

I appreciate that some folks may not have the ability to either install on or access other servers, but I thought I'd throw it out there as an option.

Load view from an external xib file in storyboard

My full example is here, but I will provide a summary below.

Layout

Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

Make the swift file the xib file's owner.

enter image description here Code

Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

import UIKit
class ResuableCustomView: UIView {

    let nibName = "ReusableCustomView"
    var contentView: UIView?

    @IBOutlet weak var label: UILabel!
    @IBAction func buttonTap(_ sender: UIButton) {
        label.text = "Hi"
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
        contentView = view
    }

    func loadViewFromNib() -> UIView? {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName, bundle: bundle)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }
}

Use it

Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

enter image description here


For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

  1. Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift
  2. Create a .xib file and style it as you want. i.e. MyCustomClass.xib
  3. Set the File's Owner of the .xib file to be your custom class (MyCustomClass)
  4. GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.
  5. Hook up your outlets as you normally would using the Assistant Editor.
    • NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.
  6. Make sure your custom class has @IBDesignable before the class statement.
  7. Make your custom class conform to the NibLoadable protocol referenced below.
    • NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.
  8. Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.
  9. Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).
  10. Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Compare two folders which has many files inside contents

I used

diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

simple using linq, change as you see fit for whatever control your dealing with.

        private void DisableButtons()
    {
        foreach (var ctl in Controls.OfType<Button>())
        {
            ctl.Enabled = false;
        }
    }

    private void EnableButtons()
    {
        foreach (var ctl in Controls.OfType<Button>())
        {
            ctl.Enabled = true;
        }
    }

How to control the line spacing in UILabel

In Swift 2.0...

Add an extension:

extension UIView {
    func attributesWithLineHeight(font: String, color: UIColor, fontSize: CGFloat, kern: Double, lineHeightMultiple: CGFloat) -> [String: NSObject] {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.lineHeightMultiple = lineHeightMultiple

        let attribute = [
            NSForegroundColorAttributeName: color,
            NSKernAttributeName: kern,
            NSFontAttributeName : UIFont(name: font, size: fontSize)!,
            NSParagraphStyleAttributeName: titleParagraphStyle
        ]
        return attribute
    }
}

Now, just set your UILabel as attributedText:

self.label.attributedText = NSMutableAttributedString(string: "SwiftExample", attributes: attributesWithLineHeight("SourceSans-Regular", color: UIColor.whiteColor(), fontSize: 20, kern: 2.0, lineHeightMultiple: 0.5))    

Obviously, I added a bunch of parameters that you may not need. Play around -- feel free to rewrite the method -- I was looking for this on a bunch of different answers so figured I'd post the whole extension in case it helps someone out there... -rab

Java: Date from unix timestamp

tl;dr

Instant.ofEpochSecond( 1_280_512_800L )

2010-07-30T18:00:00Z

java.time

The new java.time framework built into Java 8 and later is the successor to Joda-Time.

These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.

Instant instant = Instant.ofEpochSecond( 1_280_512_800L );

instant.toString(): 2010-07-30T18:00:00Z

See that code run live at IdeOne.com.

Table of date-time types in Java, both modern and legacy

Asia/Kabul or Asia/Tehran time zones ?

You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).

If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.

ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z );  // Same moment, same point on timeline, but seen as different wall-clock time.

2010-07-30T22:30+04:30[Asia/Tehran]

Converting from java.time to legacy classes

You should stick with the new java.time classes. But you can convert to old if required.

java.util.Date date = java.util.Date.from( instant );

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).

DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );

Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.

java.util.Date date = dateTime.toDate();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Styling input radio with css

Like this

DEMO

CSS

#slideselector {
    position: absolue;
    top:0;
    left:0;
    border: 2px solid black;
    padding-top: 1px;
}
.slidebutton {
    height: 21px;
    margin: 2px;
}
#slideshow { 
    margin: 50px auto; 
    position: relative; 
    width: 240px; 
    height: 240px; 
    padding: 10px; 
    box-shadow: 0 0 20px rgba(0,0,0,0.4); 
}

#slideshow > div { 
    position: absolute; 
    top: 10px; 
    left: 10px; 
    right: 10px; 
    bottom: 10px;
    overflow:hidden;
}

.imgLike {
    width:100%;
    height:100%;
}
/* Radio */

input[type="radio"] {
    background-color: #ddd;
    background-image: -webkit-linear-gradient(0deg, transparent 20%, hsla(0,0%,100%,.7), transparent 80%),
                      -webkit-linear-gradient(90deg, transparent 20%, hsla(0,0%,100%,.7), transparent 80%);
    border-radius: 10px;
    box-shadow: inset 0 1px 1px hsla(0,0%,100%,.8),
                0 0 0 1px hsla(0,0%,0%,.6),
                0 2px 3px hsla(0,0%,0%,.6),
                0 4px 3px hsla(0,0%,0%,.4),
                0 6px 6px hsla(0,0%,0%,.2),
                0 10px 6px hsla(0,0%,0%,.2);
    cursor: pointer;
    display: inline-block;
    height: 15px;
    margin-right: 15px;
    position: relative;
    width: 15px;
    -webkit-appearance: none;
}
input[type="radio"]:after {
    background-color: #444;
    border-radius: 25px;
    box-shadow: inset 0 0 0 1px hsla(0,0%,0%,.4),
                0 1px 1px hsla(0,0%,100%,.8);
    content: '';
    display: block;
    height: 7px;
    left: 4px;
    position: relative;
    top: 4px;
    width: 7px;
}
input[type="radio"]:checked:after {
    background-color: #f66;
    box-shadow: inset 0 0 0 1px hsla(0,0%,0%,.4),
                inset 0 2px 2px hsla(0,0%,100%,.4),
                0 1px 1px hsla(0,0%,100%,.8),
                0 0 2px 2px hsla(0,70%,70%,.4);
}

php hide ALL errors

To hide errors only from users but displaying logs errors in apache log

error_reporting(E_ALL);
ini_set('display_errors', 0);

1 - Displaying error only in log
2 - hide from users

What is the standard exception to throw in Java for not supported/implemented operations?

If you want more granularity and better decription, you could use NotImplementedException from commons-lang

Warning: Available before versions 2.6 and after versions 3.2, only.

npm install -g less does not work: EACCES: permission denied

In linux make sure getting all authority with:

sudo su

Calculating frames per second in a game

This is what I have used in many games.

#define MAXSAMPLES 100
int tickindex=0;
int ticksum=0;
int ticklist[MAXSAMPLES];

/* need to zero out the ticklist array before starting */
/* average will ramp up until the buffer is full */
/* returns average ticks per frame over the MAXSAMPLES last frames */

double CalcAverageTick(int newtick)
{
    ticksum-=ticklist[tickindex];  /* subtract value falling off */
    ticksum+=newtick;              /* add new value */
    ticklist[tickindex]=newtick;   /* save new value so it can be subtracted later */
    if(++tickindex==MAXSAMPLES)    /* inc buffer index */
        tickindex=0;

    /* return average */
    return((double)ticksum/MAXSAMPLES);
}

JavaScript - Replace all commas in a string

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

how to remove the bold from a headline?

style is accordingly vis css. An example

<h1 class="mynotsoboldtitle">Im not bold</h1>
<style>
.mynotsoboldtitle { font-weight:normal; }
</style>

Should I put input elements inside a label element?

Behavior difference: clicking in the space between label and input

If you click on the space between the label and the input it activates the input only if the label contains the input.

This makes sense since in this case the space is just another character of the label.

_x000D_
_x000D_
<p>Inside:</p>_x000D_
_x000D_
<label>_x000D_
  <input type="checkbox" />_x000D_
  |&lt;----- Label. Click between me and the checkbox._x000D_
</label>_x000D_
_x000D_
<p>Outside:</p>_x000D_
_x000D_
<input type="checkbox" id="check" />_x000D_
<label for="check">|&lt;----- Label. Click between me and the checkbox.</label>
_x000D_
_x000D_
_x000D_

Being able to click between label and box means that it is:

  • easier to click
  • less clear where things start and end

Bootstrap checkbox v3.3 examples use the input inside: http://getbootstrap.com/css/#forms Might be wise to follow them. But they changed their minds in v4.0 https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios so I don't know what is wise anymore:

Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our <input>s and <label>s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.

UX question that discusses this point in detail: https://ux.stackexchange.com/questions/23552/should-the-space-between-the-checkbox-and-label-be-clickable

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

adding the following lines to my /etc/environment file worked

LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8

How to delete a file after checking whether it exists

This will be the simplest way,

if (System.IO.File.Exists(filePath)) 
{
  System.IO.File.Delete(filePath);
  System.Threading.Thread.Sleep(20);
}

Thread.sleep will help to work perfectly, otherwise, it will affect the next step if we doing copy or write the file.

Another way I did is,

if (System.IO.File.Exists(filePath))
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(filePath);
}

How to connect to remote Redis server?

One thing that confused me a little bit with this command is that if redis-cli fails to connect using the passed connection string it will still put you in the redis-cli shell, i.e:

redis-cli
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected> 

You'll then need to exit to get yourself out of the shell. I wasn't paying much attention here and kept passing in new redis-cli commands wondering why the command wasn't using my passed connection string.

Check if returned value is not null and if so assign it, in one line, with one method call

Since Java 9 you have Objects#requireNonNullElse which does:

public static <T> T requireNonNullElse(T obj, T defaultObj) {
    return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
}

Your code would be

dinner = Objects.requireNonNullElse(cage.getChicken(), getFreeRangeChicken());

Which is 1 line and calls getChicken() only once, so both requirements are satisfied.

Note that the second argument cannot be null as well; this method forces non-nullness of the returned value.

Consider also the alternative Objects#requireNonNullElseGet:

public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)

which does not even evaluate the second argument if the first is not null, but does have the overhead of creating a Supplier.

Can someone explain how to append an element to an array in C programming?

Short answer is: You don't have any choice other than:

arr[4] = 5;

How to resolve 'npm should be run outside of the node repl, in your normal shell'

For Windows users, run npm commands from the Command Prompt (cmd.exe), not Node.Js (node.exe). So your "normal shell" is cmd.exe. (I agree this message can be confusing for a Windows, Node newbie.)

By the way, the Node.js Command Prompt is actually just an easy shortcut to cmd.exe.

Below is an example screenshot for installing grunt from cmd.exe:

enter image description here

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

PHP - concatenate or directly insert variables in string

You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.

If the variable inside the double quote PHP take time to parse variable.

Check out this Single quotes or double quotes for variable concatenation?

This is another example Is there a performance benefit single quote vs double quote in php?

I did not understand why this answer in above link get upvoted and why this answer got downvote.

As I said same thing.

You can look at here as well

What is faster in PHP, single or double quotes?

How to get current CPU and RAM usage in Python?

To get a line-by-line memory and time analysis of your program, I suggest using memory_profiler and line_profiler.

Installation:

# Time profiler
$ pip install line_profiler
# Memory profiler
$ pip install memory_profiler
# Install the dependency for a faster analysis
$ pip install psutil

The common part is, you specify which function you want to analyse by using the respective decorators.

Example: I have several functions in my Python file main.py that I want to analyse. One of them is linearRegressionfit(). I need to use the decorator @profile that helps me profile the code with respect to both: Time & Memory.

Make the following changes to the function definition

@profile
def linearRegressionfit(Xt,Yt,Xts,Yts):
    lr=LinearRegression()
    model=lr.fit(Xt,Yt)
    predict=lr.predict(Xts)
    # More Code

For Time Profiling,

Run:

$ kernprof -l -v main.py

Output

Total time: 0.181071 s
File: main.py
Function: linearRegressionfit at line 35

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    35                                           @profile
    36                                           def linearRegressionfit(Xt,Yt,Xts,Yts):
    37         1         52.0     52.0      0.1      lr=LinearRegression()
    38         1      28942.0  28942.0     75.2      model=lr.fit(Xt,Yt)
    39         1       1347.0   1347.0      3.5      predict=lr.predict(Xts)
    40                                           
    41         1       4924.0   4924.0     12.8      print("train Accuracy",lr.score(Xt,Yt))
    42         1       3242.0   3242.0      8.4      print("test Accuracy",lr.score(Xts,Yts))

For Memory Profiling,

Run:

$ python -m memory_profiler main.py

Output

Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    35  125.992 MiB  125.992 MiB   @profile
    36                             def linearRegressionfit(Xt,Yt,Xts,Yts):
    37  125.992 MiB    0.000 MiB       lr=LinearRegression()
    38  130.547 MiB    4.555 MiB       model=lr.fit(Xt,Yt)
    39  130.547 MiB    0.000 MiB       predict=lr.predict(Xts)
    40                             
    41  130.547 MiB    0.000 MiB       print("train Accuracy",lr.score(Xt,Yt))
    42  130.547 MiB    0.000 MiB       print("test Accuracy",lr.score(Xts,Yts))

Also, the memory profiler results can also be plotted using matplotlib using

$ mprof run main.py
$ mprof plot

enter image description here Note: Tested on

line_profiler version == 3.0.2

memory_profiler version == 0.57.0

psutil version == 5.7.0


EDIT: The results from the profilers can be parsed using the TAMPPA package. Using it, we can get line-by-line desired plots as plot

How to Auto resize HTML table cell to fit the text size

Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto; to the <table> element.

You can't specify target table for update in FROM clause

You can make this in three steps:

CREATE TABLE test2 AS
SELECT PersId 
FROM pers p
WHERE (
  chefID IS NOT NULL 
  OR gehalt < (
    SELECT MAX (
      gehalt * 1.05
    )
    FROM pers MA
    WHERE MA.chefID = p.chefID
  )
)

...

UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE PersId
IN (
  SELECT PersId
  FROM test2
)
DROP TABLE test2;

or

UPDATE Pers P, (
  SELECT PersId
  FROM pers p
  WHERE (
   chefID IS NOT NULL 
   OR gehalt < (
     SELECT MAX (
       gehalt * 1.05
     )
     FROM pers MA
     WHERE MA.chefID = p.chefID
   )
 )
) t
SET P.gehalt = P.gehalt * 1.05
WHERE p.PersId = t.PersId

Unknown version of Tomcat was specified in Eclipse

I am on MacOS and installed tomcat using homebrew, Following path fixed my problem

/usr/local/Cellar/tomcat/9.0.14/libexec

Returning a boolean value in a JavaScript function

You could simplify this a lot:

  • Check whether one is not empty
  • Check whether they are equal

This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:

function validatePassword()
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   return password.value !== "" && password.value === confirm_password.value;
       //       not empty       and              equal
}

The pipe ' ' could not be found angular2 custom pipe

Make sure you are not facing a "cross module" problem

If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.

In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.

I have declared a that the component in which you are using the pipe is

the Pipe Module

 import { NgModule }      from '@angular/core';
 import { myDateFormat }          from '../directives/myDateFormat';

 @NgModule({
     imports:        [],
     declarations:   [myDateFormat],
     exports:        [myDateFormat],
 })

 export class PipeModule {

   static forRoot() {
      return {
          ngModule: PipeModule,
          providers: [],
      };
   }
 } 

Usage in another module (e.g. app.module)

  // Import APPLICATION MODULES
  ...
  import { PipeModule }    from './tools/PipeModule';

  @NgModule({
     imports: [
    ...
    , PipeModule.forRoot()
    ....
  ],

What are Bearer Tokens and token_type in OAuth 2?

Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.

https://tools.ietf.org/html/rfc6750

Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.

If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.

However, it will be hard way since the mac spec is still changing rapidly.

https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05

How to convert numbers between hexadecimal and decimal

This is not really easiest way but this source code enable you to right any types of octal number i.e 23.214, 23 and 0.512 and so on. Hope this will help you..

    public string octal_to_decimal(string m_value)
    {
        double i, j, x = 0;
        Int64 main_value;
        int k = 0;
        bool pw = true, ch;
        int position_pt = m_value.IndexOf(".");
        if (position_pt == -1)
        {
            main_value = Convert.ToInt64(m_value);
            ch = false;
        }
        else
        {
            main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt));
            ch = true;
        }

        while (k <= 1)
        {
            do
            {
                i = main_value % 10;                                        // Return Remainder
                i = i * Convert.ToDouble(Math.Pow(8, x));                   // calculate power
                if (pw)
                    x++;
                else
                    x--;
                o_to_d = o_to_d + i;                                        // Saving Required calculated value in main variable
                main_value = main_value / 10;                               // Dividing the main value 
            }
            while (main_value >= 1);
            if (ch)
            {
                k++;
                main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1)));
            }
            else
                k = 2;
            pw = false;
            x = -1;
        }
        return (Convert.ToString(o_to_d));
    }    

How to convert object to Dictionary<TKey, TValue> in C#?

You can create a generic extension method and then use it on the object like:

public static class Extensions
{
    public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this Object obj)
    {
        // if obj is null throws exception
        Contract.Requires(obj != null);

        // gets the type of the obj parameter
        var type = obj.GetType();
        // checks if obj is of type KeyValuePair
        if (type.IsGenericType && type == typeof(KeyValuePair<TKey, TValue>))
        {

            return new KeyValuePair<TKey, TValue>(
                                                    (TKey)type.GetProperty("Key").GetValue(obj, null), 
                                                    (TValue)type.GetProperty("Value").GetValue(obj, null)
                                                 );

        }
        // if obj type does not match KeyValuePair throw exception
        throw new ArgumentException($"obj argument must be of type KeyValuePair<{typeof(TKey).FullName},{typeof(TValue).FullName}>");   
 }

and usage would be like:

KeyValuePair<string,long> kvp = obj.ToKeyValuePair<string,long>();

How to send email from MySQL 5.1

I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:

  1. Have application logic detect the need to send an e-mail and send it.
  2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.

How to change the Text color of Menu item in Android?

Thanks to max.musterman, this is the solution I got to work in level 22:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);
    setMenuTextColor(menu, R.id.displaySummary, R.string.show_summary);
    setMenuTextColor(menu, R.id.about, R.string.text_about);
    setMenuTextColor(menu, R.id.importExport, R.string.import_export);
    setMenuTextColor(menu, R.id.preferences, R.string.settings);
    return true;
}

private void setMenuTextColor(Menu menu, int menuResource, int menuTextResource) {
    MenuItem item = menu.findItem(menuResource);
    SpannableString s = new SpannableString(getString(menuTextResource));
    s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0);
    item.setTitle(s);
}

The hardcoded Color.BLACK could become an additional parameter to the setMenuTextColor method. Also, I only used this for menu items which were android:showAsAction="never".

Get POST data in C#/ASP.NET

The following is OK in HTML4, but not in XHTML. Check your editor.

<input type=button value="Submit" />

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

Django: Display Choice Value

Others have pointed out that a get_FOO_display method is what you need. I'm using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Get property value from string using reflection

Here is another way to find a nested property that doesn't require the string to tell you the nesting path. Credit to Ed S. for the single property method.

    public static T FindNestedPropertyValue<T, N>(N model, string propName) {
        T retVal = default(T);
        bool found = false;

        PropertyInfo[] properties = typeof(N).GetProperties();

        foreach (PropertyInfo property in properties) {
            var currentProperty = property.GetValue(model, null);

            if (!found) {
                try {
                    retVal = GetPropValue<T>(currentProperty, propName);
                    found = true;
                } catch { }
            }
        }

        if (!found) {
            throw new Exception("Unable to find property: " + propName);
        }

        return retVal;
    }

        public static T GetPropValue<T>(object srcObject, string propName) {
        return (T)srcObject.GetType().GetProperty(propName).GetValue(srcObject, null);
    }

How to trim a string after a specific character in java

Try this:

String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));

How to take off line numbers in Vi?

Display line numbers:

:set nu

Stop showing the line numbers:

:set nonu

Its short for :set nonumber

ps. These commands are to be run in normal mode.

Progress Bar with HTML and CSS

If you wish to have a progress bar without adding some code PACE can be an awesome tool for you.

Just include pace.js and a CSS theme of your choice, and you get a beautiful progress indicator for your page load and AJAX navigation. Best thing with PACE is the auto detection of progress.

It contains various themes and color schemes as well.

Worth a try.

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

How to split a String by space

Since it's been a while since these answers were posted, here's another more current way to do what's asked:

List<String> output = new ArrayList<>();
try (Scanner sc = new Scanner(inputString)) {
    while (sc.hasNext()) output.add(sc.next());
}

Now you have a list of strings (which is arguably better than an array); if you do need an array, you can do output.toArray(new String[0]);

What is a lambda expression in C++11?

One of the best explanation of lambda expression is given from author of C++ Bjarne Stroustrup in his book ***The C++ Programming Language*** chapter 11 (ISBN-13: 978-0321563842):

What is a lambda expression?

A lambda expression, sometimes also referred to as a lambda function or (strictly speaking incorrectly, but colloquially) as a lambda, is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator(), later making an object of that class, and finally invoking it, we can use a shorthand.

When would I use one?

This is particularly useful when we want to pass an operation as an argument to an algorithm. In the context of graphical user interfaces (and elsewhere), such operations are often referred to as callbacks.

What class of problem do they solve that wasn't possible prior to their introduction?

Here i guess every action done with lambda expression can be solved without them, but with much more code and much bigger complexity. Lambda expression this is the way of optimization for your code and a way of making it more attractive. As sad by Stroustup :

effective ways of optimizing

Some examples

via lambda expression

void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0
{
    for_each(begin(v),end(v),
        [&os,m](int x) { 
           if (x%m==0) os << x << '\n';
         });
}

or via function

class Modulo_print {
         ostream& os; // members to hold the capture list int m;
     public:
         Modulo_print(ostream& s, int mm) :os(s), m(mm) {} 
         void operator()(int x) const
           { 
             if (x%m==0) os << x << '\n'; 
           }
};

or even

void print_modulo(const vector<int>& v, ostream& os, int m) 
     // output v[i] to os if v[i]%m==0
{
    class Modulo_print {
        ostream& os; // members to hold the capture list
        int m; 
        public:
           Modulo_print (ostream& s, int mm) :os(s), m(mm) {}
           void operator()(int x) const
           { 
               if (x%m==0) os << x << '\n';
           }
     };
     for_each(begin(v),end(v),Modulo_print{os,m}); 
}

if u need u can name lambda expression like below:

void print_modulo(const vector<int>& v, ostream& os, int m)
    // output v[i] to os if v[i]%m==0
{
      auto Modulo_print = [&os,m] (int x) { if (x%m==0) os << x << '\n'; };
      for_each(begin(v),end(v),Modulo_print);
 }

Or assume another simple sample

void TestFunctions::simpleLambda() {
    bool sensitive = true;
    std::vector<int> v = std::vector<int>({1,33,3,4,5,6,7});

    sort(v.begin(),v.end(),
         [sensitive](int x, int y) {
             printf("\n%i\n",  x < y);
             return sensitive ? x < y : abs(x) < abs(y);
         });


    printf("sorted");
    for_each(v.begin(), v.end(),
             [](int x) {
                 printf("x - %i;", x);
             }
             );
}

will generate next

0

1

0

1

0

1

0

1

0

1

0 sortedx - 1;x - 3;x - 4;x - 5;x - 6;x - 7;x - 33;

[] - this is capture list or lambda introducer: if lambdas require no access to their local environment we can use it.

Quote from book:

The first character of a lambda expression is always [. A lambda introducer can take various forms:

[]: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables.

[&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference.

[=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression.

[capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements.

[&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value.

[=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference.

Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment.

Additional

Lambda expression format

enter image description here

Additional references:

Is there an R function for finding the index of an element in a vector?

The function match works on vectors:

x <- sample(1:10)
x
# [1]  4  5  9  3  8  1  6 10  7  2
match(c(4,8),x)
# [1] 1 5

match only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.

For multiple matching, %in% is the way to go:

x <- sample(1:4,10,replace=TRUE)
x
# [1] 3 4 3 3 2 3 1 1 2 2
which(x %in% c(2,4))
# [1]  2  5  9 10

%in% returns a logical vector as long as the first argument, with a TRUE if that value can be found in the second argument and a FALSE otherwise.

How to update/upgrade a package using pip?

For a non-specific package and a more general solution you can check out pip-review, a tool that checks what packages could/should be updated.

$ pip-review --interactive
requests==0.14.0 is available (you have 0.13.2)
Upgrade now? [Y]es, [N]o, [A]ll, [Q]uit y

Convert an integer to a float number

Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

Which means that you need to use float64(integer_value).

"id cannot be resolved or is not a field" error?

I also had this error when I was working in a Java class once. My problem was simply that my xml file, with the references in it, was not saved. If you have both the xml file and java class open in tabs, check to make sure the xml file name in the tab doesn't have a * by it.

Hope this helps.

React-Router: No Not Found Route?

I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:

if (!place) return <NotFound />;

hope that helps!

How to replace comma with a dot in the number (or any replacement)

As replace() creates/returns a new string rather than modifying the original (tt), you need to set the variable (tt) equal to the new string returned from the replace function.

tt = tt.replace(/,/g, '.')

JSFiddle

Java ElasticSearch None of the configured nodes are available

Faced similar issue, and here is the solution

Example :

  1. In elasticsearch.yml add the below properties

    cluster.name: production
    node.name: node1
    network.bind_host: 10.0.1.22
    network.host: 0.0.0.0
    transport.tcp.port: 9300
    
  2. Add the following in Java Elastic API for Bulk Push (just a code snippet). For IP Address add public IP address of elastic search machine

    Client client;
    BulkRequestBuilder requestBuilder;
    try {
        client = TransportClient.builder().settings(Settings.builder().put("cluster.name", "production").put("node.name","node1")).build().addTransportAddress(
        new InetSocketTransportAddress(InetAddress.getByName(""), 9300));
        requestBuilder = (client).prepareBulk();
    } 
    catch (Exception e) {
    }
    
  3. Open the Firewall ports for 9200,9300

Windows equivalent of OS X Keychain?

Windows 8 has a notion of a keychain called Password Vault. Windows Runtime apps (Modern/Metro) as well as managed desktop apps can make use of it. According to the documentation:

Apps and services don't have access to credentials associated with other apps or services.

See How to store user credentials on MSDN.

Pre-Windows 8, Data Protection API (DPAPI) is the closest equivalent to a keychain. Arbitrary data can be encrypted using this API, although storing the encrypted data is up to the developer. The data is ultimately encrypted using the current user's password, however user or developer supplied "optional entropy" could be included to further protect the data from other software or users. The data can also be decrypted on different computers in a domain.

DPAPI can be accessed through native calls to Crypt32.dll's CryptProtectData and CryptUnprotectData functions or through .NET Framework's ProtectedData class, which is a limited feature wrapper for the former functions.

More information than you ever needed to know about DPAPI is available in Passcape's article DPAPI Secrets. Security analysis and data recovery in DPAPI.

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Go to the Users & Groups pane of the System Preferences -> Select the User -> Click the lock to make changes (bottom left corner) -> right click the current user select Advanced options... -> Select the Login Shell: /bin/zsh and OK

Using column alias in WHERE clause of MySQL query produces an error

You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.

Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

Copied from MySQL documentation

As pointed in the comments, using HAVING instead may do the work. Make sure to give a read at this question too: WHERE vs HAVING.

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

Have a div cling to top of screen if scrolled down past it

The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.

Derived from the code viixii.com uses I ended up using this:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.

Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.

Just place an empty div with a class acting like an anchor just above the element you want to have fixed.

Like so:

<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>

All credit for the code goes to viixii.com

Using a PagedList with a ViewModel ASP.Net MVC

I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.

Here's a snippet of the code that worked for me:

        int pageSize = 4;
        int pageNumber = (page ?? 1);
        //Used the following two formulas so that it doesn't round down on the returned integer
        decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));     
        ViewBag.TotalPages = Math.Ceiling(totalPages);  
        //These next two functions could maybe be reduced to one function....would require some testing and building
        viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
        ViewBag.OnePageofTeachers = viewModel.Teachers;
        ViewBag.PageNumber = pageNumber;

        return View(viewModel);

I added

using.PagedList;

to my controller as the tutorial states.

Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.

@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.

Page @ViewBag.PageNumber of @ViewBag.TotalPages

@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))

Hope that works for you. Let me know if it works!!

Plot a legend outside of the plotting area in base graphics?

No one has mentioned using negative inset values for legend. Here is an example, where the legend is to the right of the plot, aligned to the top (using keyword "topright").

# Random data to plot:
A <- data.frame(x=rnorm(100, 20, 2), y=rnorm(100, 20, 2))
B <- data.frame(x=rnorm(100, 21, 1), y=rnorm(100, 21, 1))

# Add extra space to right of plot area; change clipping to figure
par(mar=c(5.1, 4.1, 4.1, 8.1), xpd=TRUE)

# Plot both groups
plot(y ~ x, A, ylim=range(c(A$y, B$y)), xlim=range(c(A$x, B$x)), pch=1,
               main="Scatter plot of two groups")
points(y ~ x, B, pch=3)

# Add legend to top right, outside plot region
legend("topright", inset=c(-0.2,0), legend=c("A","B"), pch=c(1,3), title="Group")

The first value of inset=c(-0.2,0) might need adjusting based on the width of the legend.

legend_right

Error importing Seaborn module in Python

pip install seaborn 

is also solved my problem in windows 10

Python: how to capture image from webcam on click using OpenCV

Breaking down your code example (Explanations are under the line of code.)

import cv2

imports openCV for usage

camera = cv2.VideoCapture(0)

creates an object called camera, of type openCV video capture, using the first camera in the list of cameras connected to the computer.

for i in range(10):

tells the program to loop the following indented code 10 times

    return_value, image = camera.read()

read values from the camera object, using it's read method. it resonds with 2 values save the 2 data values into two temporary variables called "return_value" and "image"

    cv2.imwrite('opencv'+str(i)+'.png', image)

use the openCV method imwrite (that writes an image to a disk) and write an image using the data in the temporary data variable

fewer indents means that the loop has now ended...

del(camera)

deletes the camrea object, we no longer needs it.

you can what you request in many ways, one could be to replace the for loop with a while loop, (running forever, instead of 10 times), and then wait for a keypress (like answered by danidee while I was typing)

or create a much more evil service that hides in the background and captures an image everytime someone presses the keyboard...

Seeing the console's output in Visual Studio 2010?

To keep open your windows console and to not use other output methods rather than the standard output stream cout go to Name-of-your-project -> Properties -> Linker -> System.

Once there, select the SubSytem Tab and mark Console (/SUBSYSTEM:CONSOLE). Once you have done this, whenever you want to compile use Ctrl + F5 (Start without debugging) and your console will keep opened. :)

How to disable all div content

I just wanted to mention this extension method for enabling and disabling elements. I think it's a much cleaner way than adding and removing attributes directly.

Then you simply do:

$("div *").disable();

How to add a .dll reference to a project in Visual Studio

You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)

From there you can reference dll's, after which you can reference namespaces that you need in your code.

Cannot make a static reference to the non-static method fxn(int) from the type Two

You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:

...
Two two = new Two();
x = two.fxn(x)
...

That is, make a Two-Object and call the method on that object.

...or make the fxn method static.

Flask raises TemplateNotFound error even though template file exists

I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.

project/
    app/
        hello.py
        static/
            main.css
    templates/
        home.html
    venv/

This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.

An example of how to use getopts in bash

The problem with the original code is that:

  • h: expects parameter where it shouldn't, so change it into just h (without colon)
  • to expect -p any_string, you need to add p: to the argument list

Basically : after the option means it requires the argument.


The basic syntax of getopts is (see: man bash):

getopts OPTSTRING VARNAME [ARGS...]

where:

  • OPTSTRING is string with list of expected arguments,

    • h - check for option -h without parameters; gives error on unsupported options;
    • h: - check for option -h with parameter; gives errors on unsupported options;
    • abc - check for options -a, -b, -c; gives errors on unsupported options;
    • :abc - check for options -a, -b, -c; silences errors on unsupported options;

      Notes: In other words, colon in front of options allows you handle the errors in your code. Variable will contain ? in the case of unsupported option, : in the case of missing value.

  • OPTARG - is set to current argument value,

  • OPTERR - indicates if Bash should display error messages.

So the code can be:

#!/usr/bin/env bash
usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }
[ $# -eq 0 ] && usage
while getopts ":hs:p:" arg; do
  case $arg in
    p) # Specify p value.
      echo "p is ${OPTARG}"
      ;;
    s) # Specify strength, either 45 or 90.
      strength=${OPTARG}
      [ $strength -eq 45 -o $strength -eq 90 ] \
        && echo "Strength is $strength." \
        || echo "Strength needs to be either 45 or 90, $strength found instead."
      ;;
    h | *) # Display help.
      usage
      exit 0
      ;;
  esac
done

Example usage:

$ ./foo.sh 
./foo.sh usage:
    p) # Specify p value.
    s) # Specify strength, either 45 or 90.
    h | *) # Display help.
$ ./foo.sh -s 123 -p any_string
Strength needs to be either 45 or 90, 123 found instead.
p is any_string
$ ./foo.sh -s 90 -p any_string
Strength is 90.
p is any_string

See: Small getopts tutorial at Bash Hackers Wiki

Gets byte array from a ByteBuffer in java

As simple as that

  private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
    byte[] bytesArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytesArray, 0, bytesArray.length);
    return bytesArray;
}

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

What's the difference between '$(this)' and 'this'?

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

In AVD emulator how to see sdcard folder? and Install apk to AVD?

I have used the following procedure.

Procedure to install the apk files in Android Emulator(AVD):

Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder

Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.

Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools

  • Go to Start -> Run -> cmd

  • Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”

  • Type adb install example.apk

  • After getting success command

  • Go to Application icon in Android emulator, we can see the your application

Hibernate Error executing DDL via JDBC Statement

I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.

How to use a variable in the replacement side of the Perl substitution operator?

Deparse tells us this is what is being executed:

$find = 'start (.*) end';
$replace = "foo \cA bar";
$var = 'start middle end';
$var =~ s/$find/$replace/;

However,

 /$find/foo \1 bar/

Is interpreted as :

$var =~ s/$find/foo $1 bar/;

Unfortunately it appears there is no easy way to do this.

You can do it with a string eval, but thats dangerous.

The most sane solution that works for me was this:

$find = "start (.*) end"; 
$replace = 'foo \1 bar';

$var = "start middle end"; 

sub repl { 
    my $find = shift; 
    my $replace = shift; 
    my $var = shift;

    # Capture first 
    my @items = ( $var =~ $find ); 
    $var =~ s/$find/$replace/; 
    for( reverse 0 .. $#items ){ 
        my $n = $_ + 1; 
        #  Many More Rules can go here, ie: \g matchers  and \{ } 
        $var =~ s/\\$n/${items[$_]}/g ;
        $var =~ s/\$$n/${items[$_]}/g ;
    }
    return $var; 
}

print repl $find, $replace, $var; 

A rebuttal against the ee technique:

As I said in my answer, I avoid evals for a reason.

$find="start (.*) end";
$replace='do{ print "I am a dirty little hacker" while 1; "foo $1 bar" }';

$var = "start middle end";
$var =~ s/$find/$replace/ee;

print "var: $var\n";

this code does exactly what you think it does.

If your substitution string is in a web application, you just opened the door to arbitrary code execution.

Good Job.

Also, it WON'T work with taints turned on for this very reason.

$find="start (.*) end";
$replace='"' . $ARGV[0] . '"';

$var = "start middle end";
$var =~ s/$find/$replace/ee;

print "var: $var\n"


$ perl /tmp/re.pl  'foo $1 bar'
var: foo middle bar
$ perl -T /tmp/re.pl 'foo $1 bar' 
Insecure dependency in eval while running with -T switch at /tmp/re.pl line 10.

However, the more careful technique is sane, safe, secure, and doesn't fail taint. ( Be assured tho, the string it emits is still tainted, so you don't lose any security. )

difference between System.out.println() and System.err.println()

this answer most probably help you it is so much easy System.err and System.out both are the same both are defined in System class as reference variable of PrintStream class as public final static PrintStream out = null; and public final static PrintStream err = null;

means both are ref. variable of PrintStream class. normally System.err is used for printing an error messages, which increase the redability for the programmer.

A minor difference comes in both when we are working with Redirection operator.

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

Encrypt & Decrypt using PyCrypto AES 256

You may need the following two functions: pad- to pad(when doing encryption) and unpad- to unpad (when doing decryption) when the length of input is not a multiple of BLOCK_SIZE.

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[:-ord(s[len(s)-1:])]

So you're asking the length of key? You can use the md5sum of the key rather than use it directly.

More, according to my little experience of using PyCrypto, the IV is used to mix up the output of a encryption when input is same, so the IV is chosen as a random string, and use it as part of the encryption output, and then use it to decrypt the message.

And here's my implementation, hope it will be useful for you:

import base64
from Crypto.Cipher import AES
from Crypto import Random

class AESCipher:
    def __init__( self, key ):
        self.key = key

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) ) 

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))

"google is not defined" when using Google Maps V3 in Firefox remotely

I don't know for sure but here are my best suggestions.

You're using jQuery. So instead of setting the event you should really be using $(function() {... }); to do your initialization. The reason to use this is that it ensures that all the scripts on the page have loaded and you're not limited to just one init function like you are with the onload body tag.

Also, be sure your Javascript code is after the Google include. Otherwise your code might execute before the Google objects are created.

I would also suggest taking a look at this page about event order.

http://dean.edwards.name/weblog/2005/09/busted/

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

My case was that the server didn't accept the connection from this IP. The server is a SQL server from Google Apps Engine, and you have to configure allowed remote hosts that can connect to the server.

Adding the (new) host to the GAE admin page solved the issue.

Lock down Microsoft Excel macro

Generate a protected application for Mac or Windows from your Excel spreadsheet using OfficeProtect with either AppProtect or QuickLicense/AddLicense. There is a demonstation video called "Protect Excel Spreedsheet" at www.excelsoftware.com/videos.

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

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

Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:

call shortcutJS.bat -linkfile "%~n0.lnk" -target  "%~f0" -linkarguments "some arguments"

With -help you can check the other options (you can set icon , admin permissions and etc.)

Initialising a multidimensional array in Java

Multidimensional Array in Java

Returning a multidimensional array

Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...

We can define a two-dimensional array as:

  1. int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}

  2. int[ ][ ] num = new int[4][2]

    num[0][0] = 1;
    num[0][1] = 2;
    num[1][0] = 1;
    num[1][1] = 2;
    num[2][0] = 1;
    num[2][1] = 2;
    num[3][0] = 1;
    num[3][1] = 2;
    

    If you don't allocate, let's say num[2][1], it is not initialized and then it is automatically allocated 0, that is, automatically num[2][1] = 0;

  3. Below, num1.length gives you rows.

  4. While num1[0].length gives you the number of elements related to num1[0]. Here num1[0] has related arrays num1[0][0] and num[0][1] only.

  5. Here we used a for loop which helps us to calculate num1[i].length. Here i is incremented through a loop.

    class array
    {
        static int[][] add(int[][] num1,int[][] num2)
        {
            int[][] temp = new int[num1.length][num1[0].length];
            for(int i = 0; i<temp.length; i++)
            {
                for(int j = 0; j<temp[i].length; j++)
                {
                    temp[i][j] = num1[i][j]+num2[i][j];
                }
            }
            return temp;
        }
    
        public static void main(String args[])
        {
            /* We can define a two-dimensional array as
                 1.  int[] num[] = {{1,2},{1,2},{1,2},{1,2}}
                 2.  int[][] num = new int[4][2]
                     num[0][0] = 1;
                     num[0][1] = 2;
                     num[1][0] = 1;
                     num[1][1] = 2;
                     num[2][0] = 1;
                     num[2][1] = 2;
                     num[3][0] = 1;
                     num[3][1] = 2;
    
                     If you don't allocate let's say num[2][1] is
                     not initialized, and then it is automatically
                     allocated 0, that is, automatically num[2][1] = 0;
                  3. Below num1.length gives you rows
                  4. While num1[0].length gives you number of elements
                     related to num1[0]. Here num1[0] has related arrays
                     num1[0][0] and num[0][1] only.
                  5. Here we used a 'for' loop which helps us to calculate
                     num1[i].length, and here i is incremented through a loop.
            */
            int num1[][] = {{1,2},{1,2},{1,2},{1,2}};
            int num2[][] = {{1,2},{1,2},{1,2},{1,2}};
    
            int num3[][] = add(num1,num2);
            for(int i = 0; i<num1.length; i++)
            {
                for(int j = 0; j<num1[j].length; j++)
                    System.out.println("num3[" + i + "][" + j + "]=" + num3[i][j]);
            }
        }
    }
    

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;

into

// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

Best way to copy a database (SQL Server 2008)

The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.

If you cannot detach the production db you should use backup and restore.

You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.

You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.

This will lists the orphaned users:

EXEC sp_change_users_login 'Report'

If you already have a login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user'

If you want to create a new login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location.replace or location.href, etc.) to redirect to whatever URL you want. Of course, that depends on what HTML has already been sent down.

How do you serialize a model instance in Django?

Use list, it will solve problem

Step1:

 result=YOUR_MODELE_NAME.objects.values('PROP1','PROP2').all();

Step2:

 result=list(result)  #after getting data from model convert result to list

Step3:

 return HttpResponse(json.dumps(result), content_type = "application/json")

Regular expression for validating names and surnames?

This one worked perfectly for me in JavaScript: ^[a-zA-Z]+[\s|-]?[a-zA-Z]+[\s|-]?[a-zA-Z]+$

Here is the method:

function isValidName(name) {
    var found = name.search(/^[a-zA-Z]+[\s|-]?[a-zA-Z]+[\s|-]?[a-zA-Z]+$/);
    return found > -1;
}