Programs & Examples On #Addobserver

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

For Swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

For Swift 4

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I had this issue today which was solved by selecting Product -> Clean. I was so confused since my code was proper. The problem started from using command-Z too many times :)

Move a view up only when the keyboard covers an input field

Here is My 2 cents:

Have you tried: https://github.com/hackiftekhar/IQKeyboardManager

Extremely easy to install Swift or Objective-C.

Here how it works:

IQKeyboardManager (Swift):- IQKeyboardManagerSwift is available through CocoaPods, to install it simply add the following line to your Podfile: (#236)

pod 'IQKeyboardManagerSwift'

In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager.

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    IQKeyboardManager.sharedManager().enable = true
    // For Swift 4, use this instead
    // IQKeyboardManager.shared.enable = true


    return true
    }
}

And that is all. Easy!

Move textfield when keyboard appears swift

In Swift 4.0 -

func textFieldDidBeginEditing(_ textField: UITextField) {
        animateViewMoving(up: true, moveValue: 100)
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        animateViewMoving(up: false, moveValue: 100)
    }
    func animateViewMoving (up:Bool, moveValue :CGFloat){
        let movementDuration:TimeInterval = 0.3
        let movement:CGFloat = ( up ? -moveValue : moveValue)
        UIView.beginAnimations( "animateView", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration ) 
        self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
        UIView.commitAnimations()
    }

NSNotificationCenter addObserver in Swift

In swift 2.2 - XCode 7.3, we use #selector for NSNotificationCenter

 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)

Best practices for Storyboard login screen, handling clearing of data upon logout

Here is what I ended up doing to accomplish everything. The only thing you need to consider in addition to this is (a) the login process and (b) where you are storing your app data (in this case, I used a singleton).

Storyboard showing login view controller and main tab controller

As you can see, the root view controller is my Main Tab Controller. I did this because after the user has logged in, I want the app to launch directly to the first tab. (This avoids any "flicker" where the login view shows temporarily.)

AppDelegate.m

In this file, I check whether the user is already logged in. If not, I push the login view controller. I also handle the logout process, where I clear data and show the login view.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Show login view if not logged in already
    if(![AppData isLoggedIn]) {
        [self showLoginScreen:NO];
    }

    return YES;
}

-(void) showLoginScreen:(BOOL)animated
{

    // Get login screen from storyboard and present it
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    LoginViewController *viewController = (LoginViewController *)[storyboard instantiateViewControllerWithIdentifier:@"loginScreen"];
    [self.window makeKeyAndVisible];
    [self.window.rootViewController presentViewController:viewController
                                             animated:animated
                                           completion:nil];
}

-(void) logout
{
    // Remove data from singleton (where all my app data is stored)
    [AppData clearData];

   // Reset view controller (this will quickly clear all the views)
   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
   MainTabControllerViewController *viewController = (MainTabControllerViewController *)[storyboard instantiateViewControllerWithIdentifier:@"mainView"];
   [self.window setRootViewController:viewController];

   // Show login screen
   [self showLoginScreen:NO];

}

LoginViewController.m

Here, if the login is successful, I simply dismiss the view and send a notification.

-(void) loginWasSuccessful
{

     // Send notification
     [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessful" object:self];

     // Dismiss login screen
     [self dismissViewControllerAnimated:YES completion:nil];

}

When should we use Observer and Observable?

They are parts of the Observer design pattern. Usually one or more obervers get informed about changes in one observable. It's a notifcation that "something" happened, where you as a programmer can define what "something" means.

When using this pattern, you decouple the both entities from each another - the observers become pluggable.

How to pass object with NSNotificationCenter

Swift 2 Version

As @Johan Karlsson pointed out... I was doing it wrong. Here's the proper way to send and receive information with NSNotificationCenter.

First, we look at the initializer for postNotificationName:

init(name name: String,
   object object: AnyObject?,
 userInfo userInfo: [NSObject : AnyObject]?)

source

We'll be passing our information using the userInfo param. The [NSObject : AnyObject] type is a hold-over from Objective-C. So, in Swift land, all we need to do is pass in a Swift dictionary that has keys that are derived from NSObject and values which can be AnyObject.

With that knowledge we create a dictionary which we'll pass into the object parameter:

 var userInfo = [String:String]()
 userInfo["UserName"] = "Dan"
 userInfo["Something"] = "Could be any object including a custom Type."

Then we pass the dictionary into our object parameter.

Sender

NSNotificationCenter.defaultCenter()
    .postNotificationName("myCustomId", object: nil, userInfo: userInfo)

Receiver Class

First we need to make sure our class is observing for the notification

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("btnClicked:"), name: "myCustomId", object: nil)   
}
    

Then we can receive our dictionary:

func btnClicked(notification: NSNotification) {
   let userInfo : [String:String!] = notification.userInfo as! [String:String!]
   let name = userInfo["UserName"]
   print(name)
}

Why does viewWillAppear not get called when an app comes back from the background?

Swift

Short answer

Use a NotificationCenter observer rather than viewWillAppear.

override func viewDidLoad() {
    super.viewDidLoad()

    // set observer for UIApplication.willEnterForegroundNotification
    NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

}

// my selector that was defined above
@objc func willEnterForeground() {
    // do stuff
}

Long answer

To find out when an app comes back from the background, use a NotificationCenter observer rather than viewWillAppear. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)

import UIKit
class ViewController: UIViewController {

    // MARK: - Overrides

    override func viewDidLoad() {
        super.viewDidLoad()
        print("view did load")

        // add notification observers
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    override func viewWillAppear(_ animated: Bool) {
        print("view will appear")
    }

    override func viewDidAppear(_ animated: Bool) {
        print("view did appear")
    }

    // MARK: - Notification oberserver methods

    @objc func didBecomeActive() {
        print("did become active")
    }

    @objc func willEnterForeground() {
        print("will enter foreground")
    }

}

On first starting the app, the output order is:

view did load
view will appear
did become active
view did appear

After pushing the home button and then bringing the app back to the foreground, the output order is:

will enter foreground
did become active 

So if you were originally trying to use viewWillAppear then UIApplication.willEnterForegroundNotification is probably what you want.

Note

As of iOS 9 and later, you don't need to remove the observer. The documentation states:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

Replace a string in shell script using a variable

echo $LINE | sed -e 's/12345678/'$replace'/g'

you can still use single quotes, but you have to "open" them when you want the variable expanded at the right place. otherwise the string is taken "literally" (as @paxdiablo correctly stated, his answer is correct as well)

A function to convert null to string

 public string ToString(this string value)
        {
            if (value == null)
            {
                value = string.Empty;
            }               
            else
            {
                return value.Trim();
            }
        }

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

Hibernate Delete query

The reason is that for deleting an object, Hibernate requires that the object is in persistent state. Thus, Hibernate first fetches the object (SELECT) and then removes it (DELETE).

Why Hibernate needs to fetch the object first? The reason is that Hibernate interceptors might be enabled (http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html), and the object must be passed through these interceptors to complete its lifecycle. If rows are delete directly in the database, the interceptor won't run.

On the other hand, it's possible to delete entities in one single SQL DELETE statement using bulk operations:

Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();

How to change indentation in Visual Studio Code?

In the toolbar in the bottom right corner you will see a item that looks like the following: enter image description here After clicking on it you will get the option to indent using either spaces or tabs. After selecting your indent type you will then have the option to change how big an indent is. In the case of the example above, indentation is set to 4 space characters per indent. If tab is selected as your indentation character then you will see Tab Size instead of Spaces

If you want to have this apply to all files and not on an idividual file basis, override the Editor: Tab Size and Editor: Insert Spaces settings in either User Settings or Workspace Settings depending on your needs

Edit 1

To get to your user or workspace settings go to Preferences -> Settings. Verify that you are on the User or Workspace tab depending on your needs and use the search bar to locate the settings. You may also want to disable Editor: Detect Indentation as this setting will override what you set for Editor: Insert Spaces and Editor: Tab Size when it is enabled

Best way to "push" into C# array

I don't understand what you are doing with the for loop. You are merely iterating over every element and assigning to the first element you encounter. If you're trying to push to a list go with the above answer that states there is no such thing as pushing to a list. That really is getting the data structures mixed up. Javascript might not be setting the best example, because a javascript list is really also a queue and a stack at the same time.

How can I trim leading and trailing white space?

I created a trim.strings () function to trim leading and/or trailing whitespace as:

# Arguments:    x - character vector
#            side - side(s) on which to remove whitespace 
#                   default : "both"
#                   possible values: c("both", "leading", "trailing")

trim.strings <- function(x, side = "both") { 
    if (is.na(match(side, c("both", "leading", "trailing")))) { 
      side <- "both" 
      } 
    if (side == "leading") { 
      sub("^\\s+", "", x)
      } else {
        if (side == "trailing") {
          sub("\\s+$", "", x)
    } else gsub("^\\s+|\\s+$", "", x)
    } 
} 

For illustration,

a <- c("   ABC123 456    ", " ABC123DEF          ")

# returns string without leading and trailing whitespace
trim.strings(a)
# [1] "ABC123 456" "ABC123DEF" 

# returns string without leading whitespace
trim.strings(a, side = "leading")
# [1] "ABC123 456    "      "ABC123DEF          "

# returns string without trailing whitespace
trim.strings(a, side = "trailing")
# [1] "   ABC123 456" " ABC123DEF"   

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

How to execute a command prompt command from python

It's very simple. You need just two lines of code with just using the built-in function and also it takes the input and runs forever until you stop it. Also that 'cmd' in quotes, leave it and don't change it. Here is the code:

import os
os.system('cmd')

Now just run this code and see the whole windows command prompt in your python project!

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

Spring Boot 1.4 Use this for Javascript HTML Json all compressions.

server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript

CodeIgniter : Unable to load the requested file:

try $this->load->view('home/home_view',$data);

instead of this:

$this->load->view(‘home\home_view’,$data);

Sort matrix according to first column in R

Be aware that if you want to have values in the reverse order, you can easily do so:

> example = matrix(c(1,1,1,4,3,3,2,349,393,392,459,49,32,94), ncol = 2)
> example[order(example[,1], decreasing = TRUE),]
     [,1] [,2]
[1,]    4  459
[2,]    3   49
[3,]    3   32
[4,]    2   94
[5,]    1  349
[6,]    1  393
[7,]    1  392

Find a file by name in Visual Studio Code

When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames

if you have:

  • plugin.ts
  • page.css
  • plugger.ts

You can type css and press enter and it will open the page.css. If you type .ts the list is filtered and contains two items.

How to keep an iPhone app running on background fully operational

Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.

How to get user name using Windows authentication in asp.net?

I think because of the below code you are not getting new credential

string fullName = Request.ServerVariables["LOGON_USER"];

You can try custom login page.

private final static attribute vs private final attribute

Final: Once a final variable has been assigned, it always contains the same value. wherever the variable is static or not static: it will be only one variable for all instances initialized one time in Memory

How to use multiple databases in Laravel

Also you can use postgres fdw system

https://www.postgresql.org/docs/9.5/postgres-fdw.html

You will be able to connect different db in postgres. After that, in one query, you can access tables that are in different databases.

Streaming via RTSP or RTP in HTML5

Chrome will never implement support RTSP streaming.

At least, in the words of a Chromium developer here:

we're never going to add support for this

Add php variable inside echo statement as href link address?

you can either use

echo '<a href="'.$link_address.'">Link</a>';

or

echo "<a href=\"$link_address\">Link</a>';

if you use double quotes you can insert the variable into the string and it will be parsed.

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

SQL statement to get column type

To build on the answers above, it's often useful to get the column data type in the same format that you need to declare columns.

For example, varchar(50), varchar(max), decimal(p, s).

This allows you to do that:

SELECT 
  [Name]         = c.[name]
, [Type]         = 
    CASE 
      WHEN tp.[name] IN ('varchar', 'char') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length AS VARCHAR(25))) + ')' 
      WHEN tp.[name] IN ('nvarchar','nchar') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length / 2 AS VARCHAR(25)))+ ')'      
      WHEN tp.[name] IN ('decimal', 'numeric') THEN tp.[name] + '(' + CAST(c.[precision] AS VARCHAR(25)) + ', ' + CAST(c.[scale] AS VARCHAR(25)) + ')'
      WHEN tp.[name] IN ('datetime2') THEN tp.[name] + '(' + CAST(c.[scale] AS VARCHAR(25)) + ')'
      ELSE tp.[name]
    END
, [RawType]      = tp.[name]
, [MaxLength]    = c.max_length
, [Precision]    = c.[precision]
, [Scale]        = c.scale
FROM sys.tables t 
JOIN sys.schemas s ON t.schema_id = s.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types tp ON c.user_type_id = tp.user_type_id
WHERE s.[name] = 'dbo' AND t.[name] = 'MyTable'

How can I check if a URL exists via PHP?

function urlIsOk($url)
{
    $headers = @get_headers($url);
    $httpStatus = intval(substr($headers[0], 9, 3));
    if ($httpStatus<400)
    {
        return true;
    }
    return false;
}

How to copy a row and insert in same table with a autoincrement field in MySQL?

You can also pass in '0' as the value for the column to auto-increment, the correct value will be used when the record is created. This is so much easier than temporary tables.

Source: Copying rows in MySQL (see the second comment, by TRiG, to the first solution, by Lore)

What is a web service endpoint?

A endpoint is a URL for web service.And Endpoints also is a distributed API.

The Simple Object Access Protocol (SOAP) endpoint is a URL. It identifies the location on the built-in HTTP service where the web services listener listens for incoming requests.

Reference: https://www.ibm.com/support/knowledgecenter/SSSHYH_7.1.0.4/com.ibm.netcoolimpact.doc/dsa/imdsa_web_netcool_impact_soap_endpoint_c.html

Redis command to get all available keys?

Take a look at following Redis Cheat Sheet. To get a subset of redis keys with the redis-cli i use the command

KEYS "prefix:*"

Text blinking jQuery

Text Blinking start and stop on button click -

<input type="button" id="btnclick" value="click" />
var intervalA;
        var intervalB;

        $(document).ready(function () {

            $('#btnclick').click(function () {
                blinkFont();

                setTimeout(function () {
                    clearInterval(intervalA);
                    clearInterval(intervalB);
                }, 5000);
            });
        });

        function blinkFont() {
            document.getElementById("blink").style.color = "red"
            document.getElementById("blink").style.background = "black"
            intervalA = setTimeout("blinkFont()", 500);
        }

        function setblinkFont() {
            document.getElementById("blink").style.color = "black"
            document.getElementById("blink").style.background = "red"
            intervalB = setTimeout("blinkFont()", 500);
        }

    </script>

    <div id="blink" class="live-chat">
        <span>This is blinking text and background</span>
    </div>

Removing duplicate elements from an array in Swift

I think this the better way with knowing the logic itself

var arrayOfInts = [2, 2, 4, 4]
var mainArray = [Int]()

for value in arrayOfInts {

if mainArray.contains(value) != true  {
    
    mainArray.append(value)
    print("mainArray:\(mainArray)")
}}

mysql.h file can't be found

this worked for me

$ gcc dbconnect.c -o dbconnect -lmysqlclient
$ ./dbconnect

-lmysqlclient is must.

and i would personally recommend to use following notation instead of using -I compilation flag.

#include <mysql/mysql.h>

How can I check Drupal log files?

If you love the command line, you can also do this using drush with the watchdog show command:

drush ws

More information about this command available here:

https://drushcommands.com/drush-7x/watchdog/watchdog-show/

How to save CSS changes of Styles panel of Chrome Developer Tools?

DevTools tech writer and developer advocate here.

Starting in Chrome 65, Local Overrides is a new, lightweight way to do this. This is a different feature than Workspaces.

Set up Overrides

  1. Go to Sources panel.
  2. Go to Overrides tab.
  3. Click Select Folder For Overrides.
  4. Select which directory you want to save your changes to.
  5. At the top of your viewport, click Allow to give DevTools read and write access to the directory.
  6. Make your changes. In the GIF below, you can see that the background:rosybrown change persists across page loads.

overrides demo

How overrides work

When you make a change in DevTools, DevTools saves the change to a modified copy of the file on your computer. When you reload the page, DevTools serves the modified file, rather than the network resource.

The difference between overrides and workspaces

Workspaces is designed to let you use DevTools as your IDE. It maps your repository code to the network code, using source maps. The real benefit is if you're minifying your code, or using code that needs to get transpiled, like SCSS, then the changes you make in DevTools (usually) get mapped back into your original source code. Overrides, on the other hand, let you modify and save any file on the web. It's a good solution if you just want to quickly experiment with changes, and save those changes across page loads.

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

Parcelable encountered IOException writing serializable object getactivity()

I faced Same issue, the issues was there are some inner classes with the static keyword.After removing the static keyword it started working and also the inner class should implements to Serializable

Issue scenario

class A implements Serializable{ 
  class static B{
  } 
}

Resolved By

class A implements Serializable{ 
      class B implements Serializable{
      } 
    }

Removing carriage return and new-line from the end of a string in c#

I use lots of erasing level

String donen = "lots of stupid whitespaces and new lines and others..."

//Remove multilines
donen = Regex.Replace(donen, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//remove multi whitespaces
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
donen = regex.Replace(donen, " ");
//remove tabs
char tab = '\u0009';
donen = donen.Replace(tab.ToString(), "");
//remove endoffile newlines
donen = donen.TrimEnd('\r', '\n');
//to be sure erase new lines again from another perspective
donen.Replace(Environment.NewLine, "");

and now we have a clean one row

Git Checkout warning: unable to unlink files, permission denied

In my case it was a ":" character in a folder name prevenitng the git repo to checkout on windows.

ToString() function in Go

I prefer something like the following:

type StringRef []byte

func (s StringRef) String() string {
        return string(s[:])
}

…

// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))

Cannot access wamp server on local network

1.

first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)

2.

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Order Allow,Deny
      Allow from all

if "Allow from all" line not work for your then use "Require all granted" then it will work for you.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80

3. Dont forget to restart All Services of Wamp or Apache after making this change

MySQL: ALTER TABLE if column not exists

hope this will help you

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'

or

delimiter '//'

CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='new_column' AND TABLE_NAME='tablename' AND TABLE_SCHEMA='the_schema'
)
THEN
    ALTER TABLE `the_schema`.`the_table`
    ADD COLUMN `new_column` TINYINT(1) NOT NULL DEFAULT 1;;

END IF;
END;
//

delimiter ';'

CALL addcol();

DROP PROCEDURE addcol;

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

Css height in percent not working

Make it 100% of the viewport height:

div {
  height: 100vh;
}

Works in all modern browsers and IE>=9, see here for more info.

Display Last Saved Date on worksheet

thought I would update on this.

Found out that adding to the VB Module behind the spreadsheet does not actually register as a Macro.

So here is the solution:

  1. Press ALT + F11
  2. Click Insert > Module
  3. Paste the following into the window:

Code

Function LastSavedTimeStamp() As Date
  LastSavedTimeStamp = ActiveWorkbook.BuiltinDocumentProperties("Last Save Time")
End Function
  1. Save the module, close the editor and return to the worksheet.
  2. Click in the Cell where the date is to be displayed and enter the following formula:

Code

=LastSavedTimeStamp()

How to compare dates in c#

If you have your dates in DateTime variables, they don't have a format.

You can use the Date property to return a DateTime value with the time portion set to midnight. So, if you have:

DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;

if(dt1.Date > dt2.Date)
{
     //It's a later date
}
else
{
     //It's an earlier or equal date
}

Declaring multiple variables in JavaScript

It's common to use one var statement per scope for organization. The way all "scopes" follow a similar pattern making the code more readable. Additionally, the engine "hoists" them all to the top anyway. So keeping your declarations together mimics what will actually happen more closely.

Difference between | and || or & and && for comparison

in C (and other languages probably) a single | or & is a bitwise comparison.
The double || or && is a logical comparison.
Edit: Be sure to read Mehrdad's comment below regarding "without short-circuiting"

In practice, since true is often equivalent to 1 and false is often equivalent to 0, the bitwise comparisons can sometimes be valid and return exactly the same result.

There was once a mission critical software component I ran a static code analyzer on and it pointed out that a bitwise comparison was being used where a logical comparison should have been. Since it was written in C and due to the arrangement of logical comparisons, the software worked just fine with either. Example:

if ( (altitide > 10000) & (knots > 100) )
...

Login credentials not working with Gmail SMTP

I had the same issue. The Authentication Error can be because of your security settings, the 2-step verification for instance. It wont allow third party apps to override the authentication.

Log in to your Google account, and use these links:

Step 1 [Link of Disabling 2-step verification]:

https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin

Step 2: [Link for Allowing less secure apps]

https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none

It should be all good now.

How can I shuffle an array?

Use the modern version of the Fisher–Yates shuffle algorithm:

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

ES2015 (ES6) version

/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.

Use

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);

Implementing prototype

Using Object.defineProperty (method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr). The following will allow you to call arr.shuffle() to shuffle the array arr:

Object.defineProperty(Array.prototype, 'shuffle', {
    value: function() {
        for (let i = this.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this[i], this[j]] = [this[j], this[i]];
        }
        return this;
    }
});

Splitting String with delimiter

def (value1, value2) = '1128-2'.split('-') should work.

Can anyone please try this in Groovy Console?

def (v, z) =  '1128-2'.split('-')

assert v == '1128'
assert z == '2'

git rebase fatal: Needed a single revision

The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.

To query the remote (in this case origin) for its HEAD (typically master), and set that as the default branch:

$ git remote set-head origin --auto

If you want to use a different default remote branch locally, you can specify that branch:

$ git remote set-head origin new-default

Once the default branch is set, you can use just the remote name in git rebase <remote> and any other commands instead of explicit <remote>/<branch>.

Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD.

$ cat .git/refs/remotes/origin/HEAD 
ref: refs/remotes/origin/master

See the git-remote man page for further details.

Select all where [first letter starts with B]

SQL Statement:

 SELECT * FROM employee WHERE employeeName LIKE 'A%';

Result:

Number of Records: 4

employeeID  employeeName    employeeName    Address City    PostalCode  Country

1           Alam             Wipro          Delhi   Delhi   11005      India

2           Aditya           Wipro          Delhi   Delhi   11005      India

3           Alok             HCL            Delhi   Delhi   11005      India

4           Ashok            IBM            Delhi   Delhi   11005      India

Fully change package name including company domain

This worked for me, from https://stackoverflow.com/a/18637004/127434

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. AndroidStudio will refactor the package name everywhere.

Finally, delete the old package.

Efficient way to determine number of digits in an integer

Practical joke: This is the most efficient way (number of digits is calculated at compile-time):

template <unsigned long long N, size_t base=10>
struct numberlength
{
    enum { value = 1 + numberlength<N/base, base>::value };
};

template <size_t base>
struct numberlength<0, base>
{
    enum { value = 0 };
};

May be useful to determine the width required for number field in formatting, input elements etc.

What is the LDF file in SQL Server?

ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.

You can however change the log model to the database to simple so this log does not grow too fast.

Check this for example.

Check here for reference.

How to hide Soft Keyboard when activity starts

To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() etc. you can use the code below:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Web Reference vs. Service Reference

In the end, both do the same thing. There are some differences in code: Web Services doesn't add a Root namespace of project, but Service Reference adds service classes to the namespace of the project. The ServiceSoapClient class gets a different naming, which is not important. In working with TFS I'd rather use Service Reference because it works better with source control. Both work with SOAP protocols.

I find it better to use the Service Reference because it is new and will thus be better maintained.

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

it turns out that I got this error because my requested module is not bundled in the minification prosses due to path misspelling

so make sure that your module exists in minified js file (do search for a word within it to be sure)

Slide right to left Android Animations

Right to left new page animation

<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false">
 <translate
    android:fromXDelta="0%" android:toXDelta="800%"
    android:fromYDelta="0%" android:toYDelta="0%"
    android:duration="600" />

How do I find out what License has been applied to my SQL Server installation?

I presume you mean via SSMS?

For a SQL Server Instance:

SELECT SERVERPROPERTY('productversion'), 
       SERVERPROPERTY ('productlevel'), 
       SERVERPROPERTY ('edition')

For a SQL Server Installation:

Select @@Version

Check if option is selected with jQuery, if not select a default

You guys are doing way too much for selecting. Just select by value:

$("#mySelect").val( 3 );

Checking from shell script if a directory contains files

Taking a hint (or several) from olibre's answer, I like a Bash function:

function isEmptyDir {
  [ -d $1 -a -n "$( find $1 -prune -empty 2>/dev/null )" ]
}

Because while it creates one subshell, it's as close to an O(1) solution as I can imagine and giving it a name makes it readable. I can then write

if isEmptyDir somedir
then
  echo somedir is an empty directory
else
  echo somedir does not exist, is not a dir, is unreadable, or is  not empty
fi

As for O(1) there are outlier cases: if a large directory has had all or all but the last entry deleted, "find" may have to read the whole thing to determine whether it's empty. I believe that expected performance is O(1) but worst-case is linear in the directory size. I have not measured this.

Arithmetic overflow error converting numeric to data type numeric

Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

How to extract filename.tar.gz file

The other scenario you mush verify is that the file you're trying to unpack is not empty and is valid.

In my case I wasn't downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.

Find everything between two XML tags with RegEx

In our case, we receive an XML as a String and need to get rid of the values that have some "special" characters, like &<> etc. Basically someone can provide an XML to us in this form:

<notes>
  <note>
     <to>jenice & carl </to>
     <from>your neighbor <; </from>
  </note>
</notes>

So I need to find in that String the values jenice & carl and your neighbor <; and properly escape & and < (otherwise this is an invalid xml if you later pass it to an engine that shall rename unnamed).

Doing this with regex is a rather dumb idea to begin with, but it's cheap and easy. So the brave ones that would like to do the same thing I did, here you go:

    String xml = ...
    Pattern p = Pattern.compile("<(.+)>(?!\\R<)(.+)</(\\1)>");
    Matcher m = p.matcher(xml);
    String result = m.replaceAll(mr -> {
        if (mr.group(2).contains("&")) {
            return "<" + m.group(1) + ">" + m.group(2) + "+ some change" + "</" + m.group(3) + ">";
        }
        return "<" + m.group(1) + ">" + mr.group(2) + "</" + m.group(3) + ">";
    });

The multi-part identifier could not be bound

Instead you can try joining tables like,

select 
  .... 
from 
   dkcd 
     right join 
                a
                  , b

This should work

Print raw string from variable? (not getting the answers)

I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:

The Solution for python 3x:

print(r'%s' % your_variable_pattern_str)

How to deep copy a list?

If your list elements are immutable objects then you can use this, otherwise you have to use deepcopy from copy module.

you can also use shortest way for deep copy a list like this.

a = [0,1,2,3,4,5,6,7,8,9,10]
b = a[:] #deep copying the list a and assigning it to b
print id(a)
20983280
print id(b)
12967208

a[2] = 20
print a
[0, 1, 20, 3, 4, 5, 6, 7, 8, 9,10]
print b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]

Plotting with C#

There is OxyPlot which I recommend. It has packages for WPF, Metro, Silverlight, Windows Forms, Avalonia UI, XWT. Besides graphics it can export to SVG, PDF, Open XML, etc. And it even supports Mono and Xamarin for Android and iOS. It is actively developed too.

There is also a new (at least for me) open source .NET plotting library called Live-Charts. The plots are pretty interactive. Library suports WPF, WinForms and UWP. Xamarin is planned. The design is made towards MV* patterns. But @Pawel Audionysos suggests not such a good performance of Live-Charts WPF.

How can I add raw data body to an axios request?

There many methods to send raw data with a post request. I personally like this one.

    const url = "your url"
    const data = {key: value}
    const headers = {
        "Content-Type": "application/json"
    }
    axios.post(url, data, headers)

jQuery rotate/transform

Why not just use, toggleClass on click?

js:

$(this).toggleClass("up");

css:

button.up {
    -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
        -ms-transform: rotate(180deg);
         -o-transform: rotate(180deg);
            transform: rotate(180deg);
               /* IE6–IE9 */
               filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
                 zoom: 1;
    }

you can also add this to the css:

button{
        -webkit-transition: all 500ms ease-in-out;
        -moz-transition: all 500ms ease-in-out;
        -o-transition: all 500ms ease-in-out;
        -ms-transition: all 500ms ease-in-out;
}

which will add the animation.

PS...

to answer your original question:

you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:

<script type="text/javascript">
    $(function() {
     var $elie = $("#bkgimg");
     rotate(0);
     function rotate(degree) {

      // For webkit browsers: e.g. Chrome
    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});


    /* add a condition here for the extremity */ 
    if(degree < 180){
      // Animate rotation with a recursive call
      setTimeout(function() { rotate(++degree); },65);
     }
    }
    });
    </script>

In Java, how can I determine if a char array contains a particular character?

This method does the trick.

boolean contains(char c, char[] array) {
    for (char x : array) {
        if (x == c) {
            return true;
        }
    }
    return false;
}

Example of usage:

class Main {

    static boolean contains(char c, char[] array) {
        for (char x : array) {
            if (x == c) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] a) {
        char[] charArray = new char[] {'h','e','l','l','o'};
        if (!contains('q', charArray)) {
            // Do something...
            System.out.println("Hello world!");
        }
    }

}

Alternative way:

if (!String.valueOf(charArray).contains("q")) {
    // do something...
}

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

Get size of an Iterable in Java

As for me, these are just different methods. The first one leaves the object you're iterating on unchanged, while the seconds leaves it empty. The question is what do you want to do. The complexity of removing is based on implementation of your iterable object. If you're using Collections - just obtain the size like was proposed by Kazekage Gaara - its usually the best approach performance wise.

Java: Enum parameter in method

You can use an enum in said parameters like this:

public enum Alignment { LEFT, RIGHT }
private static String drawCellValue(
int maxCellLength, String cellValue, Alignment align) {}

then you can use either a switch or if statement to actually do something with said parameter.

switch(align) {
case LEFT: //something
case RIGHT: //something
default: //something
}

if(align == Alignment.RIGHT) { /*code*/}

How to cancel a pull request on github?

Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image

Prevent PDF file from downloading and printing

Why dont you show a generated Picture (screenshot) of the PDF?

What does the "+" (plus sign) CSS selector mean?

See adjacent selectors on W3.org.

In this case, the selector means that the style applies only to paragraphs directly following another paragraph.

A plain p selector would apply the style to every paragraph in the page.


This will only work on IE7 or above. In IE6, the style will not be applied to any elements. This also goes for the > combinator, by the way.

See also Microsoft's overview for CSS compatibility in Internet Explorer.

Change image onmouseover

You can do that just using CSS.

You'll need to place another tag inside the <a> and then you can change the CSS background-image attribute on a:hover.

i.e.

HTML:

<a href="#" id="name">
  <span>&nbsp;</span> 
</a>

CSS:

a#name span{
  background-image:url(image/path);
}

a#name:hover span{
  background-image:url(another/image/path);
}

How to place two forms on the same page?

Well you can have each form go to to a different page. (which is preferable)

Or have a different value for the a certain input and base posts on that:

switch($_POST['submit']) {
    case 'login': 
    //...
    break;
    case 'register':
    //...
    break;
}

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

After trying all these procedures it still didn't work for me. What did work was

  1. go into File Explorer and delete the .classpath file under the project's root folder
  2. run Maven update within Eclipse, and check Force update of Snapshots/Releases

Our current work required integrating a number of disparate projects so unfortunately use of SNAPSHOTs in a production environment were required (taboo in Maven circles)!

Easier way to create circle div than using an image?

For circle, create a div element and then enter width = 2 times of the border radius = 2 times padding. Also line-height = 0 For example, with 50px as radii of the circle, the below code works well:

width: 100px;
padding: 50px 0;
border: solid;
line-height: 0px;
border-radius: 50px;

Laravel 4: how to "order by" using Eloquent ORM

If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.

So, in the model you would have:

public function scopeIdDescending($query)
{
        return $query->orderBy('id','DESC');
}   

And outside the model you would have:

$posts = Post::idDescending()->get();

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

Check status of one port on remote host

Use nc command,

nc -zv <hostname/ip> <port/port range>

For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017

You can also use telnet command

telnet <ip/host> port

Loading .sql files from within PHP

An updated solution of Plahcinski solution. Alternatively you can use fopen and fread for bigger files:

$fp = file('database.sql', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$query = '';
foreach ($fp as $line) {
    if ($line != '' && strpos($line, '--') === false) {
        $query .= $line;
        if (substr($query, -1) == ';') {
            mysql_query($query);
            $query = '';
        }
    }
}

How to change to an older version of Node.js

Another good library for managing multiple versions of Node is N: https://github.com/visionmedia/n

Function return value in PowerShell

Luke's description of the function results in these scenarios seems to be right on. I only wish to understand the root cause and the PowerShell product team would do something about the behavior. It seems to be quite common and has cost me too much debugging time.

To get around this issue I've been using global variables rather than returning and using the value from the function call.

Here's another question on the use of global variables: Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

How to use and style new AlertDialog from appCompat 22.1 and above

If you're like me you just want to modify some of the colors in AppCompat, and the only color you need to uniquely change in the dialog is the background. Then all you need to do is set a color for colorBackgroundFloating.

Here's my basic theme that simply modifies some colors with no nested themes:

    <style name="AppTheme" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/theme_colorPrimary</item>
        <item name="colorPrimaryDark">@color/theme_colorPrimaryDark</item>
        <item name="colorAccent">@color/theme_colorAccent</item>
        <item name="colorControlActivated">@color/theme_colorControlActivated</item>
        <item name="android:windowBackground">@color/theme_bg</item>
        <item name="colorBackgroundFloating">@color/theme_dialog_bg</item><!-- Dialog background color -->
        <item name="colorButtonNormal">@color/theme_colorPrimary</item>
        <item name="colorControlHighlight">@color/theme_colorAccent</item>
    </style>

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

Parse large JSON file in Nodejs

I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".

Sample code:

var fs = require('fs')
  , split = require('split')
  ;

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
    var json = JSON.parse(chunk);           
    // ...
});

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Goto processes in mysql.

So can see there is task still working.

Kill the particular process or wait until process complete.

Get viewport/window height in ReactJS

// just use (useEffect). every change will be logged with current value
import React, { useEffect } from "react";

export function () {
  useEffect(() => {
    window.addEventListener('resize', () => {
      const myWidth  = window.innerWidth;
      console.log('my width :::', myWidth)
   })
  },[window])

  return (
    <>
      enter code here
   </>
  )
}

How do you assert that a certain exception is thrown in JUnit 4 tests?

In my case I always get RuntimeException from db, but messages differ. And exception need to be handled respectively. Here is how I tested it:

@Test
public void testThrowsExceptionWhenWrongSku() {

    // Given
    String articleSimpleSku = "999-999";
    int amountOfTransactions = 1;
    Exception exception = null;

    // When
    try {
        createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku);
    } catch (RuntimeException e) {
        exception = e;
    }

    // Then
    shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU);
}

private void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) {
    assertNotNull(e);
    assertTrue(e.getMessage().contains(message));
}

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

The listed return type of the method is Task<string>. You're trying to return a string. They are not the same, nor is there an implicit conversion from string to Task<string>, hence the error.

You're likely confusing this with an async method in which the return value is automatically wrapped in a Task by the compiler. Currently that method is not an async method. You almost certainly meant to do this:

private async Task<string> methodAsync() 
{
    await Task.Delay(10000);
    return "Hello";
}

There are two key changes. First, the method is marked as async, which means the return type is wrapped in a Task, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await model always avoid blocking waits when you can. Task.Delay is a task that will be completed after the specified number of milliseconds. By await-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).

If you prefer a 4.0 way of doing it, without using await , you can do this:

private Task<string> methodAsync() 
{
    return Task.Delay(10000)
        .ContinueWith(t => "Hello");
}

The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await we aren't leveraging here.

If your Thread.Sleep(10000) is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            SomeLongRunningMethod();
            return "Hello";
        });
}

Or more likely:

private Task<string> methodAsync() 
{
    return Task.Run(()=>
        {
            return SomeLongRunningMethodThatReturnsAString();
        });
}

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

View/edit ID3 data for MP3 files

ID3.NET implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files. There's also a NuGet package available.

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Sorting dictionary keys in python

I like this one:

sorted(d, key=d.get)

HTML table with fixed headers?

Somehow I ended up with Position:Sticky working fine on my case:

_x000D_
_x000D_
table{_x000D_
  width: 100%;_x000D_
  border: collapse;_x000D_
}_x000D_
_x000D_
th{_x000D_
    position: sticky;_x000D_
    top: 0px;_x000D_
    border: 1px solid black;_x000D_
    background: #ff5722;_x000D_
    color: #f5f5f5;_x000D_
    font-weight: 600;_x000D_
}_x000D_
td{_x000D_
    background: #d3d3d3;_x000D_
    border: 1px solid black;_x000D_
    color: #f5f5f5;_x000D_
    font-weight: 600;_x000D_
}_x000D_
_x000D_
div{_x000D_
  height: 150px_x000D_
  overflow: auto;_x000D_
  width: 100%_x000D_
}
_x000D_
<div>_x000D_
    <table>_x000D_
        <thead>_x000D_
            <tr>_x000D_
                <th>header 1</th>_x000D_
                <th>header 2</th>_x000D_
                <th>header 3</th>_x000D_
                <th>header 4</th>_x000D_
                <th>header 5</th>_x000D_
                <th>header 6</th>_x000D_
                <th>header 7</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>data 1</td>_x000D_
                <td>data 2</td>_x000D_
                <td>data 3</td>_x000D_
                <td>data 4</td>_x000D_
                <td>data 5</td>_x000D_
                <td>data 6</td>_x000D_
                <td>data 7</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Any implementation of Ordered Set in Java?

Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.

You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.

Also, you can't insert at a certain position.

Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.

List of tuples to dictionary

Functional decision for @pegah answer:

from itertools import groupby

mylist = [('a', 1), ('b', 3), ('a', 2), ('b', 4)]
#mylist = iter([('a', 1), ('b', 3), ('a', 2), ('b', 4)])

