Programs & Examples On #Tile

Patterns of identical shapes that have no gaps. They usually represent the playfield in various games. They are also used in web development for reducing the count of images which needs to be transmitted.

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

How to make flutter app responsive according to different screen size?

You can use MediaQuery for parent's dimension or FractionallySizedBox as containers.

How to calculate 1st and 3rd quartiles?

In my efforts to learn object-oriented programming alongside learning statistics, I made this, maybe you'll find it useful:

samplesCourse = [9, 10, 10, 11, 13, 15, 16, 19, 19, 21, 23, 28, 30, 33, 34, 36, 44, 45, 47, 60]

class sampleSet:
    def __init__(self, sampleList):
        self.sampleList = sampleList
        self.interList = list(sampleList) # interList is sampleList alias; alias used to maintain integrity of original sampleList

    def find_median(self):
        self.median = 0

        if len(self.sampleList) % 2 == 0:
            # find median for even-numbered sample list length
            self.medL = self.interList[int(len(self.interList)/2)-1]
            self.medU = self.interList[int(len(self.interList)/2)]
            self.median = (self.medL + self.medU)/2

        else:
            # find median for odd-numbered sample list length
            self.median = self.interList[int((len(self.interList)-1)/2)]
        return self.median

    def find_1stQuartile(self, median):
        self.lower50List = []
        self.Q1 = 0

        # break out lower 50 percentile from sampleList
        if len(self.interList) % 2 == 0:
            self.lower50List = self.interList[:int(len(self.interList)/2)]
        else:
            # drop median to make list ready to divide into 50 percentiles
            self.interList.pop(interList.index(self.median))
            self.lower50List = self.interList[:int(len(self.interList)/2)]

        # find 1st quartile (median of lower 50 percentiles)
        if len(self.lower50List) % 2 == 0:
            self.Q1L = self.lower50List[int(len(self.lower50List)/2)-1]
            self.Q1U = self.lower50List[int(len(self.lower50List)/2)]
            self.Q1 = (self.Q1L + self.Q1U)/2

        else:
            self.Q1 = self.lower50List[int((len(self.lower50List)-1)/2)]

        return self.Q1

    def find_3rdQuartile(self, median):
        self.upper50List = []
        self.Q3 = 0

        # break out upper 50 percentile from sampleList
        if len(self.sampleList) % 2 == 0:
            self.upper50List = self.interList[int(len(self.interList)/2):]
        else:
            self.interList.pop(interList.index(self.median))
            self.upper50List = self.interList[int(len(self.interList)/2):]

        # find 3rd quartile (median of upper 50 percentiles)
        if len(self.upper50List) % 2 == 0:
            self.Q3L = self.upper50List[int(len(self.upper50List)/2)-1]
            self.Q3U = self.upper50List[int(len(self.upper50List)/2)]
            self.Q3 = (self.Q3L + self.Q3U)/2

        else:
            self.Q3 = self.upper50List[int((len(self.upper50List)-1)/2)]

        return self.Q3

    def find_InterQuartileRange(self, Q1, Q3):
        self.IQR = self.Q3 - self.Q1
        return self.IQR

    def find_UpperFence(self, Q3, IQR):
        self.fence = self.Q3 + 1.5 * self.IQR
        return self.fence

samples = sampleSet(samplesCourse)
median = samples.find_median()
firstQ = samples.find_1stQuartile(median)
thirdQ = samples.find_3rdQuartile(median)
iqr = samples.find_InterQuartileRange(firstQ, thirdQ)
fence = samples.find_UpperFence(thirdQ, iqr)

print("Median is: ", median)
print("1st quartile is: ", firstQ)
print("3rd quartile is: ", thirdQ)
print("IQR is: ", iqr)
print("Upper fence is: ", fence)

Bootstrap 4: Multilevel Dropdown Inside Navigation

The following is MultiLevel dropdown based on bootstrap4. I tried it was according to the bootstrap4 basic dropdown.

_x000D_
_x000D_
.dropdown-submenu{_x000D_
    position: relative;_x000D_
}_x000D_
.dropdown-submenu a::after{_x000D_
    transform: rotate(-90deg);_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 40%;_x000D_
}_x000D_
.dropdown-submenu:hover .dropdown-menu, .dropdown-submenu:focus .dropdown-menu{_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    position: absolute !important;_x000D_
    margin-top: -30px;_x000D_
    left: 100%;_x000D_
}_x000D_
@media (max-width: 992px) {_x000D_
    .dropdown-menu{_x000D_
        width: 50%;_x000D_
    }_x000D_
    .dropdown-menu .dropdown-submenu{_x000D_
        width: auto;_x000D_
    }_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link 1</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
          <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
          <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" data-toggle="dropdown" href="#">Something else here</a>_x000D_
            <ul class="dropdown-menu">_x000D_
              <a class="dropdown-item" href="#">A</a>_x000D_
              <a class="dropdown-item" href="#">b</a>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Flutter - Layout a Grid

There are few named constructors in GridView for different scenarios,

Constructors

  1. GridView
  2. GridView.builder
  3. GridView.count
  4. GridView.custom
  5. GridView.extent

Below is a example of GridView constructor:

import 'package:flutter/material.dart';

void main() => runApp(
  MaterialApp(
    home: ExampleGrid(),
  ),
);

class ExampleGrid extends StatelessWidget {
  List<String> images = [
    "https://uae.microless.com/cdn/no_image.jpg",
    "https://images-na.ssl-images-amazon.com/images/I/81aF3Ob-2KL._UX679_.jpg",
    "https://www.boostmobile.com/content/dam/boostmobile/en/products/phones/apple/iphone-7/silver/device-front.png.transform/pdpCarousel/image.jpg",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgUgs8_kmuhScsx-J01d8fA1mhlCR5-1jyvMYxqCB8h3LCqcgl9Q",
    "https://ae01.alicdn.com/kf/HTB11tA5aiAKL1JjSZFoq6ygCFXaw/Unlocked-Samsung-GALAXY-S2-I9100-Mobile-Phone-Android-Wi-Fi-GPS-8-0MP-camera-Core-4.jpg_640x640.jpg",
    "https://media.ed.edmunds-media.com/gmc/sierra-3500hd/2018/td/2018_gmc_sierra-3500hd_f34_td_411183_1600.jpg",
    "https://hips.hearstapps.com/amv-prod-cad-assets.s3.amazonaws.com/images/16q1/665019/2016-chevrolet-silverado-2500hd-high-country-diesel-test-review-car-and-driver-photo-665520-s-original.jpg",
    "https://www.galeanasvandykedodge.net/assets/stock/ColorMatched_01/White/640/cc_2018DOV170002_01_640/cc_2018DOV170002_01_640_PSC.jpg",
    "https://media.onthemarket.com/properties/6191869/797156548/composite.jpg",
    "https://media.onthemarket.com/properties/6191840/797152761/composite.jpg",
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView(
        physics: BouncingScrollPhysics(), // if you want IOS bouncing effect, otherwise remove this line
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),//change the number as you want
        children: images.map((url) {
          return Card(child: Image.network(url));
        }).toList(),
      ),
    );
  }
}

If you want your GridView items to be dynamic according to the content, you can few lines to do that but the simplest way to use StaggeredGridView package. I have provided an answer with example here.

Below is an example for a GridView.count:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 4,
        children: List.generate(40, (index) {
          return Card(
            child: Image.network("https://robohash.org/$index"),
          ); //robohash.org api provide you different images for any number you are giving
        }),
      ),
    );
  }
}

Screenshot for above snippet:

Flutter gridview example by blasanka using card widget and robohash api

Example for a SliverGridView:

import 'package:flutter/material.dart';

void main() => runApp(
      MaterialApp(
        home: ExampleGrid(),
      ),
    );

class ExampleGrid extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        primary: false,
        slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(20.0),
            sliver: SliverGrid.count(
              crossAxisSpacing: 10.0,
              crossAxisCount: 2,
              children: List.generate(20, (index) {
                return Card(child: Image.network("https://robohash.org/$index"));
              }),
            ),
          ),
        ],
      )
    );
  }
}

Angular 2 Cannot find control with unspecified name attribute on formArrays

In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

One important fact about NVIDIA drivers that is not very well known is that its built is done by DKMS. This allows automatic rebuild in case of kernel upgrade, this happens on system startup. Because of that, it's quite easy to miss error messages, especially if you're working on cloud VM, or server without an additional IPMI/management interface. However, it's possible to trigger DKMS build just executing dkms autoinstall right after packages installation. If this fails then you'll have a meaningful error message about missing dependency or what so ever. If dkms autoinstall builds modules correctly you can simply load it by modprobe - there is no need to reboot the system (which is often used as a way to trigger DKMS rebuild). You can check an example here

Changing the URL in react-router v4 without using Redirect or Link

I'm using this to redirect with React Router v4:

this.props.history.push('/foo');

Hope it work for you ;)

Access to Image from origin 'null' has been blocked by CORS policy

Under the covers there will be some form of URL loading request. You can't load images or any other content via this method from a local file system.

Your image needs to be loaded via a web server, so accessed via a proper http URL.

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

implement addClass and removeClass functionality in angular2

You can basically switch the class using [ngClass]

for example

<button [ngClass]="{'active': selectedItem === 'item1'}" (click)="selectedItem = 'item1'">Button One</button>
<button [ngClass]="{'active': selectedItem === 'item2'}" (click)="selectedItem = 'item2'">Button Two</button>

How to sort dates from Oldest to Newest in Excel?

I was having the same problem and realised one of my dates was incorrect, I had 31/11/2017, but there is no 31/11/17. When I adjusted to 30/11/17 it sorted correctly. Hope that helps.

Add Favicon with React and Webpack

Another alternative is

npm install react-favicon

And in your application you would just do:

   import Favicon from 'react-favicon';
   //other codes

    ReactDOM.render(
        <div>
            <Favicon url="/path/to/favicon.ico"/>
            // do other stuff here
        </div>
        , document.querySelector('.react'));

How to get response from S3 getObject in Node.js?

Alternatively you could use minio-js client library get-object.js

var Minio = require('minio')

var s3Client = new Minio({
  endPoint: 's3.amazonaws.com',
  accessKey: 'YOUR-ACCESSKEYID',
  secretKey: 'YOUR-SECRETACCESSKEY'
})

var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
  if (e) {
    return console.log(e)
  }
  dataStream.on('data', function(chunk) {
    size += chunk.length
  })
  dataStream.on('end', function() {
    console.log("End. Total size = " + size)
  })
  dataStream.on('error', function(e) {
    console.log(e)
  })
})

Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.

app.post('/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

Angular 2 @ViewChild annotation returns undefined

I had a similar issue and thought I'd post in case someone else made the same mistake. First, one thing to consider is AfterViewInit; you need to wait for the view to be initialized before you can access your @ViewChild. However, my @ViewChild was still returning null. The problem was my *ngIf. The *ngIf directive was killing my controls component so I couldn't reference it.

import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './controls/controls.component';
import {SlideshowComponent} from './slideshow/slideshow.component';

@Component({
    selector: 'app',
    template:  `
        <controls *ngIf="controlsOn"></controls>
        <slideshow (mousemove)="onMouseMove()"></slideshow>
    `,
    directives: [SlideshowComponent, ControlsComponent]
})

export class AppComponent {
    @ViewChild(ControlsComponent) controls:ControlsComponent;

    controlsOn:boolean = false;

    ngOnInit() {
        console.log('on init', this.controls);
        // this returns undefined
    }

    ngAfterViewInit() {
        console.log('on after view init', this.controls);
        // this returns null
    }

    onMouseMove(event) {
         this.controls.show();
         // throws an error because controls is null
    }
}

Hope that helps.

EDIT
As mentioned by @Ashg below, a solution is to use @ViewChildren instead of @ViewChild.

Update index after sorting data-frame

You can set new indices by using set_index:

df2.set_index(np.arange(len(df2.index)))

Output:

   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

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

or:

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

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

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.

Now I have an extra step before attempting the resize operation, which is to do the assertion myself:

def getSizedFrame(width, height):
"""Function to return an image with the size I want"""    
    s, img = self.cam.read()

    # Only process valid image frames
    if s:
            img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
    return s, img

Now I don't see the error.

Take multiple lists into dataframe

Adding one more scalable solution.

lists = [lst1, lst2, lst3, lst4]
df = pd.concat([pd.Series(x) for x in lists], axis=1)

@Autowired - No qualifying bean of type found for dependency at least 1 bean

I believe for @Service you have to add qualifier name like below :

@Service("employeeService") should solve your issue

or after @Service you should add @Qualifier annontion like below :

@Service
@Qualifier("employeeService")

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

Had this issue when migrated spring boot 1.5.2 to 2.0.4. Instead of creating bean I've used @EnableAutoConfiguration in the main class and it solved my problem.

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

What is the optimal algorithm for the game 2048?

Many of the other answers use AI with computationally expensive searching of possible futures, heuristics, learning and the such. These are impressive and probably the correct way forward, but I wish to contribute another idea.

Model the sort of strategy that good players of the game use.

For example:

13 14 15 16
12 11 10  9
 5  6  7  8
 4  3  2  1

Read the squares in the order shown above until the next squares value is greater than the current one. This presents the problem of trying to merge another tile of the same value into this square.

To resolve this problem, their are 2 ways to move that aren't left or worse up and examining both possibilities may immediately reveal more problems, this forms a list of dependancies, each problem requiring another problem to be solved first. I think I have this chain or in some cases tree of dependancies internally when deciding my next move, particularly when stuck.


Tile needs merging with neighbour but is too small: Merge another neighbour with this one.

Larger tile in the way: Increase the value of a smaller surrounding tile.

etc...


The whole approach will likely be more complicated than this but not much more complicated. It could be this mechanical in feel lacking scores, weights, neurones and deep searches of possibilities. The tree of possibilities rairly even needs to be big enough to need any branching at all.

Responsive Bootstrap Jumbotron Background Image

This is what I did.
First, just override the jumbotron class, and do the following:

.jumbotron{
    background: url("bg.jpg") no-repeat center center; 
    -webkit-background-size: 100% 100%;
    -moz-background-size: 100% 100%;
    -o-background-size: 100% 100%;
    background-size: 100% 100%;
}

So, now you have a jumbotron with responsive background in place. However, as Irvin Zhan already answered, the height of the background still not showing correctly.

One thing you can do is fill your div with some spaces such as this:

<div class="jumbotron">
    <div class="container">
        About
        <br><br><br> <!--keep filling br until the height is to your liking-->
    </div>
</div>

Or, more elegantly, you can set the height of the container. You might want to add another class so that you don't override Bootstrap container class.

<div class="jumbotron">
    <div class="container push-spaces">
        About
    </div>
</div>

.push-spaces
{
    height: 100px;
}

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

Calculating percentile of dataset column

If you order a vector x, and find the values that is half way through the vector, you just found a median, or 50th percentile. Same logic applies for any percentage. Here are two examples.

x <- rnorm(100)
quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1)) # quartile
quantile(x, probs = seq(0, 1, by= 0.1)) # decile

Python json.loads shows ValueError: Extra data

I came across this because I was trying to load a JSON file dumped from MongoDB. It was giving me an error

JSONDecodeError: Extra data: line 2 column 1

The MongoDB JSON dump has one object per line, so what worked for me is:

import json
data = [json.loads(line) for line in open('data.json', 'r')]

Why is synchronized block better than synchronized method?

synchronized should only be used when you want your class to be Thread safe. In fact most of the classes should not use synchronized anyways. synchronized method would only provide a lock on this object and only for the duration of its execution. if you really wanna to make your classes thread safe, you should consider making your variables volatile or synchronize the access.

one of the issues of using synchronized method is that all of the members of the class would use the same lock which will make your program slower. In your case synchronized method and block would execute no different. what I'd would recommend is to use a dedicated lock and use a synchronized block something like this.

public class AClass {
private int x;
private final Object lock = new Object();     //it must be final!

 public void setX() {
    synchronized(lock) {
        x++;
    }
 }
}

Could not resolve placeholder in string value

In your configuration you have 2 PropertySourcesPlaceholderConfigurer instances.

applicationContext.xml

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="environment">
        <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
    </property>
</bean>

infraContext.xml

<context:property-placeholder location="classpath:context-core.properties"/>

By default a PlaceholderConfigurer is going to fail-fast, so if a placeholder cannot be resolved it will throw an exception. The instance from the applicationContext.xml file has no properties and as such will fail on all placeholders.

Solution: Remove the one from applicationContext.xml as it doesn't add anything it only breaks things.

How can I parse a local JSON file from assets folder into a ListView?

If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.


Utility.kt

fun Context.loadJSONFromAssets(fileName: String): String {
    return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
        reader.readText()
    }
}

MainActivity.kt

You can define private function for load JSON data from assert like this:

 lateinit var facilityModelList: ArrayList<FacilityModel>
 private fun bindJSONDataInFacilityList() {
    facilityModelList = ArrayList<FacilityModel>()
    val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
    for (i in 0 until facilityJsonArray.length()){
        val facilityModel = FacilityModel()
        val facilityJSONObject = facilityJsonArray.getJSONObject(i)
        facilityModel.Facility = facilityJSONObject.getString("Facility")
        facilityModel.District = facilityJSONObject.getString("District")
        facilityModel.Province = facilityJSONObject.getString("Province")
        facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
        facilityModel.code = facilityJSONObject.getInt("code")
        facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
        facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")

        facilityModelList.add(facilityModel)
    }
}

You have to pass facilityModelList in your ListView


FacilityModel.kt

class FacilityModel: Serializable {
    var District: String = ""
    var Facility: String = ""
    var Province: String = ""
    var Subdistrict: String = ""
    var code: Int = 0
    var gps_latitude: Double= 0.0
    var gps_longitude: Double= 0.0
}

In my case JSON response start with JSONArray

[
  {
    "code": 875933,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Amabele Clinic",
    "gps_latitude": -32.6634,
    "gps_longitude": 27.5239
  },

  {
    "code": 455242,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Burnshill Clinic",
    "gps_latitude": -32.7686,
    "gps_longitude": 27.055
  }
]

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

Representing Directory & File Structure in Markdown Syntax

If you're using VS Code, this is an awesome extension for generating file trees.

Added directly to markdown...

quakehunter
 ? client
 ? node_modules
 ? server
 ? ? index.js
 ? .gitignore
 ? package-lock.json
 ? package.json

How to get coordinates of an svg element?

I was trying to select an area of svg with a rectangle and get all the elements from it. For this, element.getBoundingClientRect() worked perfectly for me. It returns current coordinates of svg elements regardless of whether svg is scaled or transformed.

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

S3 - Access-Control-Allow-Origin Header

I was having a similar problem with loading web fonts, when I clicked on 'add CORS configuration', in the bucket properties, this code was already there:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration> 

I just clicked save and it worked a treat, my custom web fonts were loading in IE & Firefox. I'm no expert on this, I just thought this might help you out.

Convert tuple to list and back

To convert tuples to list

(Commas were missing between the tuples in the given question, it was added to prevent error message)

Method 1:

level1 = (
     (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))

level1 = [list(row) for row in level1]

print(level1)

Method 2:

level1 = map(list,level1)

print(list(level1))

Method 1 took --- 0.0019991397857666016 seconds ---

Method 2 took --- 0.0010001659393310547 seconds ---

Can't install any package with node npm

1.>Go to your this location

C:\Users\{your user name or ID}

2.> open .npmrc & Remove all content from .npmrc file.

3.>reopen your new command prompt

4.>again run the code , will work.

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

remove None value from a list without removing the 0 value

from operator import is_not
from functools import partial   

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

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

JUNIT testing void methods

If it is possible in your case, you could make your methods method1(arg1) ... method7() protected instead of private so they could be accesible from test class within the same package. Then you can simply test all theese methods separately.

Closing Twitter Bootstrap Modal From Angular Controller

**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
  $('#btnClose').click();// this is bootstrap modal close button id that fire click event
})

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

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()

Maven Java EE Configuration Marker with Java Server Faces 1.2

I had the same problem. After adding velocity dependencies in my maven project i was getting the same error in marker tab. Then I noticed that the web.xml file that maven project creates has servlet2.3 schema. When i changed it to servlet 3.0 schema and save the project then this error gone. Here is the web.xml file that maven creates

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

Change it to

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
                        version="3.0">
    <display-name>Archetype Created Web Application</display-name>

</web-app>

save the project, and your error would gone.

After that if markers tab is still showing message then Select the project. Do mouse right click. Select Maven --> Update Project.

Hopefully error would be gone then.

Thanks

Setting Action Bar title and subtitle

You can set the title in action-bar using AndroidManifest.xml. Add label to the activity

<activity
            android:name=".YourActivity"
            android:label="Your Title" />

Quantile-Quantile Plot using SciPy

How big is your sample? Here is another option to test your data against any distribution using OpenTURNS library. In the example below, I generate a sample x of 1.000.000 numbers from a Uniform distribution and test it against a Normal distribution. You can replace x by your data if you reshape it as x= [[x1], [x2], .., [xn]]

import openturns as ot

x = ot.Uniform().getSample(1000000)
g = ot.VisualTest.DrawQQplot(x, ot.Normal())
g

In my Jupyter Notebook, I see: enter image description here

If you are writing a script, you can do it more properly