result = { k : [*map(lambda v: v[1], values)]
    for k, values in groupby(sorted(mylist, key=lambda x: x[0]), lambda x: x[0])
    }

print(result)
# {'a': [1, 2], 'b': [3, 4]}

Angular 2 / 4 / 5 - Set base href dynamically

Based on your (@sharpmachine) answer, I was able to further refactor it a little, so that we don't have to hack out a function in index.html.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }

And, ./shared/common-functions.util.ts contains:

export function getBaseLocation() {
    let paths: string[] = location.pathname.split('/').splice(1, 1);
    let basePath: string = (paths && paths[0]) || 'my-account'; // Default: my-account
    return '/' + basePath;
}

Chrome - ERR_CACHE_MISS

If you are using WebView in Android developing the problem is that you didn't add uses permission

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

How do I get the last character of a string?

Simple solution is:

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  char[] cs = str.toCharArray();
  char first = cs[0];
  cs[0] = cs[cs.length -1];
  cs[cs.length -1] = first;
  return new String(cs);
}

Using a character array (watch out for the nasty empty String or null String argument!)

Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);  
  char first = sb.charAt(0);
  sb.setCharAt(0, sb.charAt(sb.length()-1));
  sb.setCharAt(sb.length()-1, first);
  return sb.toString();
}

Yet another approach (more for instruction than actual use) is this one:

public String frontBack(String str) {
  if (str == null || str.length() < 2) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);
  String sub = sb.substring(1, sb.length() -1);
  return sb.reverse().replace(1, sb.length() -1, sub).toString();
}

Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

Android dependency has different version for the compile and runtime

I had the same error, what solve my problem was. In my library instead of using compile or implementation i use "api". So in the end my dependencies:

dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api files('libs/model.jar')
testApi 'junit:junit:4.12'
api 'com.android.support:percent:26.0.0-beta2'
api 'com.android.support:appcompat-v7:26.0.0-beta2'
api 'com.android.support:support-core-utils:26.0.0-beta2'

api 'com.squareup.retrofit2:retrofit:2.0.2'
api 'com.squareup.picasso:picasso:2.4.0'
api 'com.squareup.retrofit2:converter-gson:2.0.2'
api 'com.squareup.okhttp3:logging-interceptor:3.2.0'
api 'uk.co.chrisjenx:calligraphy:2.2.0'
api 'com.google.code.gson:gson:2.2.4'
api 'com.android.support:design:26.0.0-beta2'
api 'com.github.PhilJay:MPAndroidChart:v3.0.1'
}

You can find more info about "api", "implementation" in this link https://stackoverflow.com/a/44493379/3479489

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

data.frame rows to a list

A more modern solution uses only purrr::transpose:

library(purrr)
iris[1:2,] %>% purrr::transpose()
#> [[1]]
#> [[1]]$Sepal.Length
#> [1] 5.1
#> 
#> [[1]]$Sepal.Width
#> [1] 3.5
#> 
#> [[1]]$Petal.Length
#> [1] 1.4
#> 
#> [[1]]$Petal.Width
#> [1] 0.2
#> 
#> [[1]]$Species
#> [1] 1
#> 
#> 
#> [[2]]
#> [[2]]$Sepal.Length
#> [1] 4.9
#> 
#> [[2]]$Sepal.Width
#> [1] 3
#> 
#> [[2]]$Petal.Length
#> [1] 1.4
#> 
#> [[2]]$Petal.Width
#> [1] 0.2
#> 
#> [[2]]$Species
#> [1] 1

nvm keeps "forgetting" node in new terminal session

I'm using ZSH so I had to modify ~/.zshrc with the lines concerning NVM in that order:

[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
source ~/.nvm/nvm.sh

How can I solve a connection pool problem between ASP.NET and SQL Server?

I was facing the same problem, after hours of research I realized I was connected on Guest network without VPN so setting up VPN did the trick for me

How do I interpret precision and scale of a number in a database?

Numeric precision refers to the maximum number of digits that are present in the number.

ie 1234567.89 has a precision of 9

Numeric scale refers to the maximum number of decimal places

ie 123456.789 has a scale of 3

Thus the maximum allowed value for decimal(5,2) is 999.99

What does "async: false" do in jQuery.ajax()?

Setting async to false means the instructions following the ajax request will have to wait for the request to complete. Below is one case where one have to set async to false, for the code to work properly.

var phpData = (function get_php_data() {
  var php_data;
  $.ajax({
    url: "http://somesite/v1/api/get_php_data",
    async: false, 
    //very important: else php_data will be returned even before we get Json from the url
    dataType: 'json',
    success: function (json) {
      php_data = json;
    }
  });
  return php_data;
})();

Above example clearly explains the usage of async:false

By setting it to false, we have made sure that once the data is retreived from the url ,only after that return php_data; is called

Finding first blank row, then writing to it

I know this is an older thread however I needed to write a function that returned the first blank row WITHIN a range. All of the code I found online actually searches the entire row (even the cells outside of the range) for a blank row. Data in ranges outside the search range was triggering a used row. This seemed to me to be a simple solution:

Function FirstBlankRow(ByVal rngToSearch As Range) As Long
   Dim R As Range
   Dim C As Range
   Dim RowIsBlank As Boolean

   For Each R In rngToSearch.Rows
      RowIsBlank = True
      For Each C In R.Cells
         If IsEmpty(C.Value) = False Then RowIsBlank = False
      Next C
      If RowIsBlank Then
         FirstBlankRow = R.Row
         Exit For
      End If
   Next R
End Function

Two onClick actions one button

Give your button an id something like this:


<input id="mybutton" type="button" value="Dont show this again! " />

Then use jquery (to make this unobtrusive) and attach click action like so:


$(document).ready(function (){
    $('#mybutton').click(function (){
       fbLikeDump();
       WriteCookie();
    });
});

(this part should be in your .js file too)

I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>

The reason to add just before body closing tag is for performance of perceived page loading times

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Simplest way to detect a mobile device in PHP

Here is a source:

Code:

<?php

$useragent=$_SERVER['HTTP_USER_AGENT'];

if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

header('Location: http://detectmobilebrowser.com/mobile');

?>

Navigation drawer: How do I set the selected item at startup?

Easiest way is to select it from xml as follows,

<menu>
   <group android:checkableBehavior="single">
         <item
              android:checked="true"
              android:id="@+id/nav_home"
              android:icon="@drawable/nav_home"
              android:title="@string/main_screen_title_home" />

Note the line android:checked="true"

Trying to get Laravel 5 email to work

My .env file configuration is like this for laravel 5.1

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=tls

here most important thing is that I created gmail application specific password(16 digit).

I need to reveal one more thing since no luck for any of configuration. That is, whenever I changed .env file need to run this command

php artisan config:cache

And this is most most most important because without this command laravel executes previous settings from it's cache. It's required me more than 10 hours to figure out.

OraOLEDB.Oracle provider is not registered on the local machine

My team would stumble upon this issue every now and then in random machines that we would try to install our platform in (we use oracle drivers 12c ver 12.2.0.4 but we came across this bug with other versions as well)

After quite a bit of experimentation we realized what was wrong:

Said machines would have apps that were using the machine-wide oracle drivers silently locking them and preventing the oracle driver-installer from working its magic when would attempt to upgrade/reinstall said oracle-drivers. The sneakiest "app" would be websites running in IIS and the like because these apps essentially auto-start on reboot. To counter this we do the following:

  1. Disable IIS from starting automagically on restart. Do the same for any other apps/services that auto-start themselves on reboot.
  2. Uninstall any previous Oracle driver and double-check that there are no traces left behind in registry or folders.
  3. Reboot the machine
  4. (Re)Install the Oracle drivers and re-enable IIS and other auto-start apps.
  5. Reboot the machine <- This is vital. Oracle's OLE DB drivers won't work unless you reboot the machine.

If this doesn't work then rinse repeat until the OLE DB drivers work. Hope this helps someone out there struggling to figure out what's going on.

How do I import a .dmp file into Oracle?

I am Using Oracle Database Express Edition 11g Release 2.

Follow the Steps:

Open run SQl Command Line

Step 1: Login as system user

       SQL> connect system/tiger

Step 2 : SQL> CREATE USER UserName IDENTIFIED BY Password;

Step 3 : SQL> grant dba to UserName ;

Step 4 : SQL> GRANT UNLIMITED TABLESPACE TO UserName;

Step 5:

        SQL> CREATE BIGFILE TABLESPACE TSD_UserName
             DATAFILE 'tbs_perm_03.dat'
             SIZE 8G
             AUTOEXTEND ON;

Open Command Prompt in Windows or Terminal in Ubuntu. Then Type:

Note : if you Use Ubuntu then replace " \" to " /" in path.

Step 6: C:\> imp UserName/password@localhost file=D:\abc\xyz.dmp log=D:\abc\abc_1.log full=y;

Done....

I hope you Find Right solution here.

Thanks.

Early exit from function?

exit(); can be use to go for the next validation.

How to read a list of files from a folder using PHP?

There is a glob. In this webpage there are good article how to list files in very simple way:

How to read a list of files from a folder using PHP

Do conditional INSERT with SQL?

It is possible with EXISTS condition. WHERE EXISTS tests for the existence of any records in a subquery. EXISTS returns true if the subquery returns one or more records. Here is an example

UPDATE  TABLE_NAME 
SET val1=arg1 , val2=arg2
WHERE NOT EXISTS
    (SELECT FROM TABLE_NAME WHERE val1=arg1 AND val2=arg2)

Why is datetime.strptime not working in this simple example?

You should use strftime static method from datetime class from datetime module. Try:

import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")

Force file download with php using header()

I’m pretty sure you don’t add the mime type as a JPEG on file downloads:

header('Content-Type: image/png');

These headers have never failed me:

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);