from openturns.viewer import View`
import matplotlib.pyplot as plt
View(g)
plt.show()

What's a .sh file?

I know this is an old question and I probably won't help, but many Linux distributions(e.g., ubuntu) have a "Live cd/usb" function, so if you really need to run this script, you could try booting your computer into Linux. Just burn a .iso to a flash drive (here's how http://goo.gl/U1wLYA), start your computer with the drive plugged in, and press the F key for boot menu. If you choose "...USB...", you will boot into the OS you just put on the drive.

HTML favicon won't show on google chrome

I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.

Center Contents of Bootstrap row container

With Bootstrap 4, there is a css class specifically for this. The below will center row content:

<div class="row justify-content-center">
  ...inner divs and content...
</div>

See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

How to change the map center in Leaflet.js

You can also use:

map.setView(new L.LatLng(40.737, -73.923), 8);

It just depends on what behavior you want. map.panTo() will pan to the location with zoom/pan animation, while map.setView() immediately set the new view to the desired location/zoom level.

Store query result in a variable using in PL/pgSQL

You can use the following example to store a query result in a variable using PL/pgSQL:

 select * into demo from maintenanceactivitytrack ; 
    raise notice'p_maintenanceid:%',demo;

Thread Safe C# Singleton Pattern

In almost every case (that is: all cases except the very first ones), instance won't be null. Acquiring a lock is more costly than a simple check, so checking once the value of instance before locking is a nice and free optimization.

This pattern is called double-checked locking: http://en.wikipedia.org/wiki/Double-checked_locking

Custom sort function in ng-repeat

To include the direction along with the orderBy function:

ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"

where

defaultSortDirection = 0; // 0 = Ascending, 1 = Descending

Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

My gut told me the same thing when I came across this design.

I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.

I would ask the question "just because you can, should you?"

See this article for the problem I came across related to this design. The specified LINQ expression contains references to queries that are associated with different contexts

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

time delayed redirect?

You can include this directly in your buttun. It works very well. I hope it'll be useful for you. onclick="setTimeout('location.href = ../../dashboard.xhtml;', 7000);"

Find JavaScript function definition in Chrome

Lets say we're looking for function named foo:

  1. (open Chrome dev-tools),
  2. Windows: ctrl + shift + F, or macOS: cmd + optn + F. This opens a window for searching across all scripts.
  3. check "Regular expression" checkbox,
  4. search for foo\s*=\s*function (searches for foo = function with any number of spaces between those three tokens),
  5. press on a returned result.

Another variant for function definition is function\s*foo\s*\( for function foo( with any number of spaces between those three tokens.

Twitter Bootstrap Multilevel Dropdown Menu

I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:

.dropdown-menu li {
    position: relative;
}

I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).

Here is the full less/css change (replace the above with this):

.dropdown-menu li {
    position: relative;

    [class^="icon-"] {
        float: right;
    }

    &:hover {
        // Switch to white icons on hover
        [class^="icon-"] {
            background-image: url("../img/glyphicons-halflings-white.png");
        }
    }
}

What is the difference between atomic / volatile / synchronized?

A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.

Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.

Hope the explanation is clear enough.

How to prevent colliders from passing through each other?

  • Edit ---> Project Settings ---> Time ... decrease "Fixed Timestep" value .. This will solve the problem but it can affect performance negatively.

  • Another solution is could be calculate the coordinates (for example, you have a ball and wall. Ball will hit to wall. So calculate coordinates of wall and set hitting process according these cordinates )

C++ class forward declaration

The forward declaration is an "incomplete type", the only thing you can do with such a type is instantiate a pointer to it, or reference it in a function declaration (i.e. and argument or return type in a function prototype). In line 52 in your code, you are attempting to instantiate an object.

At that point the compiler has no knowledge of the object's size nor its constructor, so cannot instantiate an object.

YouTube Video Embedded via iframe Ignoring z-index?

Just add one of these two to the src url:

&wmode=Opaque

&wmode=transparent

<iframe id="videoIframe" width="500" height="281" src="http://www.youtube.com/embed/xxxxxx?rel=0&wmode=transparent" frameborder="0" allowfullscreen></iframe>

Case insensitive string as HashMap key

Two choices come to my mind:

  1. You could use directly the s.toUpperCase().hashCode(); as the key of the Map.
  2. You could use a TreeMap<String> with a custom Comparator that ignore the case.

Otherwise, if you prefer your solution, instead of defining a new kind of String, I would rather implement a new Map with the required case insensibility functionality.

Attributes / member variables in interfaces?

Something important has been said by Tom:

if you use the has-a concept, you avoid the issue.

Indeed, if instead of using extends and implements you define two attributes, one of type rectangle, one of type JLabel in your Tile class, then you can define a Rectangle to be either an interface or a class.

Furthermore, I would normally encourage the use of interfaces in connection with has-a, but I guess it would be an overkill in your situation. However, you are the only one that can decide on this point (tradeoff flexibility/over-engineering).

How to get file path in iPhone app

You need to use the URL for the link, such as this:

NSURL *path = [[NSBundle mainBundle] URLForResource:@"imagename" withExtension:@"jpg"];

It will give you a proper URL ref.

Maven2: Missing artifact but jars are in place

I had a similar solution like @maximilianus. The difference was that my .repositories files were called _remote.repositores and I had to delete them to make it work.

For eg in my case I deleted

  • C:\Users\USERNAME.m2\repository\jta\jta\1.0.1_remote.repositories and
  • C:\Users\USERNAME.m2\repository\jndi\jndi\1.2.1_remote.repositories

After doing so my errors disappeared.

How to cache Google map tiles for offline usage?

Unfortunately, I found this link which appears to indicate that we cannot cache these locally, therefore making this question moot.

http://support.google.com/enterprise/doc/gme/terms/maps_purchase_agreement.html

4.4 Cache Restrictions. Customer may not pre-fetch, retrieve, cache, index, or store any Content, or portion of the Services with the exception being Customer may store limited amounts of Content solely to improve the performance of the Customer Implementation due to network latency, and only if Customer does so temporarily, securely, and in a manner that (a) does not permit use of the Content outside of the Services; (b) is session-based only (once the browser is closed, any additional storage is prohibited); (c) does not manipulate or aggregate any Content or portion of the Services; (d) does not prevent Google from accurately tracking Page Views; and (e) does not modify or adjust attribution in any way.

So it appears we cannot use Google map tiles offline, legally.

JavaScript is in array

As mentioned before, if your browser supports indexOf(), great! If not, you need to pollyfil it or rely on an utility belt like lodash/underscore.

Just wanted to add this newer ES2016 addition (to keep this question updated):

Array.prototype.includes()

if (blockedTile.includes("118")) {
    // found element
}

Ignore outliers in ggplot2 boxplot

If you want to force the whiskers to extend to the max and min values, you can tweak the coef argument. Default value for coef is 1.5 (i.e. default length of the whiskers is 1.5 times the IQR).

# Load package and create a dummy data frame with outliers 
#(using example from Ramnath's answer above)
library(ggplot2)
df = data.frame(y = c(-100, rnorm(100), 100))

# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))

# create boxplot where whiskers extend to max and min values
p1 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)), coef = 500)

image of p0

image of p1

Tools for making latex tables in R

Two utilities in package taRifx can be used in concert to produce multi-row tables of nested heirarchies.

library(datasets)
library(taRifx)
library(xtable)

test.by <- bytable(ChickWeight$weight, list( ChickWeight$Chick, ChickWeight$Diet) )
colnames(test.by) <- c('Diet','Chick','Mean Weight')
print(latex.table.by(test.by), include.rownames = FALSE, include.colnames = TRUE, sanitize.text.function = force)
#   then add \usepackage{multirow} to the preamble of your LaTeX document
#   for longtable support, add ,tabular.environment='longtable' to the print command (plus add in ,floating=FALSE), then \usepackage{longtable} to the LaTeX preamble

sample table output

How to push both key and value into an Array in Jquery

arr[title] = link;

You're not pushing into the array, you're setting the element with the key title to the value link. As such your array should be an object.

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

The method I use is one of these or Hmisc::cut2(value, g=4):

temp$quartile <- with(temp, cut(value, 
                                breaks=quantile(value, probs=seq(0,1, by=0.25), na.rm=TRUE), 
                                include.lowest=TRUE))

An alternate might be:

temp$quartile <- with(temp, factor(
                            findInterval( val, c(-Inf,
                               quantile(val, probs=c(0.25, .5, .75)), Inf) , na.rm=TRUE), 
                            labels=c("Q1","Q2","Q3","Q4")
      ))

The first one has the side-effect of labeling the quartiles with the values, which I consider a "good thing", but if it were not "good for you", or the valid problems raised in the comments were a concern you could go with version 2. You can use labels= in cut, or you could add this line to your code:

temp$quartile <- factor(temp$quartile, levels=c("1","2","3","4") )

Or even quicker but slightly more obscure in how it works, although it is no longer a factor, but rather a numeric vector:

temp$quartile <- as.numeric(temp$quartile)

What are the options for storing hierarchical data in a relational database?

This is really a square peg, round hole question.

If relational databases and SQL are the only hammer you have or are willing to use, then the answers that have been posted thus far are adequate. However, why not use a tool designed to handle hierarchical data? Graph database are ideal for complex hierarchical data.

The inefficiencies of the relational model along with the complexities of any code/query solution to map a graph/hierarchical model onto a relational model is just not worth the effort when compared to the ease with which a graph database solution can solve the same problem.

Consider a Bill of Materials as a common hierarchical data structure.

class Component extends Vertex {
    long assetId;
    long partNumber;
    long material;
    long amount;
};

class PartOf extends Edge {
};

class AdjacentTo extends Edge {
};

Shortest path between two sub-assemblies: Simple graph traversal algorithm. Acceptable paths can be qualified based on criteria.

Similarity: What is the degree of similarity between two assemblies? Perform a traversal on both sub-trees computing the intersection and union of the two sub-trees. The percent similar is the intersection divided by the union.

Transitive Closure: Walk the sub-tree and sum up the field(s) of interest, e.g. "How much aluminum is in a sub-assembly?"

Yes, you can solve the problem with SQL and a relational database. However, there are much better approaches if you are willing to use the right tool for the job.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Volatile boolean vs AtomicBoolean

Volatile boolean vs AtomicBoolean

The Atomic* classes wrap a volatile primitive of the same type. From the source:

public class AtomicLong extends Number implements java.io.Serializable {
   ...
   private volatile long value;
   ...
   public final long get() {
       return value;
   }
   ...
   public final void set(long newValue) {
       value = newValue;
   }

So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.

What does AtomicBoolean do that a volatile boolean cannot achieve?

Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet() for numbers, compareAndSet() for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.

For example, if multiple threads are using the following code using ++, there will be race conditions because ++ is actually: get, increment, and set.

private volatile value;
...
// race conditions here
value++;

However, the following code will work in a multi-threaded environment safely without locks:

private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();

It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.10</version>
    </dependency>

reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

What are Transient and Volatile Modifiers?

Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

Find objects between two dates MongoDB

MongoDB actually stores the millis of a date as an int(64), as prescribed by http://bsonspec.org/#/specification

However, it can get pretty confusing when you retrieve dates as the client driver will instantiate a date object with its own local timezone. The JavaScript driver in the mongo console will certainly do this.

So, if you care about your timezones, then make sure you know what it's supposed to be when you get it back. This shouldn't matter so much for the queries, as it will still equate to the same int(64), regardless of what timezone your date object is in (I hope). But I'd definitely make queries with actual date objects (not strings) and let the driver do its thing.

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. The period is a regular expression metacharacter that matches anything, thus every character in line is considered to be a split character, and is thrown away, and all of the empty strings between them are thrown away (because they're empty strings). The result is that you have nothing left.

If you escape the period (by adding an escaped backslash before it), then you can match literal periods. (line.split("\\."))

How to make an app's background image repeat

Here is a pure-java implementation of background image repeating:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
    LinearLayout layout = new LinearLayout(this);
    layout.setBackgroundDrawable(bitmapDrawable);
}

In this case, our background image would have to be stored in res/drawable/bg_image.png.

Centering a background image, using CSS

Like this:

background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dore_woodcut_Divine_Comedy_01.jpg/481px-Dore_woodcut_Divine_Comedy_01.jpg);
background-repeat:no-repeat;
background-position: center;
background-size: cover;

_x000D_
_x000D_
html{_x000D_
height:100%_x000D_
}_x000D_
_x000D_
body{_x000D_
background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dore_woodcut_Divine_Comedy_01.jpg/481px-Dore_woodcut_Divine_Comedy_01.jpg);_x000D_
background-repeat:no-repeat;_x000D_
background-position: center;_x000D_
background-size: cover;_x000D_
}
_x000D_
_x000D_
_x000D_

link button property to open in new tab?

 <asp:LinkButton ID="LinkButton1" runat="server" target="_blank">LinkButton</asp:LinkButton>

Use target="_blank" because It creates anchor markup. the following HTML is generated for above code

<a id="ctl00_ContentPlaceHolder1_LinkButton1" target="_blank" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$LinkButton1','')">LinkButton</a>

Getting SyntaxError for print with keyword argument end=' '

Compatible with both Python 2 & 3:

sys.stdout.write('mytext')

Compatible with only Python 2

print 'mytext',

Compatible with only Python 3

print('mytext', end='')

Volatile vs Static in Java

Difference Between Static and Volatile :

Static Variable: If two Threads(suppose t1 and t2) are accessing the same object and updating a variable which is declared as static then it means t1 and t2 can make their own local copy of the same object(including static variables) in their respective cache, so update made by t1 to the static variable in its local cache wont reflect in the static variable for t2 cache .

Static variables are used in the context of Object where update made by one object would reflect in all the other objects of the same class but not in the context of Thread where update of one thread to the static variable will reflect the changes immediately to all the threads (in their local cache).

Volatile variable: If two Threads(suppose t1 and t2) are accessing the same object and updating a variable which is declared as volatile then it means t1 and t2 can make their own local cache of the Object except the variable which is declared as a volatile . So the volatile variable will have only one main copy which will be updated by different threads and update made by one thread to the volatile variable will immediately reflect to the other Thread.

How do I calculate percentiles with python/numpy?

You might be interested in the SciPy Stats package. It has the percentile function you're after and many other statistical goodies.

percentile() is available in numpy too.

import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print p
3.0

This ticket leads me to believe they won't be integrating percentile() into numpy anytime soon.

How to prevent gcc optimizing some statements in C?

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

How to call a function, PostgreSQL

if your function does not want to return anything you should declare it to "return void" and then you can call it like this "perform functionName(parameter...);"

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

My issue was that the root element actually has a xmlns="abc123"

So had to make XmlRoot("elementname",NameSpace="abc123")

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

Drawing Isometric game worlds

If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:

...1...
..234..
.56789.
..abc..
...d...

Why both no-cache and no-store should be used in HTTP response?

For chrome, no-cache is used to reload the page on a re-visit, but it still caches it if you go back in history (back button). To reload the page for history-back as well, use no-store. IE needs must-revalidate to work in all occasions.

So just to be sure to avoid all bugs and misinterpretations I always use

Cache-Control: no-store, no-cache, must-revalidate

if I want to make sure it reloads.

How can I check whether Google Maps is fully loaded?

You could check the GMap2.isLoaded() method every n milliseconds to see if the map and all its tiles were loaded (window.setTimeout() or window.setInterval() are your friends).

While this won't give you the exact event of the load completion, it should be good enough to trigger your Javascript.

Side-by-side list items as icons within a div (css)

This can be a pure CSS solution. Given:

<ul class="tileMe">
    <li>item 1<li>
    <li>item 2<li>
    <li>item 3<li>
</ul>

The CSS would be:

.tileMe li {
    display: inline;
    float: left;
}

Now, since you've changed the display mode from 'block' (implied) to 'inline', any padding, margin, width, or height styles you applied to li elements will not work. You need to nest a block-level element inside the li:

<li><a class="tile" href="home">item 1</a></li>

and add the following CSS:

.tile a {
    display: block;
    padding: 10px;
    border: 1px solid red;
    margin-right: 5px;
}

The key concept behind this solution is that you are changing the display style of the li to 'inline', and nesting a block-level element inside to achieve the consistent tiling effect.

What does the return keyword do in a void method in Java?

It just exits the method at that point. Once return is executed, the rest of the code won't be executed.

eg.

public void test(int n) {
    if (n == 1) {
        return; 
    }
    else if (n == 2) {
        doStuff();
        return;
    }
    doOtherStuff();
}

Note that the compiler is smart enough to tell you some code cannot be reached:

if (n == 3) {
    return;
    youWillGetAnError(); //compiler error here
}

How do I resize a Google Map with JavaScript after it has loaded?

First of all, thanks for guiding me and closing this issue. I found a way to fix this issue from your discussions. Yeah, Let's come to the point. The thing is I'm Using GoogleMapHelper v3 helper in CakePHP3. When i tried to open bootstrap modal popup, I got struck with the grey box issue over the map. It's been extended for 2 days. Finally i got a fix over this.

We need to Update the GoogleMapHelper to fix the issue

Need to add the below script in setCenterMap function

google.maps.event.trigger({$id}, \"resize\");

And need the include below code in JavaScript

google.maps.event.addListenerOnce({$id}, 'idle', function(){
   setCenterMap(new google.maps.LatLng({$this->defaultLatitude}, 
   {$this->defaultLongitude}));
});

Why is volatile needed in C?

The Wiki say everything about volatile:

And the Linux kernel's doc also make a excellent notation about volatile:

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

I was trying to do the same thing, but I wanted the back button to be in the navigation bar. (I actually needed a back button, that would do more than only going back, so I had to use the leftBarButtonItem property). I tried what AndrewS suggested, but in the navigation bar it wouldn't look the way it should, as the UIButton was kind of casted to a UIBarButtonItem.

But I found a way to work around this. I actually just put a UIView under the UIButton and set the customView for the UIBarButtonItem. Here is the code, if somebody needs it:

// initialize button and button view
UIButton *backButton = [UIButton buttonWithType:101];
UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backButton.frame.size.width, backButton.frame.size.height)];

[backButton addTarget:self action:@selector(backButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[backButtonView addSubview:backButton];

// set buttonview as custom view for bar button item
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
self.navigationItem.leftBarButtonItem = backButtonItem;

// push item to navigationbar items
[self.navigationController.navigationBar setItems:[NSArray arrayWithObject:backButtonItem]];

Volatile vs. Interlocked vs. lock

lock(...) works, but may block a thread, and could cause deadlock if other code is using the same locks in an incompatible way.

Interlocked.* is the correct way to do it ... much less overhead as modern CPUs support this as a primitive.

volatile on its own is not correct. A thread attempting to retrieve and then write back a modified value could still conflict with another thread doing the same.

What is the volatile keyword useful for?

Assume that a thread modifies the value of a shared variable, if you didn't use volatile modifier for that variable. When other threads want to read this variable's value, they don't see the updated value because they read the variable's value from the CPU's cache instead of RAM memory. This problem also known as Visibility Problem.

By declaring the shared variable volatile, all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory.

public class SharedObject {
    public volatile int sharedVariable = 0;
}

With non-volatile variables there are no guarantees about when the Java Virtual Machine (JVM) reads data from main memory into CPU caches, or writes data from CPU caches to main memory. This can cause several problems which I will explain in the following sections.


Example:

Imagine a situation in which two or more threads have access to a shared object which contains a counter variable declared like this:

public class SharedObject {
    public int counter = 0;
}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.

If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU cache back to main memory. This means, that the counter variable value in the CPU cache may not be the same as in main memory. This situation is illustrated here:

volatile

The problem with threads not seeing the latest value of a variable because it has not yet been written back to main memory by another thread, is called a "visibility" problem. The updates of one thread are not visible to other threads.

In Perl, how do I create a hash whose keys come from a given array?

Note that if typing if ( exists $hash{ key } ) isn’t too much work for you (which I prefer to use since the matter of interest is really the presence of a key rather than the truthiness of its value), then you can use the short and sweet

@hash{@key} = ();

Where do I find the current C or C++ standard documents?

The C99 and C++03 standards are available in book form from Wiley:

Plus, as already mentioned, the working draft for future standards is often available from the committee websites:

The C-201x draft is available as N1336, and the C++0x draft as N3225.

Algorithm to find Largest prime factor of a number

Not the quickest but it works!

    static bool IsPrime(long num)
    {
        long checkUpTo = (long)Math.Ceiling(Math.Sqrt(num));
        for (long i = 2; i <= checkUpTo; i++)
        {
            if (num % i == 0)
                return false;
        }
        return true;
    }

Hidden Features of C#?

OK, it may seem obvious, but I want to mention the Object.Equals method (the static one, with two arguments).

I'm pretty sure many people don't even know about it, or forget it's there, yet it can really help in some cases. For instance, when you want to compare two objects for equality, not knowing if they're null. How many times did you write something like that :

if ((x == y) || ((x != null && y != null) && x.Equals(y)))
{
    ...
}

When you can just write :

if (Object.Equals(x, y))
{
    ...
}

(Object.Equals is actually implemented exactly like in the first code sample)

MySQL LEFT JOIN Multiple Conditions

Correct answer is simply:

SELECT a.group_id
FROM a 
LEFT JOIN b ON a.group_id=b.group_id  and b.user_id = 4
where b.user_id is null
  and a.keyword like '%keyword%'

Here we are checking user_id = 4 (your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.

From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.

demo here

Why use Select Top 100 Percent?

No reason but indifference, I'd guess.

Such query strings are usually generated by a graphical query tool. The user joins a few tables, adds a filter, a sort order, and tests the results. Since the user may want to save the query as a view, the tool adds a TOP 100 PERCENT. In this case, though, the user copies the SQL into his code, parameterized the WHERE clause, and hides everything in a data access layer. Out of mind, out of sight.

IntelliJ Organize Imports

In addition to Optimize Imports and Auto Import, which were pointed out by @dave-newton and @ryan-stewart in earlier answers, go to:

  • IDEA <= 13: File menu > Settings > Code Style > Java > Imports
  • IDEA >= 14: File menu > Settings > Editor > Code Style > Java > Imports (thanks to @mathias-bader for the hint!) Settings dialog

There you can fine tune the grouping and order or imports, "Class count to use import with '*'", etc.

Note:
since IDEA 13 you can configure the project default settings from the IDEA "start page": Configure > Project defaults > Settings > .... Then every new project will have those default settings: enter image description here

How to set delay in vbscript

A lot of the answers here assume that you're running your VBScript in the Windows Scripting Host (usually wscript.exe or cscript.exe). If you're getting errors like 'Variable is undefined: "WScript"' then you're probably not.

The WScript object is only available if you're running under the Windows Scripting Host, if you're running under another script host, such as Internet Explorer's (and you might be without realising it if you're in something like an HTA) it's not automatically available.

Microsoft's Hey, Scripting Guy! Blog has an article that goes into just this topic How Can I Temporarily Pause a Script in an HTA? in which they use a VBScript setTimeout to create a timer to simulate a Sleep without needing to use CPU hogging loops, etc.

The code used is this:

<script language = "VBScript">

    Dim dtmStartTime

    Sub Test
        dtmStartTime = Now 
        idTimer = window.setTimeout("PausedSection", 5000, "VBScript")
    End Sub

    Sub PausedSection
        Msgbox dtmStartTime & vbCrLf & Now
        window.clearTimeout(idTimer)
    End Sub

</script>

<body>
    <input id=runbutton  type="button" value="Run Button" onClick="Test">
</body>

See the linked blog post for the full explanation, but essentially when the button is clicked it creates a timer that fires 5,000 milliseconds from now, and when it fires runs the VBScript sub-routine called "PausedSection" which clears the timer, and runs whatever code you want it to.

Should I use <i> tag for icons instead of <span>?

My guess: Because Twitter sees the need to support legacy browsers, otherwise they would be using the :before / :after pseudo-elements.

Legacy browsers don't support those pseudo-elements I mentioned, so they need to use an actual HTML element for the icons, and since icons don't have an 'exclusive' tag, they just went with the <i> tag, and all browsers support that tag.

They could've certainly used a <span>, just like you are (which is TOTALLY fine), but probably for the reason I mentioned above plus the ones mentioned by Quentin, is also why Bootstrap is using the <i> tag.

It's a bad practice when you use extra markup for styling reasons, that's why pseudo-elements were invented, to separate content from style... but when you see the need to support legacy browsers, sometimes you're forced to do these kind of things.

PS. The fact that icons start with an 'i' and that there's an <i> tag, is completely coincidental.

Xcode "Build and Archive" from command line

The xcodebuild tool can build and export archive products with the -exportArchive flag (as of Xcode 5). The export step was previously only possible via the Xcode Organizer UI.

First archive your app:

xcodebuild -scheme <scheme name> archive

Given $ARCHIVE_PATH (the path to the .xcarchive file), export the app from the archive with one of the following:

iOS .ipa file:

xcodebuild -exportArchive -exportFormat ipa -archivePath "$ARCHIVE_PATH" -exportPath "myApp.ipa" -exportProvisioningProfile "My App Provisioning profile"

Mac .app file:

xcodebuild -exportArchive -exportFormat app -archivePath "$ARCHIVE_PATH" -exportPath "myApp.app" -exportSigningIdentity "Developer ID Application: My Software Company"

In both commands the -exportProvisioningProfile and -exportSigningIdentity arguments are optional. man xcodebuild for details on the semantics. In these examples, the provisioning profile for the iOS build specified an AdHoc distribution provisioning profile, and the signing identity for the Mac app specified a Developer ID for export as a 3rd party application (i.e. not distributed via the Mac App Store).

JavaScript split String with white space

In case you're sure you have only one space between two words, you can use this one

str.replace(/\s+/g, ' ').split(' ')

so you replace one space by two, the split by space

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is a javascript class that detects IE10, IE11 and Edge.
Navigator object is injected for testing purposes.

var DeviceHelper = function (_navigator) {
    this.navigator = _navigator || navigator;
};
DeviceHelper.prototype.isIE = function() {
    if(!this.navigator.userAgent) {
        return false;
    }

    var IE10 = Boolean(this.navigator.userAgent.match(/(MSIE)/i)),
        IE11 = Boolean(this.navigator.userAgent.match(/(Trident)/i));
    return IE10 || IE11;
};

DeviceHelper.prototype.isEdge = function() {
    return !!this.navigator.userAgent && this.navigator.userAgent.indexOf("Edge") > -1;
};

DeviceHelper.prototype.isMicrosoftBrowser = function() {
    return this.isEdge() || this.isIE();
};

How to get the current location in Google Maps Android API v2?

The Google Maps API location now works, even has listeners, you can do it using that, for example:

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        mMarker = mMap.addMarker(new MarkerOptions().position(loc));
        if(mMap != null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    }
};

and then set the listener for the map:

mMap.setOnMyLocationChangeListener(myLocationChangeListener);

This will get called when the map first finds the location.

No need for LocationService or LocationManager at all.

OnMyLocationChangeListener interface is deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide.

How to use the CSV MIME-type?

With Internet Explorer you often have to specify the Pragma: public header as well for the download to function properly..

header('Pragma: public');

Just my 2 cents..

Array length in angularjs returns undefined

var leg= $scope.name.length;
$log.info(leg);

running a command as a super user from a python script

Try:

subprocess.call(['sudo', 'apach2ctl', 'restart'])

The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.

If you don't define them, then it grabs sys.stdout, etc...

jQuery count child elements

var length = $('#selected ul').children('li').length
// or the same:
var length = $('#selected ul > li').length

You probably could also omit li in the children's selector.

See .length.

nodejs npm global config missing on windows

Isn't this the path you are looking for?

C:\Program Files\nodejs\node_modules\npm\npmrc

I know that npm outputs that , but the global folder is the folder where node.js is installed and all the modules are.

How can I view the allocation unit size of a NTFS partition in Vista?

start > run > MSINFO32

goto components

goto storage

goto disk

on the right look for Bytes/Sector

How to compute the similarity between two text documents?

For Syntactic Similarity There can be 3 easy ways of detecting similarity.

  • Word2Vec
  • Glove
  • Tfidf or countvectorizer

For Semantic Similarity One can use BERT Embedding and try a different word pooling strategies to get document embedding and then apply cosine similarity on document embedding.

An advanced methodology can use BERT SCORE to get similarity. BERT SCORE

Research Paper Link: https://arxiv.org/abs/1904.09675

What's the difference between Docker Compose vs. Dockerfile

Dockerfile is a file that contains text commands to assemble an image.

Docker compose is used to run a multi-container environment.

In your specific scenario, if you have multiple services for each technology you mentioned (service 1 using reddis, service 2 using rabbit mq etc), then you can have a Dockerfile for each of the services and a common docker-compose.yml to run all the "Dockerfile" as containers.

If you want them all in a single service, docker-compose will be a viable option.

trying to align html button at the center of the my page

try this it is quite simple and give you cant make changes to your .css file this should work

<p align="center">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%"> mybuttonname</button>
</p>

What is the advantage of using REST instead of non-REST HTTP?

I would suggest everybody, who is looking for an answer to this question, go through this "slideshow".

I couldn't understand what REST is and why it is so cool, its pros and cons, differences from SOAP - but this slideshow was so brilliant and easy to understand, so it is much more clear to me now, than before.

jquery: get elements by class name and add css to each of them

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

Can you use a trailing comma in a JSON object?

It is not recommended, but you can still do something like this to parse it.

_x000D_
_x000D_
jsonStr = '[0,1,2,3,4,5,]';_x000D_
let data;_x000D_
eval('data = ' + jsonStr);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

Creating runnable JAR with Gradle

An executable jar file is just a jar file containing a Main-Class entry in its manifest. So you just need to configure the jar task in order to add this entry in its manifest:

jar {
    manifest {
        attributes 'Main-Class': 'com.foo.bar.MainClass'
    }
}

You might also need to add classpath entries in the manifest, but that would be done the same way.

See http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Replace tabs with spaces in vim

first search for tabs in your file : /^I :set expandtab :retab

will work.

MySQL FULL JOIN?

Full join in mysql :(left union right) or (right unoin left)

 SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    left JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

    Union

    SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    Right JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

Why doesn't Dijkstra's algorithm work for negative weight edges?

Dijkstra's Algorithm assumes that all edges are positive weighted and this assumption helps the algorithm run faster ( O(V^2) ) than others which take into account the possibility of negative edges (e.g bellman ford's algorithm with complexity of O(V^3)).

This algorithm wont give the correct result in the following case where A is the source vertex:

enter image description here

Also, Dijkstra's Algorithm may sometimes give correct solution even if there are negative edges. Following is an example of such a case:

enter image description here

It will never detect a negative cycle and always produce a result which will always be incorrect if a negative weight cycle is reachable from the source, as in such a case there exists no shortest path in the graph from the source vertex.

Deadly CORS when http://localhost is the origin

The real problem is that if we set -Allow- for all request (OPTIONS & POST), Chrome will cancel it. The following code works for me with POST to LocalHost with Chrome

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
} 
?>

getting file size in javascript

You could probably try this to get file sizes in kB and MB Until the file size in bytes would be upto 7 digits, the outcome would be in kbs. 7 seems to be the magic number here. After which, if the bytes would have 7 to 10 digits, we would have to divide it by 10**3(n) where n is the appending action . This pattern would repeat for every 3 digits added.

let fileSize = myInp.files[0].size.toString();

if(fileSize.length < 7) return `${Math.round(+fileSize/1024).toFixed(2)}kb`
    return `${(Math.round(+fileSize/1024)/1000).toFixed(2)}MB`

Extract digits from string - StringUtils Java

I've created a JUnit Test class(as a additional knowledge/info) for the same issue. Hope you'll be finding this helpful.

   public class StringHelper {
    //Separate words from String which has gigits
        public String drawDigitsFromString(String strValue){
            String str = strValue.trim();
            String digits="";
            for (int i = 0; i < str.length(); i++) {
                char chrs = str.charAt(i);              
                if (Character.isDigit(chrs))
                    digits = digits+chrs;
            }
            return digits;
        }
    }

And JUnit Test case is:

 public class StringHelperTest {
    StringHelper helper;

        @Before
        public void before(){
            helper = new StringHelper();
        }

        @Test
    public void testDrawDigitsFromString(){
        assertEquals("187111", helper.drawDigitsFromString("TCS187TCS111"));
    }
 }

Why does flexbox stretch my image rather than retaining aspect ratio?

Adding margin to align images:

Since we wanted the image to be left-aligned, we added:

img {
  margin-right: auto;
}

Similarly for image to be right-aligned, we can add margin-right: auto;. The snippet shows a demo for both types of alignment.

Good Luck...

_x000D_
_x000D_
div {_x000D_
  display:flex; _x000D_
  flex-direction:column;_x000D_
  border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  text-align: center;_x000D_
}_x000D_
hr {_x000D_
  border: 1px black solid;_x000D_
  width: 100%_x000D_
}_x000D_
img.one {_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
  <h1>Flex Box</h1>_x000D_
  _x000D_
  <hr />_x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="one" _x000D_
  />_x000D_
  _x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="two" _x000D_
  />_x000D_
  _x000D_
  <hr />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

Try/catch does not seem to have an effect

Adding "-EA Stop" solved this for me.

Could not open a connection to your authentication agent

I faced the same problem for Linux, and here is what I did:

Basically, the command ssh-agent starts the agent, but it doesn't really set the environment variables for it to run. It just outputs those variables to the shell.

You need to:

eval `ssh-agent`

and then do ssh-add. See Could not open a connection to your authentication agent.

How to get the innerHTML of selectable jquery element?

Use .val() instead of .innerHTML for getting value of selected option

Use .text() for getting text of selected option

Thanks for correcting :)

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

How to list imported modules?

let say you've imported math and re:

>>import math,re

now to see the same use

>>print(dir())

If you run it before the import and after the import, one can see the difference.

How to auto-size an iFrame?

On any other element, I would use the scrollHeight of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.

Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight:

function setHeight() {
    parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}

And attach that to run with the iframe-body's onLoad event.

How to get maximum value from the Collection (for example ArrayList)?

In Java8

arrayList.stream()
         .reduce(Integer::max)
         .get()

Application Crashes With "Internal Error In The .NET Runtime"

For those arriving here from google, I've eventually come across this SO question, and this specific answer solved my problem. I've contacted Microsoft for the hotfix through the live chat on support.microsoft.com and they sent me a link to the hotfix by email.

How do I remove leading whitespace in Python?

The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning:

>>> '     hello world!'.lstrip()
'hello world!'

Edit

As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string, lstrip(' ') should be used:

>>> '   hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'

Related question:

svn: E155004: ..(path of resource).. is already locked

For me it's worked with svn cleanup in Eclipse.

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

ImportError: No module named 'django.core.urlresolvers'

In my case the problem was that I had outdated django-stronghold installed (0.2.9). And even though in the code I had:

from django.urls import reverse

I still encountered the error. After I upgraded the version to django-stronghold==0.4.0 the problem disappeard.

Thymeleaf using path variables to th:href

I think you can try this:

<a th:href="${'/category/edit/' + {category.id}}">view</a>

Or if you have "idCategory" this:

<a th:href="${'/category/edit/' + {category.idCategory}}">view</a>

Formatting text in a TextBlock

Check out this example from Charles Petzolds Bool Application = Code + markup

//----------------------------------------------
// FormatTheText.cs (c) 2006 by Charles Petzold
//----------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Petzold.FormatTheText
{
    class FormatTheText : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheText());
        }
        public FormatTheText()
        {
            Title = "Format the Text";

            TextBlock txt = new TextBlock();
            txt.FontSize = 32; // 24 points
            txt.Inlines.Add("This is some ");
            txt.Inlines.Add(new Italic(new Run("italic")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Run("bold")));
            txt.Inlines.Add(" text, and let's cap it off with some ");
            txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
            txt.Inlines.Add(" text.");
            txt.TextWrapping = TextWrapping.Wrap;

            Content = txt;
        }
    }
}

How to get the html of a div on another page with jQuery ajax?

If you are looking for content from different domain this will do the trick:

$.ajax({
    url:'http://www.corsproxy.com/' +
        'en.wikipedia.org/wiki/Briarcliff_Manor,_New_York',
        type:'GET',
        success: function(data){
           $('#content').html($(data).find('#firstHeading').html());
        }
});

Git Push ERROR: Repository not found

I was getting the same error coz I change my github user name, then I do this:

git remote -v

then:

git remote set-url newname newurl 
git push -u origin master

this time I was able to push to the repository. I hope this helps.

Get device token for push notification

In order to get the device token use following code but you can get the device token only using physical device. If you have mandatory to send the device token then while using simulator you can put the below condition.

  if(!(TARGET_IPHONE_SIMULATOR))
    {
        [infoDict setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"DeviceToken"] forKey:@"device_id"];
    }
    else
    {
        [infoDict setValue:@"e79c2b66222a956ce04625b22e3cad3a63e91f34b1a21213a458fadb2b459385" forKey:@"device_id"];
    }



- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);
    NSString * deviceTokenString = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""]   stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSLog(@"the generated device token string is : %@",deviceTokenString);
    [[NSUserDefaults standardUserDefaults] setObject:deviceTokenString forKey:@"DeviceToken"];
}

Make copy of an array

For a null-safe copy of an array, you can also use an optional with the Object.clone() method provided in this answer.

int[] arrayToCopy = {1, 2, 3};
int[] copiedArray = Optional.ofNullable(arrayToCopy).map(int[]::clone).orElse(null);

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Inline JavaScript onclick function

This should work

 <a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>

You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block

syntax error when using command line in python

Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.

Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.

Parsing arguments to a Java command line program

Ok, thanks to Charles Goodwin for the concept. Here is the answer:

import java.util.*;
public class Test {

  public static void main(String[] args) {
     List<String> argsList  = new ArrayList<String>();  
     List<String> optsList  = new ArrayList<String>();
     List<String> doubleOptsList  = new ArrayList<String>();
     for (int i=0; i < args.length; i++) {
         switch (args[i].charAt(0)) {
         case '-':
             if (args[i].charAt(1) == '-') {
                 int len = 0;
                 String argstring = args[i].toString();
                 len = argstring.length();
                 System.out.println("Found double dash with command " +
                     argstring.substring(2, len) );
                 doubleOptsList.add(argstring.substring(2, len));           
             } else {
                 System.out.println("Found dash with command " + 
                   args[i].charAt(1) + " and value " + args[i+1] );   
                 i= i+1;
                 optsList.add(args[i]);      
             }           
         break;         
         default:            
         System.out.println("Add a default arg." );
         argsList.add(args[i]);
         break;         
         }     
     } 
  } 

}

Re-assign host access permission to MySQL user

I received the same error with RENAME USER and GRANTS aren't covered by the currently accepted solution:

The most reliable way seems to be to run SHOW GRANTS for the old user, find/replace what you want to change regarding the user's name and/or host and run them and then finally DROP USER the old user. Not forgetting to run FLUSH PRIVILEGES (best to run this after adding the new users' grants, test the new user, then drop the old user and flush again for good measure).

    > SHOW GRANTS FOR 'olduser'@'oldhost';
    +-----------------------------------------------------------------------------------+
    | Grants for olduser@oldhost                                                        |
    +-----------------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'olduser'@'oldhost' IDENTIFIED BY PASSWORD '*PASSHASH'      |
    | GRANT SELECT ON `db`.* TO 'olduser'@'oldhost'                                     |
    +-----------------------------------------------------------------------------------+
    2 rows in set (0.000 sec)

    > GRANT USAGE ON *.* TO 'newuser'@'newhost' IDENTIFIED BY PASSWORD '*SAME_PASSHASH';
    Query OK, 0 rows affected (0.006 sec)

    > GRANT SELECT ON `db`.* TO 'newuser'@'newhost';
    Query OK, 0 rows affected (0.007 sec)

    > DROP USER 'olduser'@'oldhost';
    Query OK, 0 rows affected (0.016 sec)

How do you force a makefile to rebuild a target

If I recall correctly, 'make' uses timestamps (file modification time) to determine whether or not a target is up to date. A common way to force a re-build is to update that timestamp, using the 'touch' command. You could try invoking 'touch' in your makefile to update the timestamp of one of the targets (perhaps one of those sub-makefiles), which might force Make to execute that command.

How do I extract data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

What is the best JavaScript code to create an img element

you could simply do:

var newImage = new Image();
newImage.src = "someImg.jpg";

if(document.images)
{
  document.images.yourImageElementName.src = newImage.src;
}

Simple :)

Change Bootstrap tooltip color

If you want to use jQuery you can try this:

$('[data-toggle="tooltip"]').on('shown.bs.tooltip', function(){
    $('.tooltip.bottom .tooltip-arrow').css('border-bottom-color', 'red');
    $('.tooltip-inner').css('background-color', 'red');
});

DB2 Date format

SELECT VARCHAR_FORMAT(CURRENT TIMESTAMP, 'YYYYMMDD')
FROM SYSIBM.SYSDUMMY1

Should work on both Mainframe and Linux/Unix/Windows DB2. Info Center entry for VARCHAR_FORMAT().

Call Javascript onchange event by programmatically changing textbox value

You're population is from the server-side. Using the registerclientscript will put the script at the beginning of the form.. you'll want to use RegisterStartupScript(Block) to have the script placed at the end of the page in question.

The former tries to run the script before the text area exists in the dom, the latter will run the script after that element in the page is created.

How to dump a table to console?

--~ print a table
function printTable(list, i)

    local listString = ''
--~ begin of the list so write the {
    if not i then
        listString = listString .. '{'
    end

    i = i or 1
    local element = list[i]

--~ it may be the end of the list
    if not element then
        return listString .. '}'
    end
--~ if the element is a list too call it recursively
    if(type(element) == 'table') then
        listString = listString .. printTable(element)
    else
        listString = listString .. element
    end

    return listString .. ', ' .. printTable(list, i + 1)

end


local table = {1, 2, 3, 4, 5, {'a', 'b'}, {'G', 'F'}}
print(printTable(table))

Hi man, I wrote a siple code that do this in pure Lua, it has a bug (write a coma after the last element of the list) but how i wrote it quickly as a prototype I will let it to you adapt it to your needs.

How to check empty DataTable

This is an old question, but because this might help a lot of c# coders out there, there is an easy way to solve this right now as follows:

if ((dataTableName?.Rows?.Count ?? 0) > 0)

Closing WebSocket correctly (HTML5, Javascript)

please use this

var uri = "ws://localhost:5000/ws";
var socket = new WebSocket(uri);
socket.onclose = function (e){
    console.log(connection closed);
};
window.addEventListener("unload", function () {
    if(socket.readyState == WebSocket.OPEN)
        socket.close();
});

Close browser doesn't trigger websocket close event. You must call socket.close() manually.

The listener supports no services

you need to reconfigure your tnsnames.ora so that it can point to your hostname after that listener will be able to pick the new hostname. after which check the status of your listener lsnrctl status and start listener lsnrctl start then register your listener. Alter system register

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

The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data

Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from

data = data.decode(encoding)

to

data = data.decode("ISO-8859-1")

solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.

Very simple C# CSV reader

If there is only ever one line then do something like this:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        String[] values = File.ReadAllText(@"d:\test.csv").Split(',');
    }
}

Remove gutter space for a specific div only

Simplest way to remove padding and margin is with simple css.

<div class="header" style="margin:0px;padding:0px;">
.....
.....
.....
</div>

Why can't decimal numbers be represented exactly in binary?

The high scoring answer above nailed it.

First you were mixing base 2 and base 10 in your question, then when you put a number on the right side that is not divisible into the base you get problems. Like 1/3 in decimal because 3 doesnt go into a power of 10 or 1/5 in binary which doesnt go into a power of 2.

Another comment though NEVER use equal with floating point numbers, period. Even if it is an exact representation there are some numbers in some floating point systems that can be accurately represented in more than one way (IEEE is bad about this, it is a horrible floating point spec to start with, so expect headaches). No different here 1/3 is not EQUAL to the number on your calculator 0.3333333, no matter how many 3's there are to the right of the decimal point. It is or can be close enough but is not equal. so you would expect something like 2*1/3 to not equal 2/3 depending on the rounding. Never use equal with floating point.

Variable is accessed within inner class. Needs to be declared final

The error says it all, change:

ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);

to

final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);

Assembly - JG/JNLE/JL/JNGE after CMP

When you do a cmp a,b, the flags are set as if you had calculated a - b.

Then the jmp-type instructions check those flags to see if the jump should be made.

In other words, the first block of code you have (with my comments added):

cmp al,dl     ; set flags based on the comparison
jg label1     ; then jump based on the flags

would jump to label1 if and only if al was greater than dl.

You're probably better off thinking of it as al > dl but the two choices you have there are mathematically equivalent:

al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0       (cancel the terms on the right hand side)

You need to be careful when using jg inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.

See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JO     | Jump if overflow             |             | OF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNO    | Jump if not overflow         |             | OF = 0             |
+--------+------------------------------+-------------+--------------------+
| JS     | Jump if sign                 |             | SF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNS    | Jump if not sign             |             | SF = 0             |
+--------+------------------------------+-------------+--------------------+
| JE/    | Jump if equal                |             | ZF = 1             |
| JZ     | Jump if zero                 |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNE/   | Jump if not equal            |             | ZF = 0             |
| JNZ    | Jump if not zero             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JP/    | Jump if parity               |             | PF = 1             |
| JPE    | Jump if parity even          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNP/   | Jump if no parity            |             | PF = 0             |
| JPO    | Jump if parity odd           |             |                    |
+--------+------------------------------+-------------+--------------------+
| JCXZ/  | Jump if CX is zero           |             | CX = 0             |
| JECXZ  | Jump if ECX is zero          |             | ECX = 0            |
+--------+------------------------------+-------------+--------------------+

Then the unsigned ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JB/    | Jump if below                | unsigned    | CF = 1             |
| JNAE/  | Jump if not above or equal   |             |                    |
| JC     | Jump if carry                |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNB/   | Jump if not below            | unsigned    | CF = 0             |
| JAE/   | Jump if above or equal       |             |                    |
| JNC    | Jump if not carry            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JBE/   | Jump if below or equal       | unsigned    | CF = 1 or ZF = 1   |
| JNA    | Jump if not above            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JA/    | Jump if above                | unsigned    | CF = 0 and ZF = 0  |
| JNBE   | Jump if not below or equal   |             |                    |
+--------+------------------------------+-------------+--------------------+

And, finally, the signed ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JL/    | Jump if less                 | signed      | SF <> OF           |
| JNGE   | Jump if not greater or equal |             |                    |
+--------+------------------------------+-------------+--------------------+
| JGE/   | Jump if greater or equal     | signed      | SF = OF            |
| JNL    | Jump if not less             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JLE/   | Jump if less or equal        | signed      | ZF = 1 or SF <> OF |
| JNG    | Jump if not greater          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JG/    | Jump if greater              | signed      | ZF = 0 and SF = OF |
| JNLE   | Jump if not less or equal    |             |                    |
+--------+------------------------------+-------------+--------------------+

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

LISTAGG function: "result of string concatenation is too long"

SELECT RTRIM(XMLAGG(XMLELEMENT(E,colname,',').EXTRACT('//text()') ORDER BY colname).GetClobVal(),',') AS LIST
FROM tablename;

This will return a clob value, so no limit on rows.

ElasticSearch - Return Unique Values

To had to distinct by two fields (derivative_id & vehicle_type) and to sort by cheapest car. Had to nest aggs.

GET /cars/_search
{
  "size": 0,
  "aggs": {
    "distinct_by_derivative_id": {
      "terms": { 
        "field": "derivative_id"
      },
      "aggs": {
        "vehicle_type": {
          "terms": {
            "field": "vehicle_type"
          },
          "aggs": {
            "cheapest_vehicle": {
              "top_hits": {
                "sort": [
                  { "rental": { "order": "asc" } }
                ],
                "_source": { "includes": [ "manufacturer_name",
                  "rental",
                  "vehicle_type" 
                  ]
                },
                "size": 1
              }
            }
          }
        }
      }
    }
  }
}

Result:

{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 8,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "distinct_by_derivative_id" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "04",
          "doc_count" : 3,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 2,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 2,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "8",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Renault",
                          "rental" : 89.99
                        },
                        "sort" : [
                          89.99
                        ]
                      }
                    ]
                  }
                }
              },
              {
                "key" : "LCV",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "7",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "LCV",
                          "manufacturer_name" : "Ford",
                          "rental" : 99.99
                        },
                        "sort" : [
                          99.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "01",
          "doc_count" : 2,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "1",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Ford",
                          "rental" : 599.99
                        },
                        "sort" : [
                          599.99
                        ]
                      }
                    ]
                  }
                }
              },
              {
                "key" : "LCV",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "2",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "LCV",
                          "manufacturer_name" : "Ford",
                          "rental" : 599.99
                        },
                        "sort" : [
                          599.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "02",
          "doc_count" : 2,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 2,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 2,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "4",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Audi",
                          "rental" : 499.99
                        },
                        "sort" : [
                          499.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "03",
          "doc_count" : 1,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "5",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Audi",
                          "rental" : 399.99
                        },
                        "sort" : [
                          399.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Error 1022 - Can't write; duplicate key in table

I had this problem when creating a new table. It turns out the Foreign Key name I gave was already in use. Renaming the key fixed it.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

How to disable mouse right click on a web page?

You can use the oncontextmenu event for doing this.

But if the user turns off javascript then you won't be able to handle this.

window.oncontextmenu = function () {
   return false;
}

will disable right click menu.

For vs. while in C programming?

For loops (at least considering C99) are superior to while loops because they limit the scope of the incremented variable(s).

Do while loops are useful when the condition is dependant on some inputs. They are the most seldom used of the three loop types.

How do I make the method return type generic?

Based on the same idea as Super Type Tokens, you could create a typed id to use instead of a string:

public abstract class TypedID<T extends Animal> {
  public final Type type;
  public final String id;

  protected TypedID(String id) {
    this.id = id;
    Type superclass = getClass().getGenericSuperclass();
    if (superclass instanceof Class) {
      throw new RuntimeException("Missing type parameter.");
    }
    this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
  }
}

But I think this may defeat the purpose, since you now need to create new id objects for each string and hold on to them (or reconstruct them with the correct type information).

Mouse jerry = new Mouse();
TypedID<Dog> spike = new TypedID<Dog>("spike") {};
TypedID<Duck> quacker = new TypedID<Duck>("quacker") {};

jerry.addFriend(spike, new Dog());
jerry.addFriend(quacker, new Duck());

But you can now use the class in the way you originally wanted, without the casts.

jerry.callFriend(spike).bark();
jerry.callFriend(quacker).quack();

This is just hiding the type parameter inside the id, although it does mean you can retrieve the type from the identifier later if you wish.

You'd need to implement the comparison and hashing methods of TypedID too if you want to be able to compare two identical instances of an id.

Installing SciPy and NumPy using pip

On windows python 3.5, I managed to install scipy by using conda not pip:

conda install scipy

How to convert an address into a Google Maps Link (NOT MAP)

The C# Replace method usually works for me:

foo = "http://maps.google.com/?q=" + address.Text.Replace(" ","+");

Laravel Request::all() Should Not Be Called Statically

I thought it would be useful for future visitors to provide a bit of an explanation on what is happening here.

The Illuminate\Http\Request class

Laravel's Illuminate\Http\Request class has a method named all (in fact the all method is defined in a trait that the Request class uses, called Illuminate\Http\Concerns\InteractsWithInput). The signature of the all method at the time of writing looks like this:

public function all($keys = null)

This method is not defined as static and so when you try to call the method in a static context, i.e. Illuminate\Http\Request::all() you will get the error displayed in OP's question. The all method is an instance method and deals with information that is present in an instance of the Request class, so calling it in this way makes no sense.

Facades

A facade in Laravel provides developers with a convenient way of accessing objects in the IoC container, and calling methods on those objects. A developer can call a method "statically" on a facade like Request::all(), but the actual method call on the real Illuminate\Http\Request object is not static.

A facade works like a proxy - it refers to an object in the IoC container and passes the static method call onto that object (non-statically). For instance, take the Illuminate\Support\Facades\Request facade, this is what it looks like:

class Request extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'request';
    }
}

Under the hood, the base Illuminate\Support\Facades\Facade class uses some PHP magic, namely the __callStatic method to:

  • Listen for a static method call, in this case all with no parameters
  • Grab the underlying object from the IoC container using the key returned by getFacadeAccessor, in this case a Illuminate\Http\Request object
  • Dynamically call the method that it received statically on the object it has retrieved, in this case all is called non-statically on an instance of Illuminate\Http\Request.

This is why, as @patricus pointed out in his answer above, by changing the use/import statement to refer to the facade, the error is no longer there, because as far as PHP is concerned, all has been correctly called on an instance of Illuminate\Http\Request.

Aliasing

Aliasing is another feature that Laravel provides for convenience. It works by effectively creating alias classes that point to facades in the root namespace. If you take a look at your config/app.php file, under the aliases key, you will find a long list of mappings of strings to facade classes. For example:

'aliases' => [

    'App' => Illuminate\Support\Facades\App::class,
    'Artisan' => Illuminate\Support\Facades\Artisan::class,
    'Auth' => Illuminate\Support\Facades\Auth::class,
    // ...
    'Request' => Illuminate\Support\Facades\Request::class,

Laravel creates these alias classes for you, based on your configuration and this allows you to utilise classes available in the root namespace (as referred to by the string keys of the aliases config) as if you're using the facade itself:

use Request:

class YourController extends Controller
{
    public function yourMethod()
    {
        $input = Request::all();

        // ...
    }
}

A note on dependency injection

While facades and aliasing are still provided in Laravel, it is possible and usually encouraged to go down the dependency injection route. For example, using constructor injection to achieve the same result:

use Illuminate\Http\Request;

class YourController extends Controller
{
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function yourMethod()
    {
        $input = $this->request->all();

        // ...
    }
}

There are a number of benefits to this approach but in my personal opinion the greatest pro for dependency injection is that it makes your code way easier to test. By declaring the dependencies of your classes as constructor or method arguments, it becomes very easy to mock out those dependencies and unit test your class in isolation.

Show all current locks from get_lock

Starting with MySQL 5.7, the performance schema exposes all metadata locks, including locks related to the GET_LOCK() function.

See http://dev.mysql.com/doc/refman/5.7/en/metadata-locks-table.html

If (Array.Length == 0)

Since .Net >= 5.0 the best way is to use Any:

if(!array.Any()) {
   //now you sure it's empty
}

For nullable arrays:

if(!(array?.Any() == true)) {
   //now you sure it's null or empty
}

Highlight Bash/shell code in Markdown files

It depends on the Markdown rendering engine and the Markdown flavour. There is no standard for this. If you mean GitHub flavoured Markdown for example, shell should work fine. Aliases are sh, bash or zsh. You can find the list of available syntax lexers here.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

First step in such case is to check whether the GC is allowed to unload classes from PermGen. The standard JVM is rather conservative in this regard – classes are born to live forever. So once loaded, classes stay in memory even if no code is using them anymore. This can become a problem when the application creates lots of classes dynamically and the generated classes are not needed for longer periods. In such a case, allowing the JVM to unload class definitions can be helpful. This can be achieved by adding just one configuration parameter to your startup scripts:

-XX:+CMSClassUnloadingEnabled

By default this is set to false and so to enable this you need to explicitly set the following option in Java options. If you enable CMSClassUnloadingEnabled, GC will sweep PermGen too and remove classes which are no longer used. Keep in mind that this option will work only when UseConcMarkSweepGC is also enabled using the below option. So when running ParallelGC or, God forbid, Serial GC, make sure you have set your GC to CMS by specifying:

-XX:+UseConcMarkSweepGC

Capturing URL parameters in request.GET

def some_view(request, *args, **kwargs):
    if kwargs.get('q', None):
        # Do something here ..

Entity framework code-first null foreign key

I have the same problem now , I have foreign key and i need put it as nullable, to solve this problem you should put

    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);

in DBContext class I am sorry for answer you very late :)

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Go to Control Panel -> Programs -> Programs and features

    Step 1 - Programs and features

  2. Go to Windows Features and disable Internet Explorer 11

    Step 2 - Windows Features

    Step 3 - Uncheck Internet Explorer 11

  3. Then click on Display installed updates

    Step 4 - Display installed updates

  4. Search for Internet explorer

  5. Right-click on Internet Explorer 11 -> Uninstall

    Step 5 - Uninstall Internet Explorer 11

  6. Do the same with Internet Explorer 10

  7. Restart your computer
  8. Install Internet Explorer 10 here (old broken link)

I think it will be okay.

Find the number of downloads for a particular app in apple appstore

I think developers can do this for their own apps via iTunes Connect but this doesn't help you if you are looking for stats on other peoples apps.

148Apps also have some aggregate AppStore metrics on their web site that could be useful to you but, again, doesn't really give a low-level breakdown of numbers.

You could also scrape some stats from the RSS feeds generated by the iTunes Store RSS Generator but, again, this just gets currently popular apps rather than actual download numbers.

ng-options with simple array init

If you setup your select like the following:

<select ng-model="myselect" ng-options="b for b in options track by b"></select>

you will get:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

working fiddle: http://jsfiddle.net/x8kCZ/15/

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Because this is the first result on Google. I want to share with you a great Talk by Dave Smith on Youtube: Mastering the Android Touch System and the slides are available here. It gave me a good deep understanding about the Android Touch System:

How the Activity handles touch:

  • Activity.dispatchTouchEvent()
    • Always first to be called
    • Sends event to root view attached to Window
    • onTouchEvent()
      • Called if no views consume the event
      • Always last to be called

How the View handles touch:

  • View.dispatchTouchEvent()
    • Sends event to listener first, if exists
      • View.OnTouchListener.onTouch()
    • If not consumed, processes the touch itself
      • View.onTouchEvent()

How a ViewGroup handles touch:

  • ViewGroup.dispatchTouchEvent()
    • onInterceptTouchEvent()
      • Check if it should supersede children
      • Passes ACTION_CANCEL to active child
      • If it returns true once, the ViewGroup consumes all subsequent events
    • For each child view (in reverse order they were added)
      • If touch is relevant (inside view), child.dispatchTouchEvent()
      • If it is not handled by a previous, dispatch to next view
    • If no children handles the event, the listener gets a chance
      • OnTouchListener.onTouch()
    • If there is no listener, or its not handled
      • onTouchEvent()
  • Intercepted events jump over the child step

He also provides example code of custom touch on github.com/devunwired/.

Answer: Basically the dispatchTouchEvent() is called on every View layer to determine if a View is interested in an ongoing gesture. In a ViewGroup the ViewGroup has the ability to steal the touch events in his dispatchTouchEvent()-method, before it would call dispatchTouchEvent() on the children. The ViewGroup would only stop the dispatching if the ViewGroup onInterceptTouchEvent()-method returns true. The difference is that dispatchTouchEvent()is dispatching MotionEvents and onInterceptTouchEvent tells if it should intercept (not dispatching the MotionEvent to children) or not (dispatching to children).

You could imagine the code of a ViewGroup doing more-or-less this (very simplified):

public boolean dispatchTouchEvent(MotionEvent ev) {
    if(!onInterceptTouchEvent()){
        for(View child : children){
            if(child.dispatchTouchEvent(ev))
                return true;
        }
    }
    return super.dispatchTouchEvent(ev);
}

How to Call Controller Actions using JQuery in ASP.NET MVC

You can easily call any controller's action using jQuery AJAX method like this:

Note in this example my controller name is Student

Controller Action

 public ActionResult Test()
 {
     return View();
 }

In Any View of this above controller you can call the Test() action like this:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "@Url.Action("Test", "Student")",
            success: function (result, status, xhr) {
                alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
            },
            error: function (xhr, status, error) {
                alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    });
</script>

How to create two columns on a web page?

I found a real cool Grid which I also use for columns. Check it out Simple Grid. Wich this CSS you can simply use:

<div class="grid">
    <div class="col-1-2">
       <div class="content">
           <p>...insert content left side...</p>
       </div>
    </div>
    <div class="col-1-2">
       <div class="content">
           <p>...insert content right side...</p>
       </div>
    </div>
</div>

I use it for all my projects.

Computed / calculated / virtual / derived columns in PostgreSQL

Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.

STORED generated columns are introduced with Postgres 12. Trivial example:

CREATE TABLE tbl (
  int1    int
, int2    int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);

db<>fiddle here

VIRTUAL generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .

Related:


Until then, you can emulate VIRTUAL generated columns with a function using attribute notation (tbl.col) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:

The expression (looking like a column) is not included in a SELECT * FROM tbl, though. You always have to list it explicitly.

Can also be supported with a matching expression index - provided the function is IMMUTABLE. Like:

CREATE FUNCTION col(tbl) ... AS ...  -- your computed expression here
CREATE INDEX ON tbl(col(tbl));

Alternatives

Alternatively, you can implement similar functionality with a VIEW, optionally coupled with expression indexes. Then SELECT * can include the generated column.

"Persisted" (STORED) computed columns can be implemented with triggers in a functionally identical way.

Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

Your root account, and this statement applies to any account, may only have been added with localhost access (which is recommended).

You can check this with:

SELECT host FROM mysql.user WHERE User = 'root';

If you only see results with localhost and 127.0.0.1, you cannot connect from an external source. If you see other IP addresses, but not the one you're connecting from - that's also an indication.

You will need to add the IP address of each system that you want to grant access to, and then grant privileges:

CREATE USER 'root'@'ip_address' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'ip_address';

If you see %, well then, there's another problem altogether as that is "any remote source". If however you do want any/all systems to connect via root, use the % wildcard to grant access:

CREATE USER 'root'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

Finally, reload the permissions, and you should be able to have remote access:

FLUSH PRIVILEGES;

How to set the JDK Netbeans runs on?

All the other answers have described how to explicitly specify the location of the java platform, which is fine if you really want to use a specific version of java. However, if you just want to use the most up-to-date version of jdk, and you have that installed in a "normal" place for your operating system, then the best solution is to NOT specify a jdk location. Instead, let the Netbeans launcher search for jdk every time you start it up.

To do this, do not specify jdkhome on the command line, and comment out the line setting netbeans_jdkhome variable in any netbeans.conf files. (See other answers for where to look for these files.)

If you do this, when you install a new version of java, your netbeans will automagically use it. In most cases, that's probably exactly what you want.

DateTimePicker: pick both date and time

Go to the Properties of your dateTimePickerin Visual Studio and set Format to Custom. Under CustomFormat enter your format. In my case I used MMMMdd, yyyy | hh:mm

enter image description here
dateTimePickerProperties

How do I do a multi-line string in node.js?

Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.

CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.

I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.

If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.

Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".

Uninstalling an MSI file from the command line without using msiexec

Short answer: you can't. Use MSIEXEC /x

Long answer: When you run the MSI file directly at the command line, all that's happening is that it runs MSIEXEC for you. This association is stored in the registry. You can see a list of associations by (in Windows Explorer) going to Tools / Folder Options / File Types.

For example, you can run a .DOC file from the command line, and WordPad or WinWord will open it for you.

If you look in the registry under HKEY_CLASSES_ROOT\.msi, you'll see that .MSI files are associated with the ProgID "Msi.Package". If you look in HKEY_CLASSES_ROOT\Msi.Package\shell\Open\command, you'll see the command line that Windows actually uses when you "run" a .MSI file.

Find unused code

It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.

One great tool come to mind:

NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).

Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

How to deal with SettingWithCopyWarning in Pandas

Followup beginner question / remark

Maybe a clarification for other beginners like me (I come from R which seems to work a bit differently under the hood). The following harmless-looking and functional code kept producing the SettingWithCopy warning, and I couldn't figure out why. I had both read and understood the issued with "chained indexing", but my code doesn't contain any:

def plot(pdb, df, title, **kw):
    df['target'] = (df['ogg'] + df['ugg']) / 2
    # ...

But then, later, much too late, I looked at where the plot() function is called:

    df = data[data['anz_emw'] > 0]
    pixbuf = plot(pdb, df, title)

So "df" isn't a data frame but an object that somehow remembers that it was created by indexing a data frame (so is that a view?) which would make the line in plot()

 df['target'] = ...

equivalent to

 data[data['anz_emw'] > 0]['target'] = ...

which is a chained indexing. Did I get that right?

Anyway,

def plot(pdb, df, title, **kw):
    df.loc[:,'target'] = (df['ogg'] + df['ugg']) / 2

fixed it.

How eliminate the tab space in the column in SQL Server 2008

Use the Below Code for that

UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`

How to solve java.lang.OutOfMemoryError trouble in Android

Few hints to handle such error/exception for Android Apps:

  1. Activities & Application have methods like:

    • onLowMemory
    • onTrimMemory Handle these methods to watch on memory usage.
  2. tag in Manifest can have attribute 'largeHeap' set to TRUE, which requests more heap for App sandbox.

  3. Managing in-memory caching & disk caching:

    • Images and other data could have been cached in-memory while app running, (locally in activities/fragment and globally); should be managed or removed.
  4. Use of WeakReference, SoftReference of Java instance creation , specifically to files.

  5. If so many images, use proper library/data structure which can manage memory, use samling of images loaded, handle disk-caching.

  6. Handle OutOfMemory exception

  7. Follow best practices for coding

    • Leaking of memory (Don't hold everything with strong reference)
  8. Minimize activity stack e.g. number of activities in stack (Don't hold everything on context/activty)

    • Context makes sense, those data/instances not required out of scope (activity and fragments), hold them into appropriate context instead global reference-holding.
  9. Minimize the use of statics, many more singletons.

  10. Take care of OS basic memory fundametals

    • Memory fragmentation issues
  11. Involk GC.Collect() manually sometimes when you are sure that in-memory caching no more needed.

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

How can I change the app display name build with Flutter?

The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows:

But, the case of iOS after you change the Display Name from Xcode, you are not able to run the application in the Flutter way, like flutter run.

Because the Flutter run expects the app name as Runner. Even if you change the name in Xcode, it doesn't work.

So, I fixed this as follows:

Move to the location on your Flutter project, ios/Runner.xcodeproj/project.pbxproj, and find and replace all instances of your new name with Runner.

Then everything should work in the flutter run way.

But don't forget to change the name display name on your next release time. Otherwise, the App Store rejects your name.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

Convert an int to ASCII character

My way to do this job is:

char to int
char var;
cout<<(int)var-48;
    
int to char
int var;
cout<<(char)(var|48);

And I write these functions for conversions:

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='\0'){
            break;
        }else{
            results*=10;
            results+=(int)szBroj[counter]-48;
            counter++;
        }
    }
    return results;
}