Copy a git repo without history

You can limit the depth of the history while cloning:

--depth <depth>
Create a shallow clone with a history truncated to the specified 
number of revisions.

Use this if you want limited history, but still some.

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

How to set null to a GUID property

you can make guid variable to accept null first using ? operator then you use Guid.Empty or typecast it to null using (Guid?)null;

eg:

 Guid? id = Guid.Empty;

or

 Guid? id =  (Guid?)null;

How to convert int to float in python?

The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.

The question asked is just a type conversion question and here its conversion from int data type to float data type and for that you can do it by the function :

float()

And for more details you can visit this page.

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

I think Quirksmode has all the answers you need (different browsers bubbling behaviour and the mouseenter/mouseleave events), but I think the most common conclusion to that event bubbling mess is the use of a framework like JQuery or Mootools (which has the mouseenter and mouseleave events, which are exactly what you intuited would happen).

Have a look at how they do it, if you want, do it yourself
or you can create your custom "lean mean" version of Mootools with just the event part (and its dependencies).

Laravel: Validation unique on update

If i understand what you want:

'email' => 'required|email|unique:users,email_address,'. $id .''

In model update method, for exemple, should receive the $id with parameter.

Sorry my bad english.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string Index = i;
            string FileName = "Mutton" + Index + ".xml";
            XmlDocument xmlDoc = new XmlDocument();

            var path = Path.Combine(Server.MapPath("~/Content/FilesXML"), FileName);
            xmlDoc.Load(path); // Can use xmlDoc.LoadXml(YourString);

this is the best Solution to get the path what is exactly need for now

How to properly use jsPDF library

Shouldn't you also be using the jspdf.plugin.from_html.js library? Besides the main library (jspdf.js), you must use other libraries for "special operations" (like jspdf.plugin.addimage.js for using images). Check https://github.com/MrRio/jsPDF.

What is "android.R.layout.simple_list_item_1"?

android.R.layout.simple_list_item_1, this is row layout file in your res/layout folder which contains the corresponding design for your row in listview. Now we just bind the array list items to the row layout by using mylistview.setadapter(aa);

How to copy directories with spaces in the name

What's with separating My Documents from C:\test-backup? And why the quotes only around My Documents?

I'm assuming it's a typo, try using robocopy C:\Users\Angie "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

[Edit:] Since the syntax the documentation specifies (robocopy <Source> <Destination> [<File>[ ...]]) says File, it might not work with Folders.

You'll have to userobocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

How can I use a for each loop on an array?

I use the counter variable like Fink suggests. If you want For Each and to pass ByRef (which can be more efficient for long strings) you have to cast your element as a string using CStr

Sub Example()

    Dim vItm As Variant
    Dim aStrings(1 To 4) As String

    aStrings(1) = "one": aStrings(2) = "two": aStrings(3) = "three": aStrings(4) = "four"

    For Each vItm In aStrings
        do_something CStr(vItm)
    Next vItm

End Sub

Function do_something(ByRef sInput As String)

    Debug.Print sInput

End Function

Django Server Error: port is already in use

It seems that IDEs, VSCode, Puppeteer, nodemon, express, etc. causes this problem, you ran a process in the background or just closed the debugging area [browser, terminal, etc. ] or whatever , anyway, i have answered same question before, Here you are it's link

https://stackoverflow.com/a/49797588/2918720

How do I add more members to my ENUM-type column in MySQL?

Your code works for me. Here is my test case:

mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                            |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
  `country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                       |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
  `country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

What error are you seeing?

FWIW this would also work:

ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');

I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.

EDIT: Now that I can see your error message:

ERROR 1265 (01000): Data truncated for column 'country' at row 1.

I suspect you have some values in your country column that do not appear in your ENUM. What is the output of the following command?

SELECT DISTINCT country FROM carmake;

ANOTHER EDIT: What is the output of the following command?

SHOW VARIABLES LIKE 'sql_mode';

Is it STRICT_TRANS_TABLES or STRICT_ALL_TABLES? That could lead to an error, rather than the usual warning MySQL would give you in this situation.

YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM. The new ENUM definition only allows 'Sweden' and 'Malaysia'. The table has 'USA', 'India' and several others.

LAST EDIT (MAYBE): I think you're trying to do this:

ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;

How to export a mysql database using Command Prompt?

The problem with all these solutions (using the > redirector character) is that you write your dump from stdout which may break the encoding of some characters of your database.

If you have a character encoding issue. Such as :

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ...

then, you MUST use -r option to write the file.

MySQL

mysqldump -u user -pyour-password-without-space-between-letter-p-and-your-password --default-character-set=utf8 --host $HOST database-name -r dump.sql

Using Docker

docker exec --rm -v $pwd:dump -it mysql:5:7 mysqldump -u user -pyour-password-without-space-between-letter-p-and-your-password --default-character-set=utf8 --host $HOST database-name -r dump/dump.sql

Note: this mounts the current path as dump inside the instance.

We found the answer here

Conversely, don't use < to import your dump into your database, again, your non-utf8 characters may not be passed; but prefer source option.

mysql -u user -pYourPasswordYouNowKnowHow --default-character-set=utf8 your-database
mysql> SET names 'utf8'
mysql> SOURCE dump.sql

What's the best way to select the minimum value from several columns?

The best way to do that is probably not to do it - it's strange that people insist on storing their data in a way that requires SQL "gymnastics" to extract meaningful information, when there are far easier ways to achieve the desired result if you just structure your schema a little better :-)

The right way to do this, in my opinion, is to have the following table:

ID    Col    Val
--    ---    ---
 1      1      3
 1      2     34
 1      3     76

 2      1     32
 2      2    976
 2      3     24

 3      1      7
 3      2    235
 3      3      3

 4      1    245
 4      2      1
 4      3    792

with ID/Col as the primary key (and possibly Col as an extra key, depending on your needs). Then your query becomes a simple select min(val) from tbl and you can still treat the individual 'old columns' separately by using where col = 2 in your other queries. This also allows for easy expansion should the number of 'old columns' grow.

This makes your queries so much easier. The general guideline I tend to use is, if you ever have something that looks like an array in a database row, you're probably doing something wrong and should think about restructuring the data.


However, if for some reason you can't change those columns, I'd suggest using insert and update triggers and add another column which these triggers set to the minimum on Col1/2/3. This will move the 'cost' of the operation away from the select to the update/insert where it belongs - most database tables in my experience are read far more often than written so incurring the cost on write tends to be more efficient over time.

In other words, the minimum for a row only changes when one of the other columns change, so that's when you should be calculating it, not every time you select (which is wasted if the data isn't changing). You would then end up with a table like:

ID   Col1   Col2   Col3   MinVal
--   ----   ----   ----   ------
 1      3     34     76        3
 2     32    976     24       24
 3      7    235      3        3
 4    245      1    792        1

Any other option that has to make decisions at select time is usually a bad idea performance-wise, since the data only changes on insert/update - the addition of another column takes up more space in the DB and will be slightly slower for the inserts and updates but can be much faster for selects - the preferred approach should depend on your priorities there but, as stated, most tables are read far more often than they're written.

Class extending more than one class Java?

In Java multiple inheritance is not permitted. It was excluded from the language as a design decision, primarily to avoid circular dependencies.

Scenario1: As you have learned the following is not possible in Java:

public class Dog extends Animal, Canine{

}

Scenario 2: However the following is possible:

public class Canine extends Animal{

}

public class Dog extends Canine{

}

The difference in these two approaches is that in the second approach there is a clearly defined parent or super class, while in the first approach the super class is ambiguous.

Consider if both Animal and Canine had a method drink(). Under the first scenario which parent method would be called if we called Dog.drink()? Under the second scenario, we know calling Dog.drink() would call the Canine classes drink method as long as Dog had not overridden it.

Why is it string.join(list) instead of list.join(string)?

Think of it as the natural orthogonal operation to split.

I understand why it is applicable to anything iterable and so can't easily be implemented just on list.

For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.

Find JavaScript function definition in Chrome

You can print the function by evaluating the name of it in the console, like so

> unknownFunc
function unknownFunc(unknown) {
    alert('unknown seems to be ' + unknown);
}

this won't work for built-in functions, they will only display [native code] instead of the source code.

EDIT: this implies that the function has been defined within the current scope.

How can I call controller/view helper methods from the console in Ruby on Rails?

An easy way to call a controller action from a script/console and view/manipulate the response object is:

> app.get '/posts/1'
> response = app.response
# You now have a Ruby on Rails response object much like the integration tests

> response.body            # Get you the HTML
> response.cookies         # Hash of the cookies

# etc., etc.

The app object is an instance of ActionController::Integration::Session

This works for me using Ruby on Rails 2.1 and 2.3, and I did not try earlier versions.

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

How to take character input in java

use the System class

char yourChar = System.in.read()

How do you access the matched groups in a JavaScript regular expression?

Your syntax probably isn't the best to keep. FF/Gecko defines RegExp as an extension of Function.
(FF2 went as far as typeof(/pattern/) == 'function')

It seems this is specific to FF -- IE, Opera, and Chrome all throw exceptions for it.

Instead, use either method previously mentioned by others: RegExp#exec or String#match.
They offer the same results:

var regex = /(?:^|\s)format_(.*?)(?:\s|$)/;
var input = "something format_abc";

regex(input);        //=> [" format_abc", "abc"]
regex.exec(input);   //=> [" format_abc", "abc"]
input.match(regex);  //=> [" format_abc", "abc"]

How to stop mongo DB in one command

From the given commands I think you're on Linux.