char * int2char(int iNumber){
    int iNumbersCount=0;
    int iTmpNum=iNumber;
    while(iTmpNum){
        iTmpNum/=10;
        iNumbersCount++;
    }
    char *buffer=new char[iNumbersCount+1];
    for(int i=iNumbersCount-1;i>=0;i--){
        buffer[i]=(char)((iNumber%10)|48);
        iNumber/=10;
    }
    buffer[iNumbersCount]='\0';
    return buffer;
}

Check if an array contains duplicate values

Here's an O(n) solution:

function hasDupes(arr) {
  /* temporary object */
  var uniqOb = {};
  /* create object attribute with name=value in array, this will not keep dupes*/
  for (var i in arr)
    uniqOb[arr[i]] = "";
  /* if object's attributes match array, then no dupes! */
  if (arr.length == Object.keys(uniqOb).length)
    alert('NO dupes');
  else
    alert('HAS dupes');


}
var arr = ["1/1/2016", "1/1/2016", "2/1/2016"];
hasDupes(arr);

https://jsfiddle.net/7kkgy1j3/

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Conda can also be used as package manager. It can be installed from Anaconda.

Alternatively, a free minimal installer is Miniconda.

Delayed function calls

This will work either on older versions of .NET
Cons: will execute in its own thread

class CancelableDelay
    {
        Thread delayTh;
        Action action;
        int ms;

        public static CancelableDelay StartAfter(int milliseconds, Action action)
        {
            CancelableDelay result = new CancelableDelay() { ms = milliseconds };
            result.action = action;
            result.delayTh = new Thread(result.Delay);
            result.delayTh.Start();
            return result;
        }

        private CancelableDelay() { }

        void Delay()
        {
            try
            {
                Thread.Sleep(ms);
                action.Invoke();
            }
            catch (ThreadAbortException)
            { }
        }

        public void Cancel() => delayTh.Abort();

    }

Usage:

var job = CancelableDelay.StartAfter(1000, () => { WorkAfter1sec(); });  
job.Cancel(); //to cancel the delayed job

reading from app.config file

This:

Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);

works fine for me.

Note that ConfigurationManager is in the System.Configuration namespace (so you'll likely want a using System.Configuration; statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.

Also, be sure you set system.configuration.dll as a reference in your project or build script.

Python threading.timer - repeat function every 'n' seconds

from threading import Timer
def TaskManager():
    #do stuff
    t = Timer( 1, TaskManager )
    t.start()

TaskManager()

Here is small sample, it will help beter understanding how it runs. function taskManager() at the end create delayed function call to it self.

Try to change "dalay" variable and you will able to see difference

from threading import Timer, _sleep

# ------------------------------------------
DATA = []
dalay = 0.25 # sec
counter = 0
allow_run = True
FIFO = True

def taskManager():

    global counter, DATA, delay, allow_run
    counter += 1

    if len(DATA) > 0:
        if FIFO:
            print("["+str(counter)+"] new data: ["+str(DATA.pop(0))+"]")
        else:
            print("["+str(counter)+"] new data: ["+str(DATA.pop())+"]")

    else:
        print("["+str(counter)+"] no data")

    if allow_run:
        #delayed method/function call to it self
        t = Timer( dalay, taskManager )
        t.start()

    else:
        print(" END task-manager: disabled")

# ------------------------------------------
def main():

    DATA.append("data from main(): 0")
    _sleep(2)
    DATA.append("data from main(): 1")
    _sleep(2)


# ------------------------------------------
print(" START task-manager:")
taskManager()

_sleep(2)
DATA.append("first data")

_sleep(2)
DATA.append("second data")

print(" START main():")
main()
print(" END main():")

_sleep(2)
DATA.append("last data")

allow_run = False

Getting all names in an enum as a String[]

The easiest way:

Category[] category = Category.values();
for (int i = 0; i < cat.length; i++) {
     System.out.println(i  + " - " + category[i]);
}

Where Category is Enum name

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'} when you define your update, which means

return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
  query: {method:'GET', params:{entryId:''}, isArray:true},
  post: {method:'POST'},
  update: {method:'PUT', params: {entryId: '@entryId'}},
  remove: {method:'DELETE'}
});

Fix: Was missing a closing curly brace on the update line.

Find and replace entire mysql database

This isn't possible - you need to carry out an UPDATE for each table individually.

WARNING: DUBIOUS, BUT IT'LL WORK (PROBABLY) SOLUTION FOLLOWS

Alternatively, you could dump the database via mysqldump and simply perform the search/replace on the resultant SQL file. (I'd recommend offlining anything that might touch the database whilst this is in progress, as well as using the --add-drop-table and --extended-insert flags.) However, you'd need to be sure that the search/replace text wasn't going to alter anything other than the data itself (i.e.: that the text you were going to swap out might not occur as a part of SQL syntax) and I'd really try doing the re-insert on an empty test database first.)

How to add percent sign to NSString

uese following code.

 NSString *searchText = @"Bhupi"
 NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];

will output: %Bhupi%

How to implement the --verbose or -v option into a script?

It might be cleaner if you have a function, say called vprint, that checks the verbose flag for you. Then you just call your own vprint function any place you want optional verbosity.

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

<DIV> inside link (<a href="">) tag

I would just format two different a-tags with a { display: block; height: 15px; width: 40px; } . This way you don't even need the div-tags...

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

Bootstrap modal z-index

Resolved this issue for vue, by adding to the options an id: 'alertBox' so now every modal container has its parent set to something like alertBox__id0whatver which can easily be changed with css:

div[id*="alertBox"] { background: red; }