Start MongoDB:

$ sudo service mongod start
mongod start/running, process XXXXX 

Check the Status:

$ sudo service mongod status
mongod start/running, process XXXXX 

Stop MongoDB:

$ sudo service mongod stop
mongod stop/waiting 

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

When to use an interface instead of an abstract class and vice versa?

When to prefer an abstract class over interface?

  1. If one plans on updating a base class throughout the life of a program/project, it is best to allow that the base class be an abstract class
  2. If one is trying to build a backbone for objects that are closely related in a hierarchy, it is highly beneficial to use an abstract class

When to prefer an interface over abstract class?

  1. If one is not dealing with a massive hierarchical type of framework, interfaces would be a great choice
  2. Because multiple inheritance is not supported with abstract classes(diamond problem), interfaces can save the day

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

"location" directive should be inside a 'server' directive, e.g.

server {
    listen       8765;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

In Python, how do I create a string of n characters in one line of code?

If you can use repeated letters, you can use the * operator:

>>> 'a'*5

'aaaaa'

How to display a Windows Form in full screen on top of the taskbar?

Use:

FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;

And then your form is placed over the taskbar.

how to save canvas as png image?

I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:

function download(){
        var download = document.getElementById("download");
        var image = document.getElementById("canvas").toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
        download.setAttribute("href", image);

    }

In the body part of your HTML specify the button:

<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>

This is working and download link looks like a button. Tested in Firefox and Chrome.

How to get current foreground activity context in android?

@lockwobr Thanks for update

This does not work 100% of the time in api version 16, if you read the code on github the function "currentActivityThread" was change in Kitkat, so I want to say version 19ish, kind of hard to match api version to releases in github.

Having access to the current Activity is very handy. Wouldn’t it be nice to have a static getActivity method returning the current Activity with no unnecessary questions?

The Activity class is very useful. It gives access to the application’s UI thread, views, resources, and many more. Numerous methods require a Context, but how to get the pointer? Here are some ways:

  • Tracking the application’s state using overridden lifecycle methods. You have to store the current Activity in a static variable and you need access to the code of all Activities.
  • Tracking the application’s state using Instrumentation. Declare Instrumentation in the manifest, implement it and use its methods to track Activity changes. Passing an Activity pointer to methods and classes used in your Activities. Injecting the pointer using one of the code injection libraries. All of these approaches are rather inconvenient; fortunately, there is a much easier way to get the current Activity.
  • Seems like the system needs access to all Activities without the issues mentioned above. So, most likely there is a way to get Activities using only static calls. I spent a lot of time digging through the Android sources on grepcode.com, and I found what I was looking for. There is a class called ActivityThread. This class has access to all Activities and, what’s even better, has a static method for getting the current ActivityThread. There is only one little problem – the Activity list has package access.

Easy to solve using reflection:

public static Activity getActivity() {
    Class activityThreadClass = Class.forName("android.app.ActivityThread");
    Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
    Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
    activitiesField.setAccessible(true);

    Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
    if (activities == null)
        return null;

    for (Object activityRecord : activities.values()) {
        Class activityRecordClass = activityRecord.getClass();
        Field pausedField = activityRecordClass.getDeclaredField("paused");
        pausedField.setAccessible(true);
        if (!pausedField.getBoolean(activityRecord)) {
            Field activityField = activityRecordClass.getDeclaredField("activity");
            activityField.setAccessible(true);
            Activity activity = (Activity) activityField.get(activityRecord);
            return activity;
        }
    }

    return null;
}

Such a method can be used anywhere in the app and it’s much more convenient than all of the mentioned approaches. Moreover, it seems like it’s not as unsafe as it looks. It doesn’t introduce any new potential leaks or null pointers.

The above code snippet lacks exception handling and naively assumes that the first running Activity is the one we’re looking for. You might want to add some additional checks.

Blog Post

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

Parse error: Syntax error, unexpected end of file in my PHP code

If your using parse_ini_file($file) or a routine is rading an .ini file, check if you data is quoted in the ini file. Unquoted data will cause this error. Ex; data1=test will cause the error, data1="test" will not.

How can I get the SQL of a PreparedStatement?

To do this you need a JDBC Connection and/or driver that supports logging the sql at a low level.

Take a look at log4jdbc

How do I connect to an MDF database file?

Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;

How to use SVG markers in Google Maps API v3

Things are going better, right now you can use SVG files.

        marker = new google.maps.Marker({
            position: {lat: 36.720426, lng: -4.412573},
            map: map,
            draggable: true,
            icon: "img/tree.svg"
        });

How to send a PUT/DELETE request in jQuery?

You should be able to use jQuery.ajax :

Load a remote page using an HTTP request.


And you can specify which method should be used, with the type option :

The type of request to make ("POST" or "GET"), default is "GET".
Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Resize image in the wiki of GitHub using Markdown

Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,

_x000D_
_x000D_
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
_x000D_
_x000D_

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Convert tuple to list and back

You have a tuple of tuples.
To convert every tuple to a list:

[list(i) for i in level] # list of lists

--- OR ---

map(list, level)

And after you are done editing, just convert them back:

tuple(tuple(i) for i in edited) # tuple of tuples

--- OR --- (Thanks @jamylak)

tuple(itertools.imap(tuple, edited))

You can also use a numpy array:

>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1]])

For manipulating:

if clicked[0] == 1:
    x = (mousey + cameraY) // 60 # For readability
    y = (mousex + cameraX) // 60 # For readability
    a[x][y] = 1

How can I generate an apk that can run without server with react-native?

Generate debug APK without dev-server

If you really want to generate a debug APK (for testing purpose) that can run without the development server, Here is the link to my answer to another similar post which may help you.
https://stackoverflow.com/a/65762142/7755579

All you've to do is:

  1. edit android/app/build.gradle
project.ext.react = [
    ...
    bundleInDebug: true, // add this line
]
  1. run this command at the root directory of your project
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
  1. Then, run gradlew assembleDebug inside /android folder
    If build failed, I suggest you to build from Android studio

Upload a file to Amazon S3 with NodeJS

So it looks like there are a few things going wrong here. Based on your post it looks like you are attempting to support file uploads using the connect-multiparty middleware. What this middleware does is take the uploaded file, write it to the local filesystem and then sets req.files to the the uploaded file(s).

The configuration of your route looks fine, the problem looks to be with your items.upload() function. In particular with this part:

var params = {
  Key: file.name,
  Body: file
};

As I mentioned at the beginning of my answer connect-multiparty writes the file to the local filesystem, so you'll need to open the file and read it, then upload it, and then delete it on the local filesystem.

That said you could update your method to something like the following:

var fs = require('fs');
exports.upload = function (req, res) {
    var file = req.files.file;
    fs.readFile(file.path, function (err, data) {
        if (err) throw err; // Something went wrong!
        var s3bucket = new AWS.S3({params: {Bucket: 'mybucketname'}});
        s3bucket.createBucket(function () {
            var params = {
                Key: file.originalFilename, //file.name doesn't exist as a property
                Body: data
            };
            s3bucket.upload(params, function (err, data) {
                // Whether there is an error or not, delete the temp file
                fs.unlink(file.path, function (err) {
                    if (err) {
                        console.error(err);
                    }
                    console.log('Temp File Delete');
                });

                console.log("PRINT FILE:", file);
                if (err) {
                    console.log('ERROR MSG: ', err);
                    res.status(500).send(err);
                } else {
                    console.log('Successfully uploaded data');
                    res.status(200).end();
                }
            });
        });
    });
};

What this does is read the uploaded file from the local filesystem, then uploads it to S3, then it deletes the temporary file and sends a response.

There's a few problems with this approach. First off, it's not as efficient as it could be, as for large files you will be loading the entire file before you write it. Secondly, this process doesn't support multi-part uploads for large files (I think the cut-off is 5 Mb before you have to do a multi-part upload).

What I would suggest instead is that you use a module I've been working on called S3FS which provides a similar interface to the native FS in Node.JS but abstracts away some of the details such as the multi-part upload and the S3 api (as well as adds some additional functionality like recursive methods).

If you were to pull in the S3FS library your code would look something like this:

var fs = require('fs'),
    S3FS = require('s3fs'),
    s3fsImpl = new S3FS('mybucketname', {
        accessKeyId: XXXXXXXXXXX,
        secretAccessKey: XXXXXXXXXXXXXXXXX
    });

// Create our bucket if it doesn't exist
s3fsImpl.create();

exports.upload = function (req, res) {
    var file = req.files.file;
    var stream = fs.createReadStream(file.path);
    return s3fsImpl.writeFile(file.originalFilename, stream).then(function () {
        fs.unlink(file.path, function (err) {
            if (err) {
                console.error(err);
            }
        });
        res.status(200).end();
    });
};

What this will do is instantiate the module for the provided bucket and AWS credentials and then create the bucket if it doesn't exist. Then when a request comes through to upload a file we'll open up a stream to the file and use it to write the file to S3 to the specified path. This will handle the multi-part upload piece behind the scenes (if needed) and has the benefit of being done through a stream, so you don't have to wait to read the whole file before you start uploading it.

If you prefer, you could change the code to callbacks from Promises. Or use the pipe() method with the event listener to determine the end/errors.

If you're looking for some additional methods, check out the documentation for s3fs and feel free to open up an issue if you are looking for some additional methods or having issues.

How to change position of Toast in Android?