(meaning if id name contains ( *= ) 'alertBox' it will be applied.

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

How can I delete a user in linux when the system says its currently used in a process

restart your computer and run $sudo deluser username... worked for me

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

If you want check only displayed objects(C#):

    public bool TextPresent(string text, int expectedNumberOfOccurrences)
    {
        var elements = Driver.FindElements(By.XPath(".//*[text()[contains(.,'" + text + "')]]"));
        var dispayedElements = 0;
        foreach (var webElement in elements)
        {
            if (webElement.Displayed)
            {
                dispayedElements++;
            }
        }
        var allExpectedElementsDisplayed = dispayedElements == expectedNumberOfOccurrences;
        return allExpectedElementsDisplayed;
    }

How to draw rounded rectangle in Android UI?

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:padding="10dp"
  android:shape="rectangle">
    <solid android:color="@color/colorAccent" /> 
    <corners
      android:bottomLeftRadius="500dp"
      android:bottomRightRadius="500dp"
      android:topLeftRadius="500dp"
      android:topRightRadius="500dp" />
</shape>

Now, in which element you want to use this shape just add: android:background="@drawable/custom_round_ui_shape"

Create a new XML in drawable named "custom_round_ui_shape"

Draw text in OpenGL ES

Take a look at CBFG and the Android port of the loading/rendering code. You should be able to drop the code into your project and use it straight away.

CBFG - http://www.codehead.co.uk/cbfg

Android loader - http://www.codehead.co.uk/cbfg/TexFont.java

Generate random integers between 0 and 9

>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]

Get value of multiselect box using jQuery or pure JS

I think the answer may be easier to understand like this:

_x000D_
_x000D_
$('#empid').on('change',function() {_x000D_
  alert($(this).val());_x000D_
  console.log($(this).val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<select id="empid" name="empname" multiple="multiple">_x000D_
  <option value="0">Potato</option>_x000D_
  <option value="1">Carrot</option>_x000D_
  <option value="2">Apple</option>_x000D_
  <option value="3">Raisins</option>_x000D_
  <option value="4">Peanut</option>_x000D_
</select>_x000D_
<br />_x000D_
Hold CTRL / CMD for selecting multiple fields
_x000D_
_x000D_
_x000D_

If you select "Carrot" and "Raisins" in the list, the output will be "1,3".

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

if your certificate is not valid, it will have a red "x" and state the reason why. Generally the reason is "This certificate has expired" or "This certificate was signed by an unknown authority.

to solve this you need to do the following step.

  1. If your certificate has expired, renew it at the iPhone Portal, download it, and double-click it to add it to your Keychain.
  2. If it's "signed by an unknown authority", download the "Apple Worldwide Developer Relations" certificate from the Certificates section of the iPhone Developer portal and double-click it to add it to your Keychain.
  3. If your certificate was revoked, delete the certificate from your Keychain, then follow the "Obtaining your iPhone Development Certificate" or "Obtaining your iPhone Distribution Certificate" section in the iPhone Developer Program Portal User Guide to generate a new certificate.
  4. Make sure you create a backup of your private key. The steps for doing this are described in the iPhone Developer Program Portal User Guide, under "Saving your Private Key and Transferring to other Systems".
  5. If you have the iPhone Developer (or iPhone Distribution) certificate and its associated private key, the Apple WWDR Intermediate certificate is installed, and your certificate is valid, confirm that Online Certificate Status Protocol (OCSP) and Certificate Revocation List (CRL) are set to "Off" in Keychain Access > Preferences > Certificates.
  6. if you still getting problem then contact support apple community.

Subset and ggplot2

Here 2 options for subsetting:

Using subset from base R:

library(ggplot2)
ggplot(subset(dat,ID %in% c("P1" , "P3"))) + 
         geom_line(aes(Value1, Value2, group=ID, colour=ID))

Using subset the argument of geom_line(Note I am using plyr package to use the special . function).

library(plyr)
ggplot(data=dat)+ 
  geom_line(aes(Value1, Value2, group=ID, colour=ID),
                ,subset = .(ID %in% c("P1" , "P3")))

You can also use the complementary subsetting:

subset(dat,ID != "P2")

Why use 'git rm' to remove a file instead of 'rm'?

If you just use rm, you will need to follow it up with git add <fileRemoved>. git rm does this in one step.

You can also use git rm --cached which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.

Java: using switch statement with enum under subclass

Change it to this:

switch (enumExample) {
    case VALUE_A: {
        //..
        break;
    }
}

The clue is in the error. You don't need to qualify case labels with the enum type, just its value.

Twitter bootstrap scrollable table

I had the same issue and used a combination of the above solutions (and added a twist of my own). Note that I had to specify column widths to keep them consistent between header and body.

In my solution, the header and footer stay fixed while the body scrolls.

<div class="table-responsive">
    <table class="table table-striped table-hover table-condensed">
        <thead>
            <tr>
                <th width="25%">First Name</th>
                <th width="13%">Last Name</th>
                <th width="25%" class="text-center">Address</th>
                <th width="25%" class="text-center">City</th>
                <th width="4%" class="text-center">State</th>
                <th width="8%" class="text-center">Zip</th>
            </tr>
        </thead>
    </table>
    <div class="bodycontainer scrollable">
        <table class="table table-hover table-striped table-condensed table-scrollable">
            <tbody>
                <!-- add rows here, specifying same widths as in header, at least on one row -->
            </tbody>
        </table>
    </div>
    <table class="table table-hover table-striped table-condensed">
        <tfoot>
            <!-- add your footer here... -->
        </tfoot>
    </table>
</div>

And then just applied the following CSS:

.bodycontainer { max-height: 450px; width: 100%; margin: 0; overflow-y: auto; }
.table-scrollable { margin: 0; padding: 0; }

I hope this helps someone else.

Send response to all clients except sender

For namespaces within rooms looping the list of clients in a room (similar to Nav's answer) is one of only two approaches I've found that will work. The other is to use exclude. E.G.

socket.on('message',function(data) {
    io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
}

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I had a similar situation, and the following process worked for me:

  1. In the terminal, type

    vi ~/.profile
    
  2. Then add this line in the file, and save

    export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
    

    where version is the one on your computer, such as 1.7.0_25

  3. Exit the editor, then type the following command make it become effective

    source ~/.profile 
    

Then type java -version to check the result

    java -version 

What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515

.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.

Batch file: Find if substring is in string (not in a file)

I usually do something like this:

Echo.%1 | findstr /C:"%2">nul && (
    REM TRUE
) || (
    REM FALSE
)

Example:

Echo.Hello world | findstr /C:"world">nul && (
    Echo.TRUE
) || (
    Echo.FALSE
)

Echo.Hello world | findstr /C:"World">nul && (Echo.TRUE) || (Echo.FALSE)

Output:

TRUE
FALSE

I don't know if this is the best way.

Unable to copy ~/.ssh/id_rsa.pub

Based on the date of this question the original poster wouldn't have been using Windows Subsystem for Linux. But if you are, and you get the same error, the following alternative works:

clip.exe < ~/.ssh/id_rsa.pub

Thanks to this page for pointing out Windows' clip.exe (and you have to type the ".exe") can be run from the bash shell.

Copying the cell value preserving the formatting from one cell to another in excel using VBA

I prefer to avoid using select

     With sheets("sheetname").range("I10") 
          .PasteSpecial Paste:=xlPasteValues, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
                  Transpose:=False
          .PasteSpecial Paste:=xlPasteFormats, _
                  Operation:=xlNone, _
                  SkipBlanks:=False, _
                  Transpose:=False
          .font.color = sheets("sheetname").range("F10").font.color
      End With
      sheets("sheetname").range("I10:J10").merge

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

What's the valid way to include an image with no src?

Use a truly blank, valid and highly compatible SVG, based on this article:

src="data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E"

It will default in size to 300x150px as any SVG does, but you can work with that in your img element default styles, as you would possibly need in any case in the practical implementation.

How to Remove Array Element and Then Re-Index Array?

In addition to xzyfer's answer

The function

function custom_unset(&$array=array(), $key=0) {
    if(isset($array[$key])){

        // remove item at index
        unset($array[$key]);

        // 'reindex' array
        $array = array_values($array);

        //alternatively
        //$array = array_merge($array); 

    }
    return $array;
}

Use

$my_array=array(
    0=>'test0', 
    1=>'test1', 
    2=>'test2'
);

custom_unset($my_array, 1);

Result

 array(2) {
    [0]=>
    string(5) "test0"
    [1]=>
    string(5) "test2"
  }

How to determine whether a substring is in a different string

People mentioned string.find(), string.index(), and string.indexOf() in the comments, and I summarize them here (according to the Python Documentation):

First of all there is not a string.indexOf() method. The link posted by Deviljho shows this is a JavaScript function.

Second the string.find() and string.index() actually return the index of a substring. The only difference is how they handle the substring not found situation: string.find() returns -1 while string.index() raises an ValueError.

A table name as a variable

Change your last statement to this:

EXEC('SELECT * FROM ' + @tablename)

This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.

--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE @table_name varchar(max)
SET @table_name =
    (SELECT 'TEST_'
            + DATENAME(YEAR,GETDATE())
            + UPPER(DATENAME(MONTH,GETDATE())) )

--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
          FROM sysobjects
          WHERE name = @table_name AND xtype = 'U')

BEGIN
    EXEC('drop table ' +  @table_name)
END

--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')

Call to getLayoutInflater() in places not in activity

Using context object you can get LayoutInflater from following code

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

dll missing in JDBC

Alright guys, I found it out! I didn't really need to change the java.library.path but the "Native library location" of sqljdbc.jar

This is the best answer I could find: https://stackoverflow.com/a/958074/2000342

It works now, thanks for the support!

Convert String into a Class Object

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

First, if I'm understanding your question, you want to store your object into a String and then later to be able to read it again and re-create the Object.

Personally, when I need to do that I use ObjectOutputStream. However, there is a mandatory condition. The object you want to convert to a String and then back to an Object must be a Serializable object, and also all its attributes.

Let's Consider ReadWriteObject, the object to manipulate and ReadWriteTest the manipulator.

Here is how I would do it:

public class ReadWriteObject implements Serializable {

    /** Serial Version UID */
    private static final long serialVersionUID = 8008750006656191706L;

    private int age;
    private String firstName;
    private String lastName;

    /**
     * @param age
     * @param firstName
     * @param lastName
     */
    public ReadWriteObject(int age, String firstName, String lastName) {
        super();
        this.age = age;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "ReadWriteObject [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + "]";
    }

}


public class ReadWriteTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Create Object to write and then to read
        // This object must be Serializable, and all its subobjects as well
        ReadWriteObject inputObject = new ReadWriteObject(18, "John", "Doe");

        // Read Write Object test

        // Write Object into a Byte Array
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(inputObject);
        byte[] rawData = baos.toByteArray();
        String rawString = new String(rawData);
        System.out.println(rawString);

        // Read Object from the Byte Array
        byte[] byteArrayFromString = rawString.getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayFromString);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object outputObject = ois.readObject();
        System.out.println(outputObject);
    }
}

The Standard Output is similar to that (actually, I can't copy/paste it) :

¬í ?sr ?*com.ajoumady.stackoverflow.ReadWriteObjecto$˲é¦LÚ ?I ?ageL ?firstNamet ?Ljava/lang/String;L ?lastNameq ~ ?xp ?t ?John ?Doe

ReadWriteObject [age=18, firstName=John, lastName=Doe]

How do I get next month date from today's date and insert it in my database?

The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.

If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.

$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;

This way, you will be able to get the month and year of the next month without having a month skipped.

How to change the CHARACTER SET (and COLLATION) throughout a database?

here describes the process well. However, some of the characters that didn't fit in latin space are gone forever. UTF-8 is a SUPERSET of latin1. Not the reverse. Most will fit in single byte space, but any undefined ones will not (check a list of latin1 - not all 256 characters are defined, depending on mysql's latin1 definition)

What is the best way to update the entity in JPA

That depends on what you want to do, but as you said, getting an entity reference using find() and then just updating that entity is the easiest way to do that.

I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.

javascript multiple OR conditions in IF statement

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

which translates to

if (id !== 1 && id !== 2 && id !== 3)

or alternatively for something more pythonesque:

if (!(id in [,1,2,3]))

Read JSON data in a shell script

Similarly using Bash regexp. Shall be able to snatch any key/value pair.

key="Body"
re="\"($key)\": \"([^\"]*)\""

while read -r l; do
    if [[ $l =~ $re ]]; then
        name="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"
        echo "$name=$value"
    else
        echo "No match"
    fi
done

Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded ". This is an illustration. Better to use some "industrial" parser :)

Hide/encrypt password in bash file to stop accidentally seeing it

I used base64 for the overcoming the same problem, i.e. people can see my password over my shoulder.

Here is what I did - I created a new "db_auth.cfg" file and created parameters with one being my db password. I set the permission as 750 for the file.

DB_PASSWORD=Z29vZ2xl

In my shell script I used the "source" command to get the file and then decode it back to use in my script.

source path_to_the_file/db_auth.cfg
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)

I hope this helps.

How to scale an Image in ImageView to keep the aspect ratio

To anyone else having this particular issue. You have an ImageView that you want to have a width of fill_parent and a height scaled proportionately:

Add these two attributes to your ImageView:

android:adjustViewBounds="true"
android:scaleType="centerCrop"

And set the ImageView width to fill_parent and height to wrap_content.

Also, if you don't want your image to be cropped, try this:

 android:adjustViewBounds="true"
 android:layout_centerInParent="true"

How to prevent ENTER keypress to submit a web form?

[revision 2012, no inline handler, preserve textarea enter handling]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Have been trying every variation on João's solution to get an IN List query to work with Tornado's mysql wrapper, and was still getting the accursed "TypeError: not enough arguments for format string" error. Turns out adding "*" to the list var "*args" did the trick.

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
db.query(sql, *args)

How to deserialize JS date using Jackson?

@JsonFormat only work for standard format supported by the jackson version that you are using.

Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6

git with development, staging and production branches

We do it differently. IMHO we do it in an easier way: in master we are working on the next major version.

Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.

To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.

If a new release is coming, we create a side-branch out of master, e.g. release-5 where only bugs get fixed.

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

CSS: 100% width or height while keeping aspect ratio?

By setting the CSS max-width property to 100%, an image will fill the width of it's parenting element, but won’t render larger than it's actual size, thus preserving resolution.

Setting the height property to auto maintains the aspect ratio of the image, using this technique allows static height to be overridden and enables the image to flex proportionally in all directions.

img {
    max-width: 100%;
    height: auto;      
}

Split large string in n-size chunks in JavaScript

Here is the code that I am using, it uses String.prototype.slice.

Yes it is quite long as an answer goes as it tries to follow current standards as close as possible and of course contains a reasonable amount of JSDOC comments. However, once minified, the code is only 828 bytes and once gzipped for transmission it is only 497 bytes.

The 1 method that this adds to String.prototype (using Object.defineProperty where available) is:

  1. toChunks

A number of tests have been included to check the functionality.

Worried that the length of code will affect the performance? No need to worry, http://jsperf.com/chunk-string/3

Much of the extra code is there to be sure that the code will respond the same across multiple javascript environments.

_x000D_
_x000D_
/*jslint maxlen:80, browser:true, devel:true */_x000D_
_x000D_
/*_x000D_
 * Properties used by toChunks._x000D_
 */_x000D_
_x000D_
/*property_x000D_
    MAX_SAFE_INTEGER, abs, ceil, configurable, defineProperty, enumerable,_x000D_
    floor, length, max, min, pow, prototype, slice, toChunks, value,_x000D_
    writable_x000D_
*/_x000D_
_x000D_
/*_x000D_
 * Properties used in the testing of toChunks implimentation._x000D_
 */_x000D_
_x000D_
/*property_x000D_
    appendChild, createTextNode, floor, fromCharCode, getElementById, length,_x000D_
    log, pow, push, random, toChunks_x000D_
*/_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;_x000D_
_x000D_
    /**_x000D_
     * Defines a new property directly on an object, or modifies an existing_x000D_
     * property on an object, and returns the object._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {Object} object_x000D_
     * @param {string} property_x000D_
     * @param {Object} descriptor_x000D_
     * @return {Object}_x000D_
     * @see https://goo.gl/CZnEqg_x000D_
     */_x000D_
    function $defineProperty(object, property, descriptor) {_x000D_
        if (Object.defineProperty) {_x000D_
            Object.defineProperty(object, property, descriptor);_x000D_
        } else {_x000D_
            object[property] = descriptor.value;_x000D_
        }_x000D_
_x000D_
        return object;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operands are strictly equal with no type conversion._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} a_x000D_
     * @param {*} b_x000D_
     * @return {boolean}_x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4_x000D_
     */_x000D_
    function $strictEqual(a, b) {_x000D_
        return a === b;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns true if the operand inputArg is undefined._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @return {boolean}_x000D_
     */_x000D_
    function $isUndefined(inputArg) {_x000D_
        return $strictEqual(typeof inputArg, 'undefined');_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation throws an error if its argument is a value that_x000D_
     * cannot be converted to an Object, otherwise returns the argument._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be tested._x000D_
     * @throws {TypeError} If inputArg is null or undefined._x000D_
     * @return {*} The inputArg if coercible._x000D_
     * @see https://goo.gl/5GcmVq_x000D_
     */_x000D_
    function $requireObjectCoercible(inputArg) {_x000D_
        var errStr;_x000D_
_x000D_
        if (inputArg === null || $isUndefined(inputArg)) {_x000D_
            errStr = 'Cannot convert argument to object: ' + inputArg;_x000D_
            throw new TypeError(errStr);_x000D_
        }_x000D_
_x000D_
        return inputArg;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation converts its argument to a value of type string_x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @return {string}_x000D_
     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring_x000D_
     */_x000D_
    function $toString(inputArg) {_x000D_
        var type,_x000D_
            val;_x000D_
_x000D_
        if (inputArg === null) {_x000D_
            val = 'null';_x000D_
        } else {_x000D_
            type = typeof inputArg;_x000D_
            if (type === 'string') {_x000D_
                val = inputArg;_x000D_
            } else if (type === 'undefined') {_x000D_
                val = type;_x000D_
            } else {_x000D_
                if (type === 'symbol') {_x000D_
                    throw new TypeError('Cannot convert symbol to string');_x000D_
                }_x000D_
_x000D_
                val = String(inputArg);_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * Returns a string only if the arguments is coercible otherwise throws an_x000D_
     * error._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg_x000D_
     * @throws {TypeError} If inputArg is null or undefined._x000D_
     * @return {string}_x000D_
     */_x000D_
    function $onlyCoercibleToString(inputArg) {_x000D_
        return $toString($requireObjectCoercible(inputArg));_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The function evaluates the passed value and converts it to an integer._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be converted to an integer._x000D_
     * @return {number} If the target value is NaN, null or undefined, 0 is_x000D_
     *                   returned. If the target value is false, 0 is returned_x000D_
     *                   and if true, 1 is returned._x000D_
     * @see http://www.ecma-international.org/ecma-262/5.1/#sec-9.4_x000D_
     */_x000D_
    function $toInteger(inputArg) {_x000D_
        var number = +inputArg,_x000D_
            val = 0;_x000D_
_x000D_
        if ($strictEqual(number, number)) {_x000D_
            if (!number || number === Infinity || number === -Infinity) {_x000D_
                val = number;_x000D_
            } else {_x000D_
                val = (number > 0 || -1) * Math.floor(Math.abs(number));_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return val;_x000D_
    }_x000D_
_x000D_
    /**_x000D_
     * The abstract operation ToLength converts its argument to an integer_x000D_
     * suitable for use as the length of an array-like object._x000D_
     *_x000D_
     * @private_x000D_
     * @function_x000D_
     * @param {*} inputArg The object to be converted to a length._x000D_
     * @return {number} If len <= +0 then +0 else if len is +INFINITY then_x000D_
     *                   2^53-1 else min(len, 2^53-1)._x000D_
     * @see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength_x000D_
     */_x000D_
    function $toLength(inputArg) {_x000D_
        return Math.min(Math.max($toInteger(inputArg), 0), MAX_SAFE_INTEGER);_x000D_
    }_x000D_
_x000D_
    if (!String.prototype.toChunks) {_x000D_
        /**_x000D_
         * This method chunks a string into an array of strings of a specified_x000D_
         * chunk size._x000D_
         *_x000D_
         * @function_x000D_
         * @this {string} The string to be chunked._x000D_
         * @param {Number} chunkSize The size of the chunks that the string will_x000D_
         *                           be chunked into._x000D_
         * @returns {Array} Returns an array of the chunked string._x000D_
         */_x000D_
        $defineProperty(String.prototype, 'toChunks', {_x000D_
            enumerable: false,_x000D_
            configurable: true,_x000D_
            writable: true,_x000D_
            value: function (chunkSize) {_x000D_
                var str = $onlyCoercibleToString(this),_x000D_
                    chunkLength = $toInteger(chunkSize),_x000D_
                    chunked = [],_x000D_
                    numChunks,_x000D_
                    length,_x000D_
                    index,_x000D_
                    start,_x000D_
                    end;_x000D_
_x000D_
                if (chunkLength < 1) {_x000D_
                    return chunked;_x000D_
                }_x000D_
_x000D_
                length = $toLength(str.length);_x000D_
                numChunks = Math.ceil(length / chunkLength);_x000D_
                index = 0;_x000D_
                start = 0;_x000D_
                end = chunkLength;_x000D_
                chunked.length = numChunks;_x000D_
                while (index < numChunks) {_x000D_
                    chunked[index] = str.slice(start, end);_x000D_
                    start = end;_x000D_
                    end += chunkLength;_x000D_
                    index += 1;_x000D_
                }_x000D_
_x000D_
                return chunked;_x000D_
            }_x000D_
        });_x000D_
    }_x000D_
}());_x000D_
_x000D_
/*_x000D_
 * Some tests_x000D_
 */_x000D_
_x000D_
(function () {_x000D_
    'use strict';_x000D_
_x000D_
    var pre = document.getElementById('out'),_x000D_
        chunkSizes = [],_x000D_
        maxChunkSize = 512,_x000D_
        testString = '',_x000D_
        maxTestString = 100000,_x000D_
        chunkSize = 0,_x000D_
        index = 1;_x000D_
_x000D_
    while (chunkSize < maxChunkSize) {_x000D_
        chunkSize = Math.pow(2, index);_x000D_
        chunkSizes.push(chunkSize);_x000D_
        index += 1;_x000D_
    }_x000D_
_x000D_
    index = 0;_x000D_
    while (index < maxTestString) {_x000D_
        testString += String.fromCharCode(Math.floor(Math.random() * 95) + 32);_x000D_
        index += 1;_x000D_
    }_x000D_
_x000D_
    function log(result) {_x000D_
        pre.appendChild(document.createTextNode(result + '\n'));_x000D_
    }_x000D_
_x000D_
    function test() {_x000D_
        var strLength = testString.length,_x000D_
            czLength = chunkSizes.length,_x000D_
            czIndex = 0,_x000D_
            czValue,_x000D_
            result,_x000D_
            numChunks,_x000D_
            pass;_x000D_
_x000D_
        while (czIndex < czLength) {_x000D_
            czValue = chunkSizes[czIndex];_x000D_
            numChunks = Math.ceil(strLength / czValue);_x000D_
            result = testString.toChunks(czValue);_x000D_
            czIndex += 1;_x000D_
            log('chunksize: ' + czValue);_x000D_
            log(' Number of chunks:');_x000D_
            log('  Calculated: ' + numChunks);_x000D_
            log('  Actual:' + result.length);_x000D_
            pass = result.length === numChunks;_x000D_
            log(' First chunk size: ' + result[0].length);_x000D_
            pass = pass && result[0].length === czValue;_x000D_
            log(' Passed: ' + pass);_x000D_
            log('');_x000D_
        }_x000D_
    }_x000D_
_x000D_
    test();_x000D_
    log('');_x000D_
    log('Simple test result');_x000D_
    log('abcdefghijklmnopqrstuvwxyz'.toChunks(3));_x000D_
}());
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

how to extract only the year from the date in sql server 2008?

SQL Server Script

declare @iDate datetime
set @iDate=GETDATE()

print year(@iDate) -- for Year

print month(@iDate) -- for Month

print day(@iDate) -- for Day

Soft hyphen in HTML (<wbr> vs. &shy;)

It is very important to notice that, as of HTML5, <wbr> and &shy; are not supposed to do the same thing!

Soft hyphens

&shy; is a soft hyphen, i.e., U+00AD: SOFT HYPHEN. For example,

innehålls&shy;förteckning

might be rendered as

innehållsförteckning

or as

innehålls-
förteckning

As of today, soft hyphens work in Firefox, Chrome, and Internet Explorer.

The wbr element

The wbr element is a word-break opportunity, which will not display a hyphen if a line break occurs. For example,

ABCDEFG<wbr/>abcdefg

might be rendered as

ABCDEFGabcdefg

or as

ABCDEFG
abcdefg

As of today, this element works in Firefox and Chrome.

How to get the second column from command output?

#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

ls -lh | co 5

List<String> to ArrayList<String> conversion issue

Take a look at ArrayList#addAll(Collection)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behaviour of this call is undefined if the specified collection is this list, and this list is nonempty.)

So basically you could use

ArrayList<String> listOfStrings = new ArrayList<>(list.size());
listOfStrings.addAll(list);

How do I convert between ISO-8859-1 and UTF-8 in Java?

The easiest way to convert an ISO-8859-1 string to UTF-8 string.

private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("ISO-8859-1"), "utf-8");
}

If we want to convert an UTF-8 string to ISO-8859-1 string.

private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("utf-8"), "ISO-8859-1");
}

Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.

public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
    String res = "";
    int i = 0;
    for (i = 0; i < strISO_8859_1.length() - 1; i++) {
        char ch = strISO_8859_1.charAt(i);
        char chNext = strISO_8859_1.charAt(i + 1);
        if (ch <= 127) {
            res += ch;
        } else if (ch == 194 && chNext >= 128 && chNext <= 191) {
            res += chNext;
        } else if(ch == 195 && chNext >= 128 && chNext <= 191){
            int resNum = chNext + 64;
            res += (char) resNum;
        } else if(ch == 194){
            res += (char) 173;
        } else if(ch == 195){
            res += (char) 224;
        }
    }
    char ch = strISO_8859_1.charAt(i);
    if (ch <= 127 ){
        res += ch;
    }
    return res;
}

}

That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1

Make Div overlay ENTIRE page (not just viewport)?

I looked at Nate Barr's answer above, which you seemed to like. It doesn't seem very different from the simpler

html {background-color: grey}

INNER JOIN vs LEFT JOIN performance in SQL Server

From my comparisons, I find that they have the exact same execution plan. There're three scenarios:

  1. If and when they return the same results, they have the same speed. However, we must keep in mind that they are not the same queries, and that LEFT JOIN will possibly return more results (when some ON conditions aren't met) --- this is why it's usually slower.

  2. When the main table (first non-const one in the execution plan) has a restrictive condition (WHERE id = ?) and the corresponding ON condition is on a NULL value, the "right" table is not joined --- this is when LEFT JOIN is faster.

  3. As discussed in Point 1, usually INNER JOIN is more restrictive and returns fewer results and is therefore faster.

Both use (the same) indices.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

It's Easy.

Example from MSDN:

public static void Main()
{
    // Use the file name to load the assembly into the current
    // application domain.
    Assembly a = Assembly.Load("example");
    // Get the type to use.
    Type myType = a.GetType("Example");
    // Get the method to call.
    MethodInfo myMethod = myType.GetMethod("MethodA");
    // Create an instance.
    object obj = Activator.CreateInstance(myType);
    // Execute the method.
    myMethod.Invoke(obj, null);
}

Here's a reference link

https://msdn.microsoft.com/en-us/library/25y1ya39.aspx

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

postgreSQL - psql \i : how to execute script in a given path

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

How to download the latest artifact from Artifactory repository?

Using shell/unix tools

  1. curl 'http://$artiserver/artifactory/api/storage/$repokey/$path/$version/?lastModified'

The above command responds with a JSON with two elements - "uri" and "lastModified"

  1. Fetching the link in the uri returns another JSON which has the "downloadUri" of the artifact.

  2. Fetch the link in the "downloadUri" and you have the latest artefact.

Using Jenkins Artifactory plugin

(Requires Pro) to resolve and download latest artifact, if Jenkins Artifactory plugin was used to publish to artifactory in another job:

  1. Select Generic Artifactory Integration
  2. Use Resolved Artifacts as ${repokey}:**/${component}*.jar;status=${STATUS}@${PUBLISH_BUILDJOB}#LATEST=>${targetDir}

Increasing the maximum number of TCP/IP connections in Linux

There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.

More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:

  • Check if your TCP window setting is large enough. Linux defaults are good for everything except really fast inet link (hundreds of mbps) or fast satellite links. What is your bandwidth*delay product?
  • Check for packet loss using ping with large packets (ping -s 1472 ...)
  • Check for rate limiting. On Linux, this is configured with tc
  • Confirm that the bandwidth you think exists actually exists using e.g., iperf
  • Confirm that your protocol is sane. Remember latency.
  • If this is a gigabit+ LAN, can you use jumbo packets? Are you?

Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat or lsof). If that number is substantial, you might:

  • Have a lot of bandwidth, e.g., 100mbps+. In this case, you may actually need to up the ulimit -n. Still, ~1000 connections (default on my system) is quite a few.
  • Have network problems which are slowing down your connections (e.g., packet loss)
  • Have something else slowing you down, e.g., IO bandwidth, especially if you're seeking. Have you checked iostat -x?

Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.

I hope this provides some help. You're really asking a networking question.

Running Node.Js on Android

Dory - node.js

Great New Application
No Need to root your Phone and You Can Run your js File From anywere.

  • node.js runtime(run ES2015/ES6, ES2016 javascript and node.js APIs in android)
  • API Documents and instant code run from doc
  • syntax highlighting code editor
  • npm supports
  • linux terminal(toybox 0.7.4). node.js REPL and npm command in shell (add '--no-bin-links' option if you execute npm in /sdcard)
  • StartOnBoot / LiveReload
  • native node.js binary and npm are included. no need to be online.

Update instruction to node js 8 (async await)

  1. Download node.js v8.3.0 arm zip file and unzip.

  2. copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)

  3. open the shell(check it out in the app's menu)

  4. cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )

  5. rm node

  6. cp /sdcard/node .

  7. (chmod a+x node

(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)

encapsulation vs abstraction real world example

Let me give my 2 cents of a real-world example-analogy close to IT.

Lets say you have a subscription site, e.g a wordpress site

Each user has a role, eg admin, subscriber and so on. Many users can be admins, subscribers etc..

So abstraction here is reflected in the fact that any user with admin role can do a set of things, it does not matter which specific user this is (this is an example of abstraction).

On the other hand, subscriber users do not have access to certain settings of the site, thus some internals of the application are encapsulated for plain subscribers (this is an example of encapsulation)

As one can see abstraction and encapsulation are relative concepts, they apply with respect to something specific.

One can follow this line of reasoning and explain polymoprhism and inheritance.

For example super-admin users could do all the things admin users could do, plus some more. Moreover, if admin roles get an update in functionality, super-admins would get the same update. Thus one can see here an example of inheritance, in that super-admin roles inherit all the properties of admin roles and extend them. Note that for most part of the site, admins are interchangeable with super-admins (meaning a super-admin user can easily be used in place of an admin user, but not vice-versa in general).

C++ variable has initializer but incomplete type?

I got a similar error and hit this page while searching the solution.

With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.

Is there a way to use shell_exec without waiting for the command to complete?

You can also give your output back to the client instantly and continue processing your PHP code afterwards.

This is the method I am using for long-waiting Ajax calls which would not have any effect on client side:

ob_end_clean();
ignore_user_abort();
ob_start();
header("Connection: close");
echo json_encode($out);
header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
// execute your command here. client will not wait for response, it already has one above.

You can find the detailed explanation here: http://oytun.co/response-now-process-later

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

The code below resolved the issue

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3

Get refresh token google api

For those using the Google API Client Library for PHP and seeking offline access and refresh tokens beware as of the time of this writing the docs are showing incorrect examples.

currently it's showing:

$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true);   // incremental auth

source: https://developers.google.com/identity/protocols/OAuth2WebServer#offline

All of this works great - except ONE piece

$client->setApprovalPrompt("consent");

After a bit of reasoning I changed this line to the following and EVERYTHING WORKED

$client->setPrompt("consent");

It makes sense since using the HTTP requests it was changed from approval_prompt=force to prompt=consent. So changing the setter method from setApprovalPrompt to setPrompt follows natural convention - BUT IT'S NOT IN THE DOCS!!! That I found at least.

Convert Text to Uppercase while typing in Text box

I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
        {
            int iPos = textBox1.SelectionStart;
            int iLen = textBox1.SelectionLength;
            textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
            textBox1.SelectionStart = iPos + 1;
            e.Handled = true;
        }
    }

It works even if you type a lowercase character in a textbox where some characters are selected. I don't know if the code works with a Multiline textbox.

Can we create an instance of an interface in Java?

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

Google Maps setCenter()

For me above solutions didn't work then I tried

map.setCenter(new google.maps.LatLng(lat, lng));

and it worked as expected.

Converts scss to css

Install Ruby-sass using below command
sudo apt-get -y update
sudo apt-get -y install ruby-full
sudo apt install ruby-sass
gem install bundler

Example
sass SCSS_FILE_PATH:CSS_FILE_PATH;

e.g sass mda/at-md-black.scss:css/at-md-black.css;

Change text from "Submit" on input tag

The value attribute on submit-type <input> elements controls the text displayed.

<input type="submit" class="like" value="Like" />

How to use if statements in LESS

I stumbled over the same question and I've found a solution.

First make sure you upgrade to LESS 1.6 at least. You can use npm for that case.

Now you can use the following mixin:

.if (@condition, @property, @value) when (@condition = true){
     @{property}: @value;
 }

Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:

.myHeadline {
   .if(@include-lineHeight,  line-height, '35px');
}

If @include-lineheight resolves to true LESS will print the line-height: 35px and it will skip the mixin if @include-lineheight is not true.

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

How to get current timestamp in milliseconds since 1970 just the way Java gets

If using gettimeofday you have to cast to long long otherwise you will get overflows and thus not the real number of milliseconds since the epoch: long int msint = tp.tv_sec * 1000 + tp.tv_usec / 1000; will give you a number like 767990892 which is round 8 days after the epoch ;-).

int main(int argc, char* argv[])
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    long long mslong = (long long) tp.tv_sec * 1000L + tp.tv_usec / 1000; //get current timestamp in milliseconds
    std::cout << mslong << std::endl;
}

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.