Toast toast = Toast.makeText(this, "Custom toast creation", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
    toast.show();

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

Spring Boot @Value Properties

Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows

Sample Application.properties

file.directory = somePlaceOverHere

Sample Java Class

@ComponentScan
public class PrintProperty {

  @Value("${file.directory}")
  private String fileDirectory;

  @PostConstruct
  public void print() {
    System.out.println(fileDirectory);
  }
}

Code above will print out "somePlaceOverhere"

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Ran into a similar issue and my problem was that MySQL installed itself configured to run on non-default port. I do not know the reason for that, but to find out which port MySQL is running on, run the following in MySql client:

SHOW GLOBAL VARIABLES LIKE 'PORT';

How to add external fonts to android application

To implement you need use Typeface go through with sample below

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
   if (view instanceof TextView) 
   {
      TextView textView = (TextView) view;
      textView.setTypeface(typeface);
      }
   }
}

Razor MVC Populating Javascript array with Model Array

This would be better approach as I have implemented :)

@model ObjectUser
@using System.Web.Script.Serialization
@{ 
    var javaScriptSearilizer = new JavaScriptSerializer();
    var searializedObject = javaScriptSearilizer.Serialize(Model);
 }

<script>
    var searializedObject = @Html.Raw(searializedObject )
    console.log(searializedObject);
    alert(searializedObject);
</script>

Hope this will help you to prevent you from iterating model ( happy coding )

C++ Best way to get integer division and remainder

On x86 at least, g++ 4.6.1 just uses IDIVL and gets both from that single instruction.

C++ code:

void foo(int a, int b, int* c, int* d)
{
  *c = a / b;
  *d = a % b;
}

x86 code:

__Z3fooiiPiS_:
LFB4:
    movq    %rdx, %r8
    movl    %edi, %edx
    movl    %edi, %eax
    sarl    $31, %edx
    idivl   %esi
    movl    %eax, (%r8)
    movl    %edx, (%rcx)
    ret

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:

http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA

Perform curl request in javascript?

Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like

$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});

The callback parameter will be filled in automatically by the browser, so don't worry.

On the server side ('validate.php') you would have something like this

<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>

How to record phone calls in android?

The answer of pratt is bit uncomplete, because when you restart your device your app will working stop, recording stop, its become useless.

i m adding some line that copy in your project for complete working of Pratt answer.

<receiver
        android:name=".DeviceAdminDemo"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data
            android:name="android.app.admin"
            android:resource="@xml/device_admin" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.HOME" />
        </intent-filter>
    </receiver>

put this code in onReceive of DeviceAdminDemo

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    context.stopService(new Intent(context, TService.class));
    Intent myIntent = new Intent(context, TService.class);
    context.startService(myIntent);

}

Blurring an image via CSS?

This code is working for blur effect for all browsers.

filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);

ImportError: No module named PIL

On windows, try checking the path to the location of the PIL library. On my system, I noticed the path was

\Python26\Lib\site-packages\pil instead of \Python26\Lib\site-packages\PIL  

after renaming the pil folder to PIL, I was able to load the PIL module.

How can I pass data from Flask to JavaScript in a template?

<script>
    const geocodeArr = JSON.parse('{{ geocode | tojson }}');
    console.log(geocodeArr);
</script>

This uses jinja2 to turn the geocode tuple into a json string, and then the javascript JSON.parse turns that into a javascript array.

Where to find Application Loader app in Mac?

In more modern versions of Xcode, you'll find "Application Loader" under the "Xcode" menu (the first menu to the right of the Apple in the menu bar) and it'll be hiding in the "Open Developer Tools" submenu.

enter image description here

OWIN Startup Class Missing

Create One Class With Name Startup this will help you..

public class Startup
{
   public void Configuration(IAppBuilder app)
   {
      app.MapSignalR();
   }
}

Installing PDO driver on MySQL Linux server

On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql

There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.

What data type to use for money in Java?

I like using Tiny Types which would wrap either a double, BigDecimal, or int as previous answers have suggested. (I would use a double unless precision problems crop up).

A Tiny Type gives you type safety so you don't confused a double money with other doubles.

Class has been compiled by a more recent version of the Java Environment

Your JDK version: Java 8
Your JRE version: Java 9

Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java into <yourclassname>.java

javac -source 1.8 -target 1.8  *.java

source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.

map vs. hash_map in C++

Some of the key differences are in the complexity requirements.

  • A map requires O(log(N)) time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.

  • An unordered_map requires an 'average' time of O(1) for inserts and finds, but is allowed to have a worst-case time of O(N). This is because it's implemented using Hash Table data structure.

So, usually, unordered_map will be faster, but depending on the keys and the hash function you store, can become much worse.

How to check if a String is numeric in Java

Exceptions are expensive, but in this case the RegEx takes much longer. The code below shows a simple test of two functions -- one using exceptions and one using regex. On my machine the RegEx version is 10 times slower than the exception.

import java.util.Date;


public class IsNumeric {

public static boolean isNumericOne(String s) {
    return s.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.      
}

public static boolean isNumericTwo(String s) {
    try {
        Double.parseDouble(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static void main(String [] args) {

    String test = "12345.F";

    long before = new Date().getTime();     
    for(int x=0;x<1000000;++x) {
        //isNumericTwo(test);
        isNumericOne(test);
    }
    long after = new Date().getTime();

    System.out.println(after-before);

}

}

How do I get currency exchange rates via an API such as Google Finance?

I got this content from http://www.scriptarticle.com/2012/05/03/get-live-currency-rates-and-currency-conversion-using-php-and-apis/

<?php

function get_currency($from_Currency, $to_Currency, $amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);

    $url = "http://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency";

    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt ($ch, CURLOPT_USERAGENT,
                 "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('bld>', $rawdata);
    $data = explode($to_Currency, $data[1]);

    return round($data[0], 2);
}

// Call the function to get the currency converted
echo get_currency('USD', 'INR', 1);

?>

Absolute positioning ignoring padding of parent

I would set the child's width this way:

.child {position: absolute; width: calc(100% - padding);}

Padding, in the formula, is the sum of the left and right parent's padding. I admit it is probably not very elegant, but in my case, a div with the function of an overlay, it worked.

Setting java locale settings

I had to control this in a script that ran on a machine with French locale, but a specific Java program had to run with en_US. As already pointed out, the following works:

java -Duser.language=en -Duser.country=US ...

Alternatively,

LC_ALL=en_US.UTF-8 java ...

I prefer the latter.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

It's more than one error

Under apply plugin: 'android-library'

add this ::

android {
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}

In case of duplicate files it's easy, look inside the JAR under the META-INF dir and see what's causing the error. It could be multiple. In my case Couchbase Lite plugin. As you add more plugins, you will need more exceptions

How to append output to the end of a text file

You can use the >> operator. This will append data from a command to the end of a text file.

To test this try running:

echo "Hi this is a test" >> textfile.txt

Do this a couple of times and then run:

cat textfile.txt

You'll see your text has been appended several times to the textfile.txt file.

Convert data file to blob

async function FileToString (file) {
    try {
        let res = await file.raw.text();
        console.log(res);
    } catch (err) {
        throw err;
    }
}

Performance of Arrays vs. Lists

Very easy to measure...

In a small number of tight-loop processing code where I know the length is fixed I use arrays for that extra tiny bit of micro-optimisation; arrays can be marginally faster if you use the indexer / for form - but IIRC believe it depends on the type of data in the array. But unless you need to micro-optimise, keep it simple and use List<T> etc.

Of course, this only applies if you are reading all of the data; a dictionary would be quicker for key-based lookups.

Here's my results using "int" (the second number is a checksum to verify they all did the same work):

(edited to fix bug)

List/for: 1971ms (589725196)
Array/for: 1864ms (589725196)
List/foreach: 3054ms (589725196)
Array/foreach: 1860ms (589725196)

based on the test rig:

using System;
using System.Collections.Generic;
using System.Diagnostics;
static class Program
{
    static void Main()
    {
        List<int> list = new List<int>(6000000);
        Random rand = new Random(12345);
        for (int i = 0; i < 6000000; i++)
        {
            list.Add(rand.Next(5000));
        }
        int[] arr = list.ToArray();

        int chk = 0;
        Stopwatch watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            int len = list.Count;
            for (int i = 0; i < len; i++)
            {
                chk += list[i];
            }
        }
        watch.Stop();
        Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                chk += arr[i];
            }
        }
        watch.Stop();
        Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in list)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in arr)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        Console.ReadLine();
    }
}

open link in iframe

Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!

<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>

How do I add an existing directory tree to a project in Visual Studio?

I found no answer to my satisfaction, so I figured out myself.

Here is the answer to you if you want to add external source codes to your project and don't want to copy over the entire codes. I have many dependencies on other gits and they are updated hourly if not minutely. I can't do copy every hour to sync up. Here is what you need to do.

Assume this is structure:

/root/projA/src

/root/projA/includes

/root/projB/src

/root/projB/includes

/root/yourProj/src

/root/yourProj/includes

  1. Start your VS solution.
  2. Right-click the project name right below the Solution.
  3. Then click the "Add", "New Filter", put the name "projA" for projA.
  4. Right-click on the "projA", click "Add", "New Filter", enter name "src"
  5. Right-click on the "projA", click "Add", "New Filter", enter name "includes"
  6. Right-click "projA"/"src", click "Add", "Existing Item", then browse to the /root/projA/src to add all source codes or one by one for the ones you want.
  7. Do same for "projA"/"includes"
  8. Do same for projB. Now the external/existing projects outside yours are present in your solution/project. The VS will compile them together. Here is an trick. Since the projA and projB are virtual folders under your project, the compiler may not find the projA/includes.

  9. If it doesn't find the projA/includes, then right click the project, select the "Properties".

  10. Navigate to "C/C++". Edit "Additional Include Directories", add your projA/include as such "../projA/includes", relative path.

One caveat, if there are duplicated include/header files, the "exclude from project" on the "Header file" doesn't really work. It's a bug in VS.