Programs & Examples On #Pike

Pike is an interpreted, object-oriented, dynamic programming language with a syntax similar to C. It includes a powerful modules system that, for instance, has image manipulation, database connectivity and advanced cryptography. It is simple to learn, does not require long compilation passes and has powerful built-in data types allowing simple and fast data manipulation.

HTTP POST with Json on Body - Flutter/Dart

This would also work :

import 'package:http/http.dart' as http;

  sendRequest() async {

    Map data = {
       'apikey': '12345678901234567890'
    };

    var url = 'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
    http.post(url, body: data)
        .then((response) {
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");
    });  
  }

NullInjectorError: No provider for AngularFirestore

I solved this problem by just removing firestore from:

import { AngularFirestore } from '@angular/fire/firestore/firestore';

in my component.ts file. as use only:

import { AngularFirestore } from '@angular/fire/firestore';

this can be also your problem.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Access Control Origin Header error using Axios in React Web throwing error in Chrome

I had the same error. I solved it by installing CORS in my backend using npm i cors. You'll then need to add this to your code:

const cors = require('cors');
app.use(cors());

This fixed it for me; now I can post my forms using AJAX and without needing to add any customized headers.

How to push JSON object in to array using javascript

var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};

var data = [];
data.push(postdata);

console.log(data);

How do I get rid of the b-prefix in a string in python?

You need to decode it to convert it to a string. Check the answer here about bytes literal in python3.

In [1]: b'I posted a new photo to Facebook'.decode('utf-8')
Out[1]: 'I posted a new photo to Facebook'

Correctly Parsing JSON in Swift 3

Swift has a powerful type inference. Lets get rid of "if let" or "guard let" boilerplate and force unwraps using functional approach:

  1. Here is our JSON. We can use optional JSON or usual. I'm using optional in our example:
let json: Dictionary<String, Any>? = ["current": ["temperature": 10]]
  1. Helper functions. We need to write them only once and then reuse with any dictionary:
/// Curry
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { a in
        { f(a, $0) }
    }
}

/// Function that takes key and optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key, _ json: Dictionary<Key, Any>?) -> Value? {
    return json.flatMap {
        cast($0[key])
    }
}

/// Function that takes key and return function that takes optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key) -> (Dictionary<Key, Any>?) -> Value? {
    return curry(extract)(key)
}

/// Precedence group for our operator
precedencegroup RightApplyPrecedence {
    associativity: right
    higherThan: AssignmentPrecedence
    lowerThan: TernaryPrecedence
}

/// Apply. g § f § a === g(f(a))
infix operator § : RightApplyPrecedence
public func §<A, B>(_ f: (A) -> B, _ a: A) -> B {
    return f(a)
}

/// Wrapper around operator "as".
public func cast<A, B>(_ a: A) -> B? {
    return a as? B
}
  1. And here is our magic - extract the value:
let temperature = (extract("temperature") § extract("current") § json) ?? NSNotFound

Just one line of code and no force unwraps or manual type casting. This code works in playground, so you can copy and check it. Here is an implementation on GitHub.

Getting "Cannot call a class as a function" in my React Project

Mostly these issues occur when you miss extending Component from react:

import React, {Component} from 'react'

export default class TimePicker extends Component {
    render() {
        return();     
    }
}

Is it safe to expose Firebase apiKey to the public?

EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.

Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.

You can always restrict you firebase project keys to domains / IP's.

https://console.cloud.google.com/apis/credentials/key

select your project Id and key and restrict it to Your Android/iOs/web App.

Google Maps API warning: NoApiKeys

I had the same problem and I found out that if you add the URL param ?v=3 you won't get the warning message anymore:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>

Reproduction online

As pointed out in the comments by @Zia Ul Rehman Mughal

Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version

Update 07-Jun-2016

This solution doesn't work anymore.

How to force Docker for a clean build of an image

The command docker build --no-cache . solved our similar problem.

Our Dockerfile was:

RUN apt-get update
RUN apt-get -y install php5-fpm

But should have been:

RUN apt-get update && apt-get -y install php5-fpm

To prevent caching the update and install separately.

See: Best practices for writing Dockerfiles

Forward X11 failed: Network error: Connection refused

X display location : localhost:0 Worked for me :)

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Why "Accepted Answer" works... but it wasn't enough for me

This works in the specification. At least swagger-tools (version 0.10.1) validates it as a valid.

But if you are using other tools like swagger-codegen (version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:

this.authentications = {
  'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};

There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:

this.rootGet = function(callback) { ... }

This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.

My alternative

Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.

Note: which is being discussed in

So, it's handle authentication like a standard header. On path object append an header paremeter:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: localhost
schemes:
  - http
  - https
paths:
  /:
    get:
      parameters:
        - 
          name: authorization
          in: header
          type: string
          required: true
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

This will generate a client with a new parameter on method signature:

this.rootGet = function(authorization, callback) {
  // ...
  var headerParams = {
    'authorization': authorization
  };
  // ...
}

To use this method in the right way, just pass the "full string"

// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);

And works.

How to know a Pod's own IP address from inside a container in the Pod?

The simplest answer is to ensure that your pod or replication controller yaml/json files add the pod IP as an environment variable by adding the config block defined below. (the block below additionally makes the name and namespace available to the pod)

env:
- name: MY_POD_NAME
  valueFrom:
    fieldRef:
      fieldPath: metadata.name
- name: MY_POD_NAMESPACE
  valueFrom:
    fieldRef:
      fieldPath: metadata.namespace
- name: MY_POD_IP
  valueFrom:
    fieldRef:
      fieldPath: status.podIP

Recreate the pod/rc and then try

echo $MY_POD_IP

also run env to see what else kubernetes provides you with.

Cheers

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

Adding subscribers to a list using Mailchimp's API v3

These are good answers but detached from a full answer as to how you would get a form to send data and handle that response. This will demonstrate how to add a member to a list with v3.0 of the API from an HTML page via jquery .ajax().

In Mailchimp:

  1. Acquire your API Key and List ID
  2. Make sure you setup your list and what custom fields you want to use with it. In this case, I've set up zipcode as a custom field in the list BEFORE I did the API call.
  3. Check out the API docs on adding members to lists. We are using the create method which requires the use of HTTP POST requests. There are other options in here that require PUT if you want to be able to modify/delete subs.

HTML:

<form id="pfb-signup-submission" method="post">
  <div class="sign-up-group">
    <input type="text" name="pfb-signup" id="pfb-signup-box-fname" class="pfb-signup-box" placeholder="First Name">
    <input type="text" name="pfb-signup" id="pfb-signup-box-lname" class="pfb-signup-box" placeholder="Last Name">
    <input type="email" name="pfb-signup" id="pfb-signup-box-email" class="pfb-signup-box" placeholder="[email protected]">
    <input type="text" name="pfb-signup" id="pfb-signup-box-zip" class="pfb-signup-box" placeholder="Zip Code">
  </div>
  <input type="submit" class="submit-button" value="Sign-up" id="pfb-signup-button"></a>
  <div id="pfb-signup-result"></div>
</form>

Key things:

  1. Give your <form> a unique ID and don't forget the method="post" attribute so the form works.
  2. Note the last line #signup-result is where you will deposit the feedback from the PHP script.

PHP:

<?php
  /*
   * Add a 'member' to a 'list' via mailchimp API v3.x
   * @ http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   *
   * ================
   * BACKGROUND
   * Typical use case is that this code would get run by an .ajax() jQuery call or possibly a form action
   * The live data you need will get transferred via the global $_POST variable
   * That data must be put into an array with keys that match the mailchimp endpoints, check the above link for those
   * You also need to include your API key and list ID for this to work.
   * You'll just have to go get those and type them in here, see README.md
   * ================
   */

  // Set API Key and list ID to add a subscriber
  $api_key = 'your-api-key-here';
  $list_id = 'your-list-id-here';

  /* ================
   * DESTINATION URL
   * Note: your API URL has a location subdomain at the front of the URL string
   * It can vary depending on where you are in the world
   * To determine yours, check the last 3 digits of your API key
   * ================
   */
  $url = 'https://us5.api.mailchimp.com/3.0/lists/' . $list_id . '/members/';

  /* ================
   * DATA SETUP
   * Encode data into a format that the add subscriber mailchimp end point is looking for
   * Must include 'email_address' and 'status'
   * Statuses: pending = they get an email; subscribed = they don't get an email
   * Custom fields go into the 'merge_fields' as another array
   * More here: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#create-post_lists_list_id_members
   * ================
   */
  $pfb_data = array(
    'email_address' => $_POST['emailname'],
    'status'        => 'pending',
    'merge_fields'  => array(
      'FNAME'       => $_POST['firstname'],
      'LNAME'       => $_POST['lastname'],
      'ZIPCODE'     => $_POST['zipcode']
    ),
  );

  // Encode the data
  $encoded_pfb_data = json_encode($pfb_data);

  // Setup cURL sequence
  $ch = curl_init();

  /* ================
   * cURL OPTIONS
   * The tricky one here is the _USERPWD - this is how you transfer the API key over
   * _RETURNTRANSFER allows us to get the response into a variable which is nice
   * This example just POSTs, we don't edit/modify - just a simple add to a list
   * _POSTFIELDS does the heavy lifting
   * _SSL_VERIFYPEER should probably be set but I didn't do it here
   * ================
   */
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_pfb_data);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

  $results = curl_exec($ch); // store response
  $response = curl_getinfo($ch, CURLINFO_HTTP_CODE); // get HTTP CODE
  $errors = curl_error($ch); // store errors

  curl_close($ch);

  // Returns info back to jQuery .ajax or just outputs onto the page

  $results = array(
    'results' => $result_info,
    'response' => $response,
    'errors' => $errors
  );

  // Sends data back to the page OR the ajax() in your JS
  echo json_encode($results);
?>

Key things:

  1. CURLOPT_USERPWD handles the API key and Mailchimp doesn't really show you how to do this.
  2. CURLOPT_RETURNTRANSFER gives us the response in such a way that we can send it back into the HTML page with the .ajax() success handler.
  3. Use json_encodeon the data you received.

JS:

// Signup form submission
$('#pfb-signup-submission').submit(function(event) {
  event.preventDefault();

  // Get data from form and store it
  var pfbSignupFNAME = $('#pfb-signup-box-fname').val();
  var pfbSignupLNAME = $('#pfb-signup-box-lname').val();
  var pfbSignupEMAIL = $('#pfb-signup-box-email').val();
  var pfbSignupZIP = $('#pfb-signup-box-zip').val();

  // Create JSON variable of retreived data
  var pfbSignupData = {
    'firstname': pfbSignupFNAME,
    'lastname': pfbSignupLNAME,
    'email': pfbSignupEMAIL,
    'zipcode': pfbSignupZIP
  };

  // Send data to PHP script via .ajax() of jQuery
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'mailchimp-signup.php',
    data: pfbSignupData,
    success: function (results) {
      $('#pfb-signup-box-fname').hide();
      $('#pfb-signup-box-lname').hide();
      $('#pfb-signup-box-email').hide();
      $('#pfb-signup-box-zip').hide();
      $('#pfb-signup-result').text('Thanks for adding yourself to the email list. We will be in touch.');
      console.log(results);
    },
    error: function (results) {
      $('#pfb-signup-result').html('<p>Sorry but we were unable to add you into the email list.</p>');
      console.log(results);
    }
  });
});

Key things:

  1. JSON data is VERY touchy on transfer. Here, I am putting it into an array and it looks easy. If you are having problems, it is likely because of how your JSON data is structured. Check this out!
  2. The keys for your JSON data will become what you reference in the PHP _POST global variable. In this case it will be _POST['email'], _POST['firstname'], etc. But you could name them whatever you want - just remember what you name the keys of the data part of your JSON transfer is how you access them in PHP.
  3. This obviously requires jQuery ;)

No connection could be made because the target machine actively refused it 127.0.0.1

After six days I find the answer which make me crazy! The answer is disable proxy at web.config file:

<system.net>
  <defaultProxy> 
    <proxy usesystemdefault="False"/> 
  </defaultProxy>
</system.net>

Simulate a specific CURL in PostMan

1) Put https://api-server.com/API/index.php/member/signin in the url input box and choose POST from the dropdown

2) In Headers tab, enter:

Content-Type: image/jpeg

Content-Transfer-Encoding: binary

3) In Body tab, select the raw radio button and write:

{"description":"","phone":"","lastname":"","app_version":"2.6.2","firstname":"","password":"my_pass","city":"","apikey":"213","lang":"fr","platform":"1","email":"[email protected]","pseudo":"example"}

select form-data radio button and write:

key = name Value = userfile Select Text key = filename Select File and upload your profil.jpg

pass JSON to HTTP POST Request

Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)

Using library: https://github.com/request/request-promise

npm install --save request
npm install --save request-promise

client:

//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');

rp({
    method: 'POST',
    uri: 'http://localhost:3000/',
    body: {
        val1 : 1,
        val2 : 2
    },
    json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
        console.log(parsedBody);
        // POST succeeded...
    })
    .catch(function (err) {
        console.log(parsedBody);
        // POST failed...
    });

server:

var express = require('express')
    , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
    console.log(request.body);      // your JSON

    var jsonRequest = request.body;
    var jsonResponse = {};

    jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;

    response.send(jsonResponse);
});


app.listen(3000);

Plotting a fast Fourier transform in Python

So I run a functionally equivalent form of your code in an IPython notebook:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()

I get what I believe to be very reasonable output.

enter image description here

It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?

In response to the raw data and comments being posted

The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.

import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline

# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)

enter image description here

Python and JSON - TypeError list indices must be integers not str

I solved changing

readable_json['firstName']

by

readable_json[0]['firstName']

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

Just add:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Simple C example of doing an HTTP POST and consuming the response

A message has a header part and a message body separated by a blank line. The blank line is ALWAYS needed even if there is no message body. The header starts with a command and has additional lines of key value pairs separated by a colon and a space. If there is a message body, it can be anything you want it to be.

Lines in the header and the blank line at the end of the header must end with a carraige return and linefeed pair (see HTTP header line break style) so that's why those lines have \r\n at the end.

A URL has the form of http://host:port/path?query_string

There are two main ways of submitting a request to a website:

  • GET: The query string is optional but, if specified, must be reasonably short. Because of this the header could just be the GET command and nothing else. A sample message could be:

    GET /path?query_string HTTP/1.0\r\n
    \r\n
    
  • POST: What would normally be in the query string is in the body of the message instead. Because of this the header needs to include the Content-Type: and Content-Length: attributes as well as the POST command. A sample message could be:

    POST /path HTTP/1.0\r\n
    Content-Type: text/plain\r\n
    Content-Length: 12\r\n
    \r\n
    query_string
    

So, to answer your question: if the URL you are interested in POSTing to is http://api.somesite.com/apikey=ARG1&command=ARG2 then there is no body or query string and, consequently, no reason to POST because there is nothing to put in the body of the message and so nothing to put in the Content-Type: and Content-Length:

I guess you could POST if you really wanted to. In that case your message would look like:

POST /apikey=ARG1&command=ARG2 HTTP/1.0\r\n
\r\n

So to send the message the C program needs to:

  • create a socket
  • lookup the IP address
  • open the socket
  • send the request
  • wait for the response
  • close the socket

The send and receive calls won't necessarily send/receive ALL the data you give them - they will return the number of bytes actually sent/received. It is up to you to call them in a loop and send/receive the remainder of the message.

What I did not do in this sample is any sort of real error checking - when something fails I just exit the program. Let me know if it works for you:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        80;
    char *host =        "api.somesite.com";
    char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }

    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]);
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    return 0;
}

Like the other answer pointed out, 4096 bytes is not a very big response. I picked that number at random assuming that the response to your request would be short. If it can be big you have two choices:

  • read the Content-Length: header from the response and then dynamically allocate enough memory to hold the whole response.
  • write the response to a file as the pieces arrive

Additional information to answer the question asked in the comments:

What if you want to POST data in the body of the message? Then you do need to include the Content-Type: and Content-Length: headers. The Content-Length: is the actual length of everything after the blank line that separates the header from the body.

Here is a sample that takes the following command line arguments:

  • host
  • port
  • command (GET or POST)
  • path (not including the query data)
  • query data (put into the query string for GET and into the body for POST)
  • list of headers (Content-Length: is automatic if using POST)

So, for the original question you would run:

a.out api.somesite.com 80 GET "/apikey=ARG1&command=ARG2"

And for the question asked in the comments you would run:

a.out api.somesite.com 80 POST / "name=ARG1&value=ARG2" "Content-Type: application/x-www-form-urlencoded"

Here is the code:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

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

    /* first where are we going to send it? */
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total, message_size;
    char *message, response[4096];

    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }

    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(argv[4]);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
        message_size+=strlen("%s %s HTTP/1.0\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(argv[4]);                         /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }

    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/",                 /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"");                 /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/");                /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            strlen(argv[4])>0?argv[4]:"/");                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }

    /* What are we going to send? */
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    free(message);
    return 0;
}

Find column whose name contains a specific string

You can also use df.columns[df.columns.str.contains(pat = 'spike')]

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)

colNames = df.columns[df.columns.str.contains(pat = 'spike')] 

print(colNames)

This will output the column names: 'spike-2', 'spiked-in'

More about pandas.Series.str.contains.

TypeError: ObjectId('') is not JSON serializable

in my case I needed something like this:

class JsonEncoder():
    def encode(self, o):
        if '_id' in o:
            o['_id'] = str(o['_id'])
        return o

How to use MapView in android using google map V2?

More complete sample from here and here.

Or you can check out my layout sample. p.s no need to put API key in the map view.

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
            android:id="@+id/map_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />

    <ListView android:id="@+id/nearby_lv"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:layout_weight="1"
            />

</LinearLayout>

This app won't run unless you update Google Play Services (via Bazaar)

I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110 and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.

I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.

Missing styles. Is the correct theme chosen for this layout?

With reference to the answer provided by @Benno: Instead of changing to a specific theme, you can simply choose 'DeviceDefault' from the theme menu. This should choose the theme most compatible with the emulated device.

uncaught syntaxerror unexpected token U JSON

The parameter for the JSON.parse may be returning nothing (i.e. the value given for the JSON.parse is undefined)!

It happened to me while I was parsing the Compiled solidity code from an xyz.sol file.

import web3 from './web3';
import xyz from './build/xyz.json';

const i = new web3.eth.Contract(
  JSON.parse(xyz.interface),
  '0x99Fd6eFd4257645a34093E657f69150FEFf7CdF5'
);

export default i;

which was misspelled as

JSON.parse(xyz.intereface)

which was returning nothing!

Using JSON POST Request

An example using jQuery is below. Hope this helps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "https://example.com/api/",
        type: "POST",
        data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 

Firebug debug process

Firebug XHR debug process

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

PHP cURL vs file_get_contents

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

fopen() with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.

Delete all local git branches

For this purpose, you can use git-extras

$ git delete-merged-branches
Deleted feature/themes (was c029ab3).
Deleted feature/live_preview (was a81b002).
Deleted feature/dashboard (was 923befa).

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

How to Troubleshoot Intermittent SQL Timeout Errors

The issue is because of a bad query the time to executing query is taking more than 60 seconds or a Lock on the Table

The issue looks like a deadlock is occurring; we have queries which are blocking the queries to complete in time. The default timeout for a query is 60 secs and beyond that we will have the SQLException for timeout.

Please check the SQL Server logs for deadlocks. The other way to solve the issue to to increase the Timeout on the Command Object (Temp Solution).

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

Place API key in Headers or URL

I would not put the key in the url, as it does violate this loose 'standard' that is REST. However, if you did, I would place it in the 'user' portion of the url.

eg: http://[email protected]/myresource/myid

This way it can also be passed as headers with basic-auth.

How to create a CPU spike with a bash command

Here is a program that you can download Here

Install easily on your Linux system

./configure
make
make install

and launch it in a simple command line

stress -c 40

to stress all your CPUs (however you have) with 40 threads each running a complex sqrt computation on a ramdomly generated numbers.

You can even define the timeout of the program

stress -c 40 -timeout 10s

unlike the proposed solution with the dd command, which deals essentially with IO and therefore doesn't really overload your system because working with data.

The stress program really overloads the system because dealing with computation.

Python, Matplotlib, subplot: How to set the axis range?

If you have multiple subplots, i.e.

fig, ax = plt.subplots(4, 2)

You can use the same y limits for all of them. It gets limits of y ax from first plot.

plt.setp(ax, ylim=ax[0,0].get_ylim())

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.

Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater.

The code is the following, where this is an Activity:

final LayoutInflater factory = getLayoutInflater();

final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);

landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);

You need to get the inflater for this context, access the root view through the inflate method and finally call findViewById on the root view of the layout.

Hope this is useful for someone! Bye

Set new id with jQuery

Did you try

$(this).val('test');

instead of

$(this).attr('value', 'test');

val() is generally easier, since the attribute you need to change may be different on different DOM elements.

How do I make the method return type generic?

Not really, because as you say, the compiler only knows that callFriend() is returning an Animal, not a Dog or Duck.

Can you not add an abstract makeNoise() method to Animal that would be implemented as a bark or quack by its subclasses?

What's the best way to check if a String represents an integer in Java?

You can also use the Scanner class, and use hasNextInt() - and this allows you to test for other types, too, like floats, etc.

How to determine total number of open/active connections in ms sql server 2005

This shows the number of connections per each DB:

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame

And this gives the total:

SELECT 
    COUNT(dbid) as TotalConnections
FROM
    sys.sysprocesses
WHERE 
    dbid > 0

If you need more detail, run:

sp_who2 'Active'

Note: The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)

Install Visual Studio 2013 on Windows 7

your log files shows it is stopping on error "0x8004C000"

From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):

Setup Status
Block

Restart not required
0x80044000 [-2147205120]

Restart required
0x8004C000 [-2147172352]

Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).

How do I negate a test with regular expressions in a bash script?

You can also put the exclamation mark inside the brackets:

if [[ ! $PATH =~ $temp ]]

but you should anchor your pattern to reduce false positives:

temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]

which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

php foreach with multidimensional array

I know this is quite an old answer. Here is a faster solution without using foreach:

Use array_column

print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'

Also you can check before executing the above operation

if(array_key_exists('firstname', $array)){
   print_r(array_column($array, 'firstname'));
}

reCAPTCHA ERROR: Invalid domain for site key

There is another point must be noted before regenerating keys that resolve 90% issue.

for example your xampp directory is C:\xampp

and htdocs folder is C:\xampp\htdocs

we want to open page called: example-cap.html and page is showing error "invalid domain for site key"

USE YOUR LOCALHOST ADDRESS in browser address like:

localhost/example-cap.html

this will resolve your issue

DONOT USE ADDRESS c:\xampp\htdocs\example-cap.html this will generate error

remove all variables except functions

The posted setdiff answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).

lstype<-function(type='closure'){ 
    inlist<-ls(.GlobalEnv)
    if (type=='function') type <-'closure'
    typelist<-sapply(sapply(inlist,get),typeof)
    return(names(typelist[typelist==type]))
}

How to present UIActionSheet iOS Swift?

Updated for Swift 3.x, Swift 4.x, Swift 5.x

// create an actionSheet
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

// create an action
let firstAction: UIAlertAction = UIAlertAction(title: "First Action", style: .default) { action -> Void in

    print("First Action pressed")
}

let secondAction: UIAlertAction = UIAlertAction(title: "Second Action", style: .default) { action -> Void in

    print("Second Action pressed")
}

let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }

// add actions
actionSheetController.addAction(firstAction)
actionSheetController.addAction(secondAction)
actionSheetController.addAction(cancelAction)


// present an actionSheet...
// present(actionSheetController, animated: true, completion: nil)   // doesn't work for iPad

actionSheetController.popoverPresentationController?.sourceView = yourSourceViewName // works for both iPhone & iPad

present(actionSheetController, animated: true) {
    print("option menu presented")
}

enter image description here

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

Note that some zip programs have trouble unzipping a CRX like sathish described - if this is the case, try using 7-Zip - http://www.7-zip.org/

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

Disable native datepicker in Google Chrome

If you have misused <input type="date" /> you can probably use:

$('input[type="date"]').attr('type','text');

after they have loaded to turn them into text inputs. You'll need to attach your custom datepicker first:

$('input[type="date"]').datepicker().attr('type','text');

Or you could give them a class:

$('input[type="date"]').addClass('date').attr('type','text');

How to force deletion of a python object?

In general, to make sure something happens no matter what, you use

from exceptions import NameError

try:
    f = open(x)
except ErrorType as e:
    pass # handle the error
finally:
    try:
        f.close()
    except NameError: pass

finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

The general way to make sure a file is closed is to use a "context manager".

http://docs.python.org/reference/datamodel.html#context-managers

with open(x) as f:
    # do stuff

This will automatically close f.

For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

Objects are NOT created by __init__, they're created by __new__.

http://docs.python.org/reference/datamodel.html#object.new

When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

Edit: Corrected when deletion happens if a reference count decreases to zero.

How can I count text lines inside an DOM element? Can I?

If the div's size is dependent on the content (which I assume to be the case from your description) then you can retrieve the div's height using:

var divHeight = document.getElementById('content').offsetHeight;

And divide by the font line height:

document.getElementById('content').style.lineHeight;

Or to get the line height if it hasn't been explicitly set:

var element = document.getElementById('content');
document.defaultView.getComputedStyle(element, null).getPropertyValue("lineHeight");

You will also need to take padding and inter-line spacing into account.

EDIT

Fully self-contained test, explicitly setting line-height:

_x000D_
_x000D_
function countLines() {_x000D_
   var el = document.getElementById('content');_x000D_
   var divHeight = el.offsetHeight_x000D_
   var lineHeight = parseInt(el.style.lineHeight);_x000D_
   var lines = divHeight / lineHeight;_x000D_
   alert("Lines: " + lines);_x000D_
}
_x000D_
<body onload="countLines();">_x000D_
  <div id="content" style="width: 80px; line-height: 20px">_x000D_
    hello how are you? hello how are you? hello how are you? hello how are you?_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

What is a quick way to force CRLF in C# / .NET?

Simple variant:

Regex.Replace(input, @"\r\n|\r|\n", "\r\n")

For better performance:

static Regex newline_pattern = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
[...]
    newline_pattern.Replace(input, "\r\n");

Remap values in pandas column with a dict

There is a bit of ambiguity in your question. There are at least three two interpretations:

  1. the keys in di refer to index values
  2. the keys in di refer to df['col1'] values
  3. the keys in di refer to index locations (not the OP's question, but thrown in for fun.)

Below is a solution for each case.


Case 1: If the keys of di are meant to refer to index values, then you could use the update method:

df['col1'].update(pd.Series(di))

For example,

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':['w', 10, 20],
                   'col2': ['a', 30, np.nan]},
                  index=[1,2,0])
#   col1 col2
# 1    w    a
# 2   10   30
# 0   20  NaN

di = {0: "A", 2: "B"}

# The value at the 0-index is mapped to 'A', the value at the 2-index is mapped to 'B'
df['col1'].update(pd.Series(di))
print(df)

yields

  col1 col2
1    w    a
2    B   30
0    A  NaN

I've modified the values from your original post so it is clearer what update is doing. Note how the keys in di are associated with index values. The order of the index values -- that is, the index locations -- does not matter.


Case 2: If the keys in di refer to df['col1'] values, then @DanAllan and @DSM show how to achieve this with replace:

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':['w', 10, 20],
                   'col2': ['a', 30, np.nan]},
                  index=[1,2,0])
print(df)
#   col1 col2
# 1    w    a
# 2   10   30
# 0   20  NaN

di = {10: "A", 20: "B"}

# The values 10 and 20 are replaced by 'A' and 'B'
df['col1'].replace(di, inplace=True)
print(df)

yields

  col1 col2
1    w    a
2    A   30
0    B  NaN

Note how in this case the keys in di were changed to match values in df['col1'].


Case 3: If the keys in di refer to index locations, then you could use

df['col1'].put(di.keys(), di.values())

since

df = pd.DataFrame({'col1':['w', 10, 20],
                   'col2': ['a', 30, np.nan]},
                  index=[1,2,0])
di = {0: "A", 2: "B"}

# The values at the 0 and 2 index locations are replaced by 'A' and 'B'
df['col1'].put(di.keys(), di.values())
print(df)

yields

  col1 col2
1    A    a
2   10   30
0    B  NaN

Here, the first and third rows were altered, because the keys in di are 0 and 2, which with Python's 0-based indexing refer to the first and third locations.

How to show soft-keyboard when edittext is focused

Inside your manifest:

android:windowSoftInputMode="stateAlwaysVisible" - initially launched keyboard. android:windowSoftInputMode="stateAlwaysHidden" - initially hidden keyboard.

I like to use also "adjustPan" because when the keyboard launches then the screen auto adjusts.

 <activity
      android:name="YourActivity"
      android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>

Java, How to implement a Shift Cipher (Caesar Cipher)

The warning is due to you attempting to add an integer (int shift = 3) to a character value. You can change the data type to char if you want to avoid that.

A char is 16 bits, an int is 32.

char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;

As an aside, you can simplify the following:

char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'}; 

To:

char[] message = "onceuponatime".toCharArray();

Type List vs type ArrayList in Java

It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

This way, you have to change only one line if you decide to use a TreeSet instead.

Also, methods that operate on sets should specify parameters of type Set:

public static void print(Set<String> s)

Then the method can be used for all set implementations.

In theory, we should make the same recommendation for linked lists, namely to save LinkedList references in variables of type List. However, in the Java library, the List interface is common to both the ArrayList and the LinkedList class. In particular, it has get and set methods for random access, even though these methods are very inefficient for linked lists.

You can’t write efficient code if you don’t know whether random access is efficient or not.

This is plainly a serious design error in the standard library, and I cannot recommend using the List interface for that reason.

To see just how embarrassing that error is, have a look at the source code for the binarySearch method of the Collections class. That method takes a List parameter, but binary search makes no sense for a linked list. The code then clumsily tries to discover whether the list is a linked list, and then switches to a linear search!

The Set interface and the Map interface, are well designed, and you should use them.

Oracle listener not running and won't start

I encountered the same problem and reason being: Mine is a personal windows PC. And i have modified the computer name and the same did not reflect in listener.ora. Updating ORACLE_HOME\network\ADMIN\listener.ora with updated host name fixed the issue.

Use CASE statement to check if column exists in table - SQL Server

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

How do I concatenate strings with variables in PowerShell?

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name

Visual Studio Post Build Event - Copy to Relative Directory Location

Here is what you want to put in the project's Post-build event command line:

copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"

EDIT: Or if your target name is different than the Project Name.

copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"

git pull from master into the development branch

git pull origin master --allow-unrelated-histories

You might want to use this if your histories doesnt match and want to merge it anyway..

refer here

Simple IEnumerator use (with example)

Here is the documentation on IEnumerator. They are used to get the values of lists, where the length is not necessarily known ahead of time (even though it could be). The word comes from enumerate, which means "to count off or name one by one".

IEnumerator and IEnumerator<T> is provided by all IEnumerable and IEnumerable<T> interfaces (the latter providing both) in .NET via GetEnumerator(). This is important because the foreach statement is designed to work directly with enumerators through those interface methods.

So for example:

IEnumerator enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
{
    object item = enumerator.Current;
    // Perform logic on the item
}

Becomes:

foreach(object item in enumerable)
{
    // Perform logic on the item
}

As to your specific scenario, almost all collections in .NET implement IEnumerable. Because of that, you can do the following:

public IEnumerator Enumerate(IEnumerable enumerable)
{
    // List implements IEnumerable, but could be any collection.
    List<string> list = new List<string>(); 

    foreach(string value in enumerable)
    {
        list.Add(value + "roxxors");
    }
    return list.GetEnumerator();
}

Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

Aligning a button to the center

For me it worked using flexbox, which is in my opinion the cleanest solution.

Add a css class around the parent div / element with :

.parent {
display: flex;
}

and for the button use:

.button {
justify-content: center;
}

You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.

If this is not working, try :

#wrapper {
    display:flex;
    justify-content: center;
}

How to change the style of alert box?

I tried to use script for alert() boxes styles using java-script.Here i used those JS and CSS.

Refer this coding JS functionality.

var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";

if(document.getElementById) {
    window.alert = function(txt) {
        createCustomAlert(txt);
    }
}

function createCustomAlert(txt) {
    d = document;

    if(d.getElementById("modalContainer")) return;

    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
    mObj.id = "modalContainer";
    mObj.style.height = d.documentElement.scrollHeight + "px";

    alertObj = mObj.appendChild(d.createElement("div"));
    alertObj.id = "alertBox";
    if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
    alertObj.style.visiblity="visible";

    h1 = alertObj.appendChild(d.createElement("h1"));
    h1.appendChild(d.createTextNode(ALERT_TITLE));

    msg = alertObj.appendChild(d.createElement("p"));
    //msg.appendChild(d.createTextNode(txt));
    msg.innerHTML = txt;

    btn = alertObj.appendChild(d.createElement("a"));
    btn.id = "closeBtn";
    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
    btn.href = "#";
    btn.focus();
    btn.onclick = function() { removeCustomAlert();return false; }

    alertObj.style.display = "block";

}

function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

And CSS for alert() Box

#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    position:absolute;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:10000;
    background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}

#alertBox {
    position:relative;
    width:300px;
    min-height:100px;
    margin-top:50px;
    border:1px solid #666;
    background-color:#fff;
    background-repeat:no-repeat;
    background-position:20px 30px;
}

#modalContainer > #alertBox {
    position:fixed;
}

#alertBox h1 {
    margin:0;
    font:bold 0.9em verdana,arial;
    background-color:#3073BB;
    color:#FFF;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;
}

#alertBox p {
    font:0.7em verdana,arial;
    height:50px;
    padding-left:5px;
    margin-left:55px;
}

#alertBox #closeBtn {
    display:block;
    position:relative;
    margin:5px auto;
    padding:7px;
    border:0 none;
    width:70px;
    font:0.7em verdana,arial;
    text-transform:uppercase;
    text-align:center;
    color:#FFF;
    background-color:#357EBD;
    border-radius: 3px;
    text-decoration:none;
}

/* unrelated styles */

#mContainer {
    position:relative;
    width:600px;
    margin:auto;
    padding:5px;
    border-top:2px solid #000;
    border-bottom:2px solid #000;
    font:0.7em verdana,arial;
}

h1,h2 {
    margin:0;
    padding:4px;
    font:bold 1.5em verdana;
    border-bottom:1px solid #000;
}

code {
    font-size:1.2em;
    color:#069;
}

#credits {
    position:relative;
    margin:25px auto 0px auto;
    width:350px; 
    font:0.7em verdana;
    border-top:1px solid #000;
    border-bottom:1px solid #000;
    height:90px;
    padding-top:4px;
}

#credits img {
    float:left;
    margin:5px 10px 5px 0px;
    border:1px solid #000000;
    width:80px;
    height:79px;
}

.important {
    background-color:#F5FCC8;
    padding:2px;
}

code span {
    color:green;
}

And HTML file:

<input type="button" value = "Test the alert" onclick="alert('Alert this pages');" />

And also View this DEMO: JSFIDDLE and DEMO RESULT IMAGE

enter image description here

How to instantiate a File object in JavaScript?

Update

BlobBuilder has been obsoleted see how you go using it, if you're using it for testing purposes.

Otherwise apply the below with migration strategies of going to Blob, such as the answers to this question.

Use a Blob instead

As an alternative there is a Blob that you can use in place of File as it is what File interface derives from as per W3C spec:

interface File : Blob {
    readonly attribute DOMString name;
    readonly attribute Date lastModifiedDate;
};

The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Create the Blob

Using the BlobBuilder like this on an existing JavaScript method that takes a File to upload via XMLHttpRequest and supplying a Blob to it works fine like this:

var BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder;
var bb = new BlobBuilder();

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://jsfiddle.net/img/logo.png', true);

xhr.responseType = 'arraybuffer';

bb.append(this.response); // Note: not xhr.responseText

//at this point you have the equivalent of: new File()
var blob = bb.getBlob('image/png');

/* more setup code */
xhr.send(blob);

Extended example

The rest of the sample is up on jsFiddle in a more complete fashion but will not successfully upload as I can't expose the upload logic in a long term fashion.

How do I convert Long to byte[] and back in java

 public static long bytesToLong(byte[] bytes) {
        if (bytes.length > 8) {
            throw new IllegalMethodParameterException("byte should not be more than 8 bytes");

        }
        long r = 0;
        for (int i = 0; i < bytes.length; i++) {
            r = r << 8;
            r += bytes[i];
        }

        return r;
    }



public static byte[] longToBytes(long l) {
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        while (l != 0) {
            bytes.add((byte) (l % (0xff + 1)));
            l = l >> 8;
        }
        byte[] bytesp = new byte[bytes.size()];
        for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
            bytesp[j] = bytes.get(i);
        }
        return bytesp;
    }

Removing leading and trailing spaces from a string

void removeSpaces(string& str)
{
    /* remove multiple spaces */
    int k=0;
    for (int j=0; j<str.size(); ++j)
    {
            if ( (str[j] != ' ') || (str[j] == ' ' && str[j+1] != ' ' ))
            {
                    str [k] = str [j];
                    ++k;
            }

    }
    str.resize(k);

    /* remove space at the end */   
    if (str [k-1] == ' ')
            str.erase(str.end()-1);
    /* remove space at the begin */
    if (str [0] == ' ')
            str.erase(str.begin());
}

Is it possible to set an object to null?

You want to check if an object is NULL/empty. Being NULL and empty are not the same. Like Justin and Brian have already mentioned, in C++ NULL is an assignment you'd typically associate with pointers. You can overload operator= perhaps, but think it through real well if you actually want to do this. Couple of other things:

  1. In C++ NULL pointer is very different to pointer pointing to an 'empty' object.
  2. Why not have a bool IsEmpty() method that returns true if an object's variables are reset to some default state? Guess that might bypass the NULL usage.
  3. Having something like A* p = new A; ... p = NULL; is bad (no delete p) unless you can ensure your code will be garbage collected. If anything, this'd lead to memory leaks and with several such leaks there's good chance you'd have slow code.
  4. You may want to do this class Null {}; Null _NULL; and then overload operator= and operator!= of other classes depending on your situation.

Perhaps you should post us some details about the context to help you better with option 4.

Arpan

Redirect after Login on WordPress

The Theme My Login plugin may help - it allows you to redirect users of specific roles to specific pages.

How to use nan and inf in C?

You can test if your implementation has it:

#include <math.h>
#ifdef NAN
/* NAN is supported */
#endif
#ifdef INFINITY
/* INFINITY is supported */
#endif

The existence of INFINITY is guaranteed by C99 (or the latest draft at least), and "expands to a constant expression of type float representing positive or unsigned infinity, if available; else to a positive constant of type float that overflows at translation time."

NAN may or may not be defined, and "is defined if and only if the implementation supports quiet NaNs for the float type. It expands to a constant expression of type float representing a quiet NaN."

Note that if you're comparing floating point values, and do:

a = NAN;

even then,

a == NAN;

is false. One way to check for NaN would be:

#include <math.h>
if (isnan(a)) { ... }

You can also do: a != a to test if a is NaN.

There is also isfinite(), isinf(), isnormal(), and signbit() macros in math.h in C99.

C99 also has nan functions:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

(Reference: n1256).

Docs INFINITY Docs NAN

Jackson enum Serializing and DeSerializer

In the context of an enum, using @JsonValue now (since 2.0) works for serialization and deserialization.

According to the jackson-annotations javadoc for @JsonValue:

NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.

So having the Event enum annotated just as above works (for both serialization and deserialization) with jackson 2.0+.

Open Form2 from Form1, close Form1 from Form2

Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.

VirtualBox error "Failed to open a session for the virtual machine"

Killing VM process dint work in my case.

Right click on the VM and click on "Discard Saved State".

 Right click on the VM and click on "Discard Saved State".

This worked for me.

Error - trustAnchors parameter must be non-empty

None of solutions that I found on the Internet worked, but a modified version of Peter Kriens's answer seems to do the job.

First find your Java folder by running /usr/libexec/java_home. For me it was the 1.6.0.jdk version. Then go to its lib/security subfolder (for me /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security).

Then delete the cacerts file if there is one already and search for one on the system with sudo find / -name "cacerts". It found multiple items for me, in versions of Xcode or other applications that I had installed, but also at /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts which I chose.

Use that file and make a symbolic link to it (while inside the Java folder from before), sudo ln -fsh "/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts", and it should work.

I have both - Java from Apple's 2017-001 download (https://support.apple.com/kb/dl1572 - I assume that's where the correct certificates are from) and Oracle's one installed on Mac OS X v10.12 (Sierra).

Swift: Sort array of objects alphabetically

In the closure you pass to sort, compare the properties you want to sort by. Like this:

movieArr.sorted { $0.name < $1.name }

or the following in the cases that you want to bypass cases:

movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }

Sidenote: Typically only types start with an uppercase letter; I'd recommend using name and date, not Name and Date.


Example, in a playground:

class Movie {
    let name: String
    var date: Int?

    init(_ name: String) {
        self.name = name
    }
}

var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")

let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies

sortedMovies will be in the order [movieA, movieB, movieC]

Swift5 Update

channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
            let channelName1 = channel1.name
            let channelName2 = channel2.name
            return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)

Difference between Fact table and Dimension table?

Dimension table : It is nothing but we can maintains information about the characterized date called as Dimension table.

Example : Time Dimension , Product Dimension.

Fact Table : It is nothing but we can maintains information about the metrics or precalculation data.

Example : Sales Fact, Order Fact.

Star schema : one fact table link with dimension table form as a Start Schema.

enter image description here

Is mathematics necessary for programming?

As a self taught programmer who started working on games about 30 years ago I would definitely say you need to get as much math as you can. Things like matrices, quaternions, ray tracing, particle systems, physics engines and such do require a good level of math comprehension and I only wish that I had learned all those things much earlier.

Docker - Ubuntu - bash: ping: command not found

I have used the statement below on debian 10

apt-get install iputils-ping

Resize image with javascript canvas (smoothly)

I don't understand why nobody is suggesting createImageBitmap.

createImageBitmap(
    document.getElementById('image'), 
    { resizeWidth: 300, resizeHeight: 234, resizeQuality: 'high' }
)
.then(imageBitmap => 
    document.getElementById('canvas').getContext('2d').drawImage(imageBitmap, 0, 0)
);

works beautifully (assuming you set ids for image and canvas).

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Can I use GDB to debug a running process?

You can attach to a running process with gdb -p PID.

How can I get LINQ to return the object which has the max value for a given property?

try this:

var maxid = from i in items
            group i by i.clientid int g
            select new { id = g.Max(i=>i.ID }

How to write a file or data to an S3 object using boto3

it is worth mentioning smart-open that uses boto3 as a back-end.

smart-open is a drop-in replacement for python's open that can open files from s3, as well as ftp, http and many other protocols.

for example

from smart_open import open
import json
with open("s3://your_bucket/your_key.json", 'r') as f:
    data = json.load(f)

The aws credentials are loaded via boto3 credentials, usually a file in the ~/.aws/ dir or an environment variable.

How to get json key and value in javascript?

you have parse that Json string using JSON.parse()

..
}).done(function(data){
    obj = JSON.parse(data);
    alert(obj.jobtitel);
});

Change tab bar item selected color in a storyboard

You can subclass the UITabBarController, and replace the one with it in the storyboard. In your viewDidLoad implementation of subclass call this:

[self.tabBar setTintColor:[UIColor greenColor]];

How to increment a number by 2 in a PHP For Loop

You should do it like this:

 for ($i=1; $i <=10; $i+=2) 
{ 
    echo $i.'<br>';
}

"+=" you can increase your variable as much or less you want. "$i+=5" or "$i+=.5"

Lazy Method for Reading Big File in Python?

f = ... # file-like object, i.e. supporting read(size) function and 
        # returning empty string '' when there is nothing to read

def chunked(file, chunk_size):
    return iter(lambda: file.read(chunk_size), '')

for data in chunked(f, 65536):
    # process the data

UPDATE: The approach is best explained in https://stackoverflow.com/a/4566523/38592

Getting value from JQUERY datepicker

You could remove the name attribute of this input, so it won't be submited.

To access the value of this controll:

$("div#someID").datepicker( "getDate" )

and your may have a look at the document in http://jqueryui.com/demos/datepicker/

ios app maximum memory budget

I created one more list by sorting Jaspers list by device RAM (I made my own tests with Split's tool and fixed some results - check my comments in Jaspers thread).

device RAM: percent range to crash

  • 256MB: 49% - 51%
  • 512MB: 53% - 63%
  • 1024MB: 57% - 68%
  • 2048MB: 68% - 69%
  • 3072MB: 63% - 66%
  • 4096MB: 77%
  • 6144MB: 81%

Special cases:

  • iPhone X (3072MB): 50%
  • iPhone XS/XS Max (4096MB): 55%
  • iPhone XR (3072MB): 63%
  • iPhone 11/11 Pro Max (4096MB): 54% - 55%

Device RAM can be read easily:

[NSProcessInfo processInfo].physicalMemory

From my experience it is safe to use 45% for 1GB devices, 50% for 2/3GB devices and 55% for 4GB devices. Percent for macOS can be a bit bigger.

What's the difference between a POST and a PUT HTTP REQUEST?

Define operations in terms of HTTP methods

The HTTP protocol defines a number of methods that assign semantic meaning to a request. The common HTTP methods used by most RESTful web APIs are:

GET retrieves a representation of the resource at the specified URI. The body of the response message contains the details of the requested resource.

POST creates a new resource at the specified URI. The body of the request message provides the details of the new resource. Note that POST can also be used to trigger operations that don't actually create resources.

PUT either creates or replaces the resource at the specified URI. The body of the request message specifies the resource to be created or updated.

PATCH performs a partial update of a resource. The request body specifies the set of changes to apply to the resource.

DELETE removes the resource at the specified URI.

The effect of a specific request should depend on whether the resource is a collection or an individual item. The following table summarizes the common conventions adopted by most RESTful implementations using the e-commerce example. Not all of these requests might be implemented—it depends on the specific scenario.

Resource POST GET PUT DELETE
/customers Create a new customer Retrieve all customers Bulk update of customers Remove all customers
/customers/1 Error Retrieve the details for customer 1 Update the details of customer 1 if it exists Remove customer 1
/customers/1/orders Create a new order for customer 1 Retrieve all orders for customer 1 Bulk update of orders for customer 1 Remove all orders for customer 1

The differences between POST, PUT, and PATCH can be confusing.

A POST request creates a resource. The server assigns a URI for the new resource and returns that URI to the client. In the REST model, you frequently apply POST requests to collections. The new resource is added to the collection. A POST request can also be used to submit data for processing to an existing resource, without any new resource being created.

A PUT request creates a resource or updates an existing resource. The client specifies the URI for the resource. The request body contains a complete representation of the resource. If a resource with this URI already exists, it is replaced. Otherwise, a new resource is created, if the server supports doing so. PUT requests are most frequently applied to resources that are individual items, such as a specific customer, rather than collections. A server might support updates but not creation via PUT. Whether to support creation via PUT depends on whether the client can meaningfully assign a URI to a resource before it exists. If not, then use POST to create resources and PUT or PATCH to update.

A PATCH request performs a partial update to an existing resource. The client specifies the URI for the resource. The request body specifies a set of changes to apply to the resource. This can be more efficient than using PUT, because the client only sends the changes, not the entire representation of the resource. Technically PATCH can also create a new resource (by specifying a set of updates to a "null" resource), if the server supports this.

PUT requests must be idempotent. If a client submits the same PUT request multiple times, the results should always be the same (the same resource will be modified with the same values). POST and PATCH requests are not guaranteed to be idempotent.

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

How to add ID property to Html.BeginForm() in asp.net mvc?

In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)

Means you should use like this :

Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

So, it worked in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "signupform" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}

Windows Scipy Install: No Lapack/Blas Resources Found

If you are working with Windows and Visual Studio 2015

Enter the following commands

  • "conda install numpy"
  • "conda install pandas"
  • "conda install scipy"

smtpclient " failure sending mail"

what error do you get is it a SmtpFailedrecipientException? if so you can check the innerexceptions list and view the StatusCode to get more information. the link below has some good information

MSDN

Edit for the new information

Thisis a problem with finding your SMTP server from what I can see, though you say that it only happens on some emails. Are you using more than one smtp server and if so maybe you can tract the issue down to one in particular, if not it may be that the speed/amount of emails you are sending is causing your smtp server some issue.

WCF error: The caller was not authenticated by the service

If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."

<bindings>
    <basicHttpBinding>
        <binding name="MyBasicHttpBinding">
            <security mode="None">
                <transport clientCredentialType="None" />
            </security>
        </binding>
    </basicHttpBinding>
</bindings>
<services>
    <service behaviorConfiguration="MyServiceBehavior" name="MyService">
        <endpoint 
            binding="basicHttpBinding" 
            bindingConfiguration="MyBasicHttpBinding"
            name="basicEndPoint"    
            contract="IMyService" 
        />
</service>

Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Try resetting your password for the email used. Had similar issue, and got it fixed only after changing password.

Are there any Open Source alternatives to Crystal Reports?

You can use jasper report.

iReport is a very effective tool to develop jasper reports.

It supports almost all the facilities provided by crystal report like formatting, grouping, creation of charts etc.

Refer the link for tutorial:

http://www.opentaps.org/docs/index.php/Tutorial_iReports

Play audio from a stream using C#

Bass can do just this. Play from Byte[] in memory or a through file delegates where you return the data, so with that you can play as soon as you have enough data to start the playback..

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

Java array reflection: isArray vs. instanceof

There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.

If it confuses readers of your code (because String[] instanceof Object[] is true), you may want to use the first to be more explicit if code reviewers keep asking about it.

Using intents to pass data between activities

I like to use this clean code to pass one value only:

startActivity(new Intent(context, YourActivity.class).putExtra("key","value"));

This make more simple to write and understandable code.

How do you modify the web.config appSettings at runtime?

2012 This is a better solution for this scenario (tested With Visual Studio 2008):

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();

Update 2018 =>
Tested in vs 2015 - Asp.net MVC5

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();

if u need to checking element exist, use this code:

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();

Android: Quit application when press back button

Use this code very simple solution

 @Override
    public void onBackPressed() {
      super.onBackPressed(); // this line close the  app on backpress
 }

enable cors in .htaccess

I tried @abimelex solution, but in Slim 3.0, mapping the OPTIONS requests goes like:

$app = new \Slim\App();
$app->options('/books/{id}', function ($request, $response, $args) {
    // Return response headers
});

https://www.slimframework.com/docs/objects/router.html#options-route

Foreign key referring to primary keys across multiple tables?

Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:

Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".

Then you translate this higher-level description to three tables: employees, employees_ce and employees_sn:

  • employees(id, name)
  • employees_ce(id, ce-specific stuff)
  • employees_sn(id, sn-specific stuff)

Since all employees are employees (duh!), every employee will have a row in the employees table. "ce" employees also have a row in the employees_ce table, and "sn" employees also have a row in the employees_sn table. employees_ce.id is a foreign key to employees.id, just as employees_sn.id is.

To refer to an employee of any kind (ce or sn), refer to the employees table. That is, the foreign key you had trouble with should refer to that table!

How to obtain a Thread id in Python?

I saw examples of thread IDs like this:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

The threading module docs lists name attribute as well:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.

Why isn't .ico file defined when setting window's icon?

Got stuck on that too...

Finally managed to set the icon i wanted using the following code:

from tkinter import *
root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='resources/icon.png'))

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

How to convert CSV file to multiline JSON?

I took @SingleNegationElimination's response and simplified it into a three-liner that can be used in a pipeline:

import csv
import json
import sys

for row in csv.DictReader(sys.stdin):
    json.dump(row, sys.stdout)
    sys.stdout.write('\n')

jQuery: Get height of hidden element in jQuery

One workaround is to create a parent div outside the element you want to get the height of, apply a height of '0' and hide any overflow. Next, take the height of the child element and remove the overflow property of the parent.

_x000D_
_x000D_
var height = $("#child").height();_x000D_
// Do something here_x000D_
$("#parent").append(height).removeClass("overflow-y-hidden");
_x000D_
.overflow-y-hidden {_x000D_
  height: 0px;_x000D_
  overflow-y: hidden;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="parent" class="overflow-y-hidden">_x000D_
  <div id="child">_x000D_
    This is some content I would like to get the height of!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Please update your php.ini with

default_socket_timeout = 120

You can create your own php.ini if php is installed a CGI instead of a Apache module

How can I reverse a list in Python?

ORGANIZING VALUES:

In Python, lists' order too can be manipulated with sort, organizing your variables in numerical/alphabetical order: Temporarily:

print(sorted(my_list))

Permanent:

my_list.sort(), print(my_list)

You can sort with the flag "reverse=True":

print(sorted(my_list, reverse=True))

or

my_list.sort(reverse=True), print(my_list)

WITHOUT ORGANIZING

Maybe you do not want to sort values, but only reverse the values. Then we can do it like this:

print(list(reversed(my_list)))

**Numbers have priority over alphabet in listing order. The Python values' organization is awesome.

Edit 1: a mistaken moderator claimed that my answer was a copy and deleted my old post.

Difference between onLoad and ng-init in angular

ng-init is a directive that can be placed inside div's, span's, whatever, whereas onload is an attribute specific to the ng-include directive that functions as an ng-init. To see what I mean try something like:

<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>

You'll see that only the second one shows up.

An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.

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

Use the quotemeta function:

$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";

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

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

How to drop unique in MySQL?

mysql> DROP INDEX email ON fuinfo;

where email is the unique key (rather than the column name). You find the name of the unique key by

mysql> SHOW CREATE TABLE fuinfo;

here you see the name of the unique key, which could be email_2, for example. So...

mysql> DROP INDEX email_2 ON fuinfo;

mysql> DESCRIBE fuinfo;

This should show that the index is removed

Set date input field's max date to today

Yes, and no. There are min and max attributes in HTML 5, but

The max attribute will not work for dates and time in Internet Explorer 10+ or Firefox, since IE 10+ and Firefox does not support these input types.

EDIT: Firefox now does support it

So if you are confused by the documentation of that attributes, yet it doesn't work, that's why.
See the W3 page for the versions.

I find it easiest to use Javascript, s the other answers say, since you can just use a pre-made module. Also, many Javascript date picker libraries have a min/max setting and have that nice calendar look.

Return JSON response from Flask view

If you want to analyze a file uploaded by the user, the Flask quickstart shows how to get files from users and access them. Get the file from request.files and pass it to the summary function.

from flask import request, jsonify
from werkzeug import secure_filename

@app.route('/summary', methods=['GET', 'POST'])
def summary():
    if request.method == 'POST':
        csv = request.files['data']
        return jsonify(
            summary=make_summary(csv),
            csv_name=secure_filename(csv.filename)
        )

    return render_template('submit_data.html')

Replace the 'data' key for request.files with the name of the file input in your HTML form.

PHP foreach loop key value

As Pekka stated above

foreach ($array as $key => $value)

Also you might want to try a recursive function

displayRecursiveResults($site);

function displayRecursiveResults($arrayObject) {
    foreach($arrayObject as $key=>$data) {
        if(is_array($data)) {
            displayRecursiveResults($data);
        } elseif(is_object($data)) {
            displayRecursiveResults($data);
        } else {
            echo "Key: ".$key." Data: ".$data."<br />";
        }
    }
}

is vs typeof

I did some benchmarking where they do the same - sealed types.

var c1 = "";
var c2 = typeof(string);
object oc1 = c1;
object oc2 = c2;

var s1 = 0;
var s2 = '.';
object os1 = s1;
object os2 = s2;

bool b = false;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    b = c1.GetType() == typeof(string); // ~60ms
    b = c1 is string; // ~60ms

    b = c2.GetType() == typeof(string); // ~60ms
    b = c2 is string; // ~50ms

    b = oc1.GetType() == typeof(string); // ~60ms
    b = oc1 is string; // ~68ms

    b = oc2.GetType() == typeof(string); // ~60ms
    b = oc2 is string; // ~64ms


    b = s1.GetType() == typeof(int); // ~130ms
    b = s1 is int; // ~50ms

    b = s2.GetType() == typeof(int); // ~140ms
    b = s2 is int; // ~50ms

    b = os1.GetType() == typeof(int); // ~60ms
    b = os1 is int; // ~74ms

    b = os2.GetType() == typeof(int); // ~60ms
    b = os2 is int; // ~68ms


    b = GetType1<string, string>(c1); // ~178ms
    b = GetType2<string, string>(c1); // ~94ms
    b = Is<string, string>(c1); // ~70ms

    b = GetType1<string, Type>(c2); // ~178ms
    b = GetType2<string, Type>(c2); // ~96ms
    b = Is<string, Type>(c2); // ~65ms

    b = GetType1<string, object>(oc1); // ~190ms
    b = Is<string, object>(oc1); // ~69ms

    b = GetType1<string, object>(oc2); // ~180ms
    b = Is<string, object>(oc2); // ~64ms


    b = GetType1<int, int>(s1); // ~230ms
    b = GetType2<int, int>(s1); // ~75ms
    b = Is<int, int>(s1); // ~136ms

    b = GetType1<int, char>(s2); // ~238ms
    b = GetType2<int, char>(s2); // ~69ms
    b = Is<int, char>(s2); // ~142ms

    b = GetType1<int, object>(os1); // ~178ms
    b = Is<int, object>(os1); // ~69ms

    b = GetType1<int, object>(os2); // ~178ms
    b = Is<int, object>(os2); // ~69ms
}

sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

The generic functions to test for generic types:

static bool GetType1<S, T>(T t)
{
    return t.GetType() == typeof(S);
}
static bool GetType2<S, T>(T t)
{
    return typeof(T) == typeof(S);
}
static bool Is<S, T>(T t)
{
    return t is S;
}

I tried for custom types as well and the results were consistent:

var c1 = new Class1();
var c2 = new Class2();
object oc1 = c1;
object oc2 = c2;

var s1 = new Struct1();
var s2 = new Struct2();
object os1 = s1;
object os2 = s2;

bool b = false;

Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    b = c1.GetType() == typeof(Class1); // ~60ms
    b = c1 is Class1; // ~60ms

    b = c2.GetType() == typeof(Class1); // ~60ms
    b = c2 is Class1; // ~55ms

    b = oc1.GetType() == typeof(Class1); // ~60ms
    b = oc1 is Class1; // ~68ms

    b = oc2.GetType() == typeof(Class1); // ~60ms
    b = oc2 is Class1; // ~68ms


    b = s1.GetType() == typeof(Struct1); // ~150ms
    b = s1 is Struct1; // ~50ms

    b = s2.GetType() == typeof(Struct1); // ~150ms
    b = s2 is Struct1; // ~50ms

    b = os1.GetType() == typeof(Struct1); // ~60ms
    b = os1 is Struct1; // ~64ms

    b = os2.GetType() == typeof(Struct1); // ~60ms
    b = os2 is Struct1; // ~64ms


    b = GetType1<Class1, Class1>(c1); // ~178ms
    b = GetType2<Class1, Class1>(c1); // ~98ms
    b = Is<Class1, Class1>(c1); // ~78ms

    b = GetType1<Class1, Class2>(c2); // ~178ms
    b = GetType2<Class1, Class2>(c2); // ~96ms
    b = Is<Class1, Class2>(c2); // ~69ms

    b = GetType1<Class1, object>(oc1); // ~178ms
    b = Is<Class1, object>(oc1); // ~69ms

    b = GetType1<Class1, object>(oc2); // ~178ms
    b = Is<Class1, object>(oc2); // ~69ms


    b = GetType1<Struct1, Struct1>(s1); // ~272ms
    b = GetType2<Struct1, Struct1>(s1); // ~140ms
    b = Is<Struct1, Struct1>(s1); // ~163ms

    b = GetType1<Struct1, Struct2>(s2); // ~272ms
    b = GetType2<Struct1, Struct2>(s2); // ~140ms
    b = Is<Struct1, Struct2>(s2); // ~163ms

    b = GetType1<Struct1, object>(os1); // ~178ms
    b = Is<Struct1, object>(os1); // ~64ms

    b = GetType1<Struct1, object>(os2); // ~178ms
    b = Is<Struct1, object>(os2); // ~64ms
}

sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());

And the types:

sealed class Class1 { }
sealed class Class2 { }
struct Struct1 { }
struct Struct2 { }

Inference:

  1. Calling GetType on structs is slower. GetType is defined on object class which can't be overridden in sub types and thus structs need to be boxed to be called GetType.

  2. On an object instance, GetType is faster, but very marginally.

  3. On generic type, if T is class, then is is much faster. If T is struct, then is is much faster than GetType but typeof(T) is much faster than both. In cases of T being class, typeof(T) is not reliable since its different from actual underlying type t.GetType.

In short, if you have an object instance, use GetType. If you have a generic class type, use is. If you have a generic struct type, use typeof(T). If you are unsure if generic type is reference type or value type, use is. If you want to be consistent with one style always (for sealed types), use is..

ASP.Net MVC How to pass data from view to controller

You can do it with ViewModels like how you passed data from your controller to view.

Assume you have a viewmodel like this

public class ReportViewModel
{
   public string Name { set;get;}
}

and in your GET Action,

public ActionResult Report()
{
  return View(new ReportViewModel());
}

and your view must be strongly typed to ReportViewModel

@model ReportViewModel
@using(Html.BeginForm())
{
  Report NAme : @Html.TextBoxFor(s=>s.Name)
  <input type="submit" value="Generate report" />
}

and in your HttpPost action method in your controller

[HttpPost]
public ActionResult Report(ReportViewModel model)
{
  //check for model.Name property value now
  //to do : Return something
}

OR Simply, you can do this without the POCO classes (Viewmodels)

@using(Html.BeginForm())
{
   <input type="text" name="reportName" />
   <input type="submit" />
}

and in your HttpPost action, use a parameter with same name as the textbox name.

[HttpPost]
public ActionResult Report(string reportName)
{
  //check for reportName parameter value now
  //to do : Return something
}

EDIT : As per the comment

If you want to post to another controller, you may use this overload of the BeginForm method.

@using(Html.BeginForm("Report","SomeOtherControllerName"))
{
   <input type="text" name="reportName" />
   <input type="submit" />
}

Passing data from action method to view ?

You can use the same view model, simply set the property values in your GET action method

public ActionResult Report()
{
  var vm = new ReportViewModel();
  vm.Name="SuperManReport";
  return View(vm);
}

and in your view

@model ReportViewModel
<h2>@Model.Name</h2>
<p>Can have input field with value set in action method</p>
@using(Html.BeginForm())
{
  @Html.TextBoxFor(s=>s.Name)
  <input type="submit" />
}

Understanding The Modulus Operator %

As others have pointed out modulus is based on remainder system.

I think an easier way to think about modulus is what remains after a dividend (number to be divided) has been fully divided by a divisor. So if we think about 5%7, when you divide 5 by 7, 7 can go into 5 only 0 times and when you subtract 0 (7*0) from 5 (just like we learnt back in elementary school), then the remainder would be 5 ( the mod). See the illustration below.

   0
  ______
7) 5    
__-0____
   5

With the same logic, -5 mod 7 will be -5 ( only 0 7s can go in -5 and -5-0*7 = -5). With the same token -5 mod -7 will also be -5. A few more interesting cases:

5 mod (-3) = 2 i.e. 5 - (-3*-1)

(-5) mod (-3) = -2 i.e. -5 - (-3*1) = -5+3

How to remove the last character from a bash grep output

I'd use sed 's/;$//'. eg:

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | sed 's/;$//'`

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

How can I pass an Integer class correctly by reference?

The Integer is immutable. You can wrap int in your custom wrapper class.

class WrapInt{
    int value;
}

WrapInt theInt = new WrapInt();

inc(theInt);
System.out.println("main: "+theInt.value);

How to change the blue highlight color of a UITableViewCell?

for completeness: if you created your own subclass of UITableViewCell you can implement the - (void)setSelected:(BOOL)selected animated:(BOOL)animated method, and set the background color of some view you added in the content view. (if that is the case) or of the contentView itself (if it is not covered by one of your own views.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    if(selected) {
        self.contentView.backgroundColor = UIColor.blueColor;
    } else {
        self.contentView.backgroundColor = UIColor.whiteColor;
    }
}

(did not use ? to fit the small width of source code DIV's :)

this approach has two advantages over using selectedBackgroundView, it uses less memory, and slightly less CPU, not that u would even notice unless u display hundreds of cells.

How to make a node.js application run permanently?

During development, I recommend using nodemon. It will restart your server whenever a file changes. As others have pointed out, Forever is an option but in production, it all depends on the platform you are using. You will typically want to use the operating system's recommended way of keeping services up (e.g. http://www.freedesktop.org/wiki/Software/systemd/).

Pythonic way to print list items

Expanding @lucasg's answer (inspired by the comment it received):

To get a formatted list output, you can do something along these lines:

l = [1,2,5]
print ", ".join('%02d'%x for x in l)

01, 02, 05

Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

how to delete default values in text field using selenium?

You can use the code below. It selects the pre-existing value in the field and overwrites it with the new value.

driver.findElement(By.xpath("*enter your xpath here*")).sendKeys(Keys.chord(Keys.CONTROL, "a"),*enter the new value here*);

Apply function to all elements of collection through LINQ

I found some way to perform in on dictionary contain my custom class methods

foreach (var item in this.Values.Where(p => p.IsActive == false))
            item.Refresh();

Where 'this' derived from : Dictionary<string, MyCustomClass>

class MyCustomClass 
{
   public void Refresh(){}
}

Java substring: 'string index out of range'

itemdescription is shorter than 38 chars. Which is why the StringOutOfBoundsException is being thrown.

Checking .length() > 0 simply makes sure the String has some not-null value, what you need to do is check that the length is long enough. You could try:

if(itemdescription.length() > 38)
  ...

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

Get last key-value pair in PHP array

You can use end to advance the internal pointer to the end or array_slice to get an array only containing the last element:

$last = end($arr);
$last = current(array_slice($arr, -1));

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

How to pass an object from one activity to another on Android

Crete a class like bean class and implement the Serializable interface. Then we can pass it through the intent method, for example:

intent.putExtra("class", BeanClass);

Then get it from the other activity, for example:

BeanClass cb = intent.getSerializableExtra("class");

How to test if JSON object is empty in Java

I have added isEmpty() methods on JSONObject and JSONArray()

 //on JSONObject 
 public Boolean isEmpty(){         
     return !this.keys().hasNext();
 }

...

//on JSONArray
public Boolean isEmpty(){
    return this.length()==0;        
}

you can get it here https://github.com/kommradHomer/JSON-java

Angular 2 two way binding using ngModel is not working

import FormsModule in your AppModule to work with two way binding [(ngModel)] with your

Increment value in mysql update query

You could also just do this:

mysql_query("
    UPDATE member_profile 
    SET points = points + 1
    WHERE user_id = '".$userid."'
");

How to compare two JSON objects with the same elements in a different order equal?

Another way could be to use json.dumps(X, sort_keys=True) option:

import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison

This works for nested dictionaries and lists.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

You can add to your web.config in your project.

It wouldn't work when you add it to projects web.config because it works with MVC.

How to connect to a secure website using SSL in Java with a pkcs12 file?

It appears that you are extracting you certificate from the PKCS #12 key store and creating a new Java key store (with type "JKS"). You don't strictly have to provide a trust store password (although using one allows you to test the integrity of your root certificates).

So, try your program with only the following SSL properties set. The list shown in your question is over-specified and may be causing problems.

System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

Also, using the PKCS #12 file directly as the trust store should work, as long as the CA certificate is detected as a "trusted" entry. But in that case, you'll have to specify the javax.net.ssl.trustStoreType property as "PKCS12" too.

Try with these properties only. If you get the same error, I suspect your problem is not the key store. If it still occurs, post more of the stack trace in your question to narrow the problem down.


The new error, "the trustAnchors parameter must be non-empty," could be due to setting the javax.net.ssl.trustStore property to a file that doesn't exist; if the file cannot be opened, an empty key store created, which would lead to this error.

Command failed due to signal: Segmentation fault: 11

I ran into this while building for Tests. Build to Run works fine. Xcode 7/Swift 2 didn't like the way a variable was initialized. This code ran fine in Xcode 6.4. Here's the line that caused the seg fault:

var lineWidth: CGFloat = (UIScreen.mainScreen().scale == 1.0) ? 1.0 : 0.5

Changing it to this solved the problem:

var lineWidth: CGFloat {
    return (UIScreen.mainScreen().scale == 1.0) ? 1.0 : 0.5
}

Storing an object in state of a React component?

  1. this.setState({ abc.xyz: 'new value' }); syntax is not allowed. You have to pass the whole object.

    this.setState({abc: {xyz: 'new value'}});
    

    If you have other variables in abc

    var abc = this.state.abc;
    abc.xyz = 'new value';
    this.setState({abc: abc});
    
  2. You can have ordinary variables, if they don't rely on this.props and this.state.

Android Studio shortcuts like Eclipse

View > Quick Switch Scheme > Keymap > Eclipse
use this option for eclipse keymap or if u want to go with AndroidStudio keymap then follow below link

Click here for Official Android Studio Keymap Refference guide

you may find default keymap referrence in

AndroidStudio --> Help-->Default keymap refrence

Vertically align an image inside a div with responsive height

html code

<div class="image-container"> <img src=""/> </div>

css code

img
{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

Meaning of "[: too many arguments" error from if [] (square brackets)

Just bumped into this post, by getting the same error, trying to test if two variables are both empty (or non-empty). That turns out to be a compound comparison - 7.3. Other Comparison Operators - Advanced Bash-Scripting Guide; and I thought I should note the following:

  • I used -e thinking it means "empty" at first; but that means "file exists" - use -z for testing empty variable (string)
  • String variables need to be quoted
  • For compound logical AND comparison, either:
    • use two tests and && them: [ ... ] && [ ... ]
    • or use the -a operator in a single test: [ ... -a ... ]

Here is a working command (searching through all txt files in a directory, and dumping those that grep finds contain both of two words):

find /usr/share/doc -name '*.txt' | while read file; do \
  a1=$(grep -H "description" $file); \
  a2=$(grep -H "changes" $file); \
  [ ! -z "$a1" -a ! -z "$a2"  ] && echo -e "$a1 \n $a2" ; \
done

Edit 12 Aug 2013: related problem note:

Note that when checking string equality with classic test (single square bracket [), you MUST have a space between the "is equal" operator, which in this case is a single "equals" = sign (although two equals' signs == seem to be accepted as equality operator too). Thus, this fails (silently):

$ if [ "1"=="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] ; then echo A; else echo B; fi 
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi 
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi 
A

... but add the space - and all looks good:

$ if [ "1" = "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi 
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi 
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi 
B

Getting cursor position in Python

For Mac using native library:

import Quartz as q
q.NSEvent.mouseLocation()

#x and y individually
q.NSEvent.mouseLocation().x
q.NSEvent.mouseLocation().y

If the Quartz-wrapper is not installed:

python3 -m pip install -U pyobjc-framework-Quartz

(The question specify Windows, but a lot of Mac users come here because of the title)

maximum value of int

#include <iostrema>

int main(){
    int32_t maxSigned = -1U >> 1;
    cout << maxSigned << '\n';
    return 0;
}

It might be architecture dependent but it does work at least in my setup.

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

Following the official installation guide for Windows C++ compilers:

https://wiki.python.org/moin/WindowsCompilers

to upgrade setuptools and install specific Microsoft Visual C++ compiler.

It has already contains some points refered in other answer.

Javascript get object key name

An ES6 update... though both filter and map might need customization.

Object.entries(theObj) returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.

Saves a ton of work on iterating over parts of an object Object.keys(theObj), or Object.values() separately.

_x000D_
_x000D_
const buttons = {_x000D_
    button1: {_x000D_
        text: 'Close',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button2: {_x000D_
        text: 'OK',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    },_x000D_
    button3: {_x000D_
        text: 'Cancel',_x000D_
        onclick: function(){_x000D_
_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
    .filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
    .map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
    _x000D_
console.log(list)
_x000D_
_x000D_
_x000D_

What is the difference between decodeURIComponent and decodeURI?

To explain the difference between these two let me explain the difference between encodeURI and encodeURIComponent.

The main difference is that:

  • The encodeURI function is intended for use on the full URI.
  • The encodeURIComponent function is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : @ & = + $ , #).

So, in encodeURIComponent these separators are encoded also because they are regarded as text and not special characters.

Now back to the difference between the decode functions, each function decodes strings generated by its corresponding encode counterpart taking care of the semantics of the special characters and their handling.

Using FolderBrowserDialog in WPF application

You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog class.

Adding using WinForms = System.Windows.Forms; will be helpful.

Is it possible to start a shell session in a running container (without ssh)

Maybe you were mislead like myself into thinking in terms of VMs when developing containers. My advice: Try not to.

Containers are just like any other process. Indeed you might want to "attach" to them for debugging purposes (think of /proc//env or strace -p ) but that's a very special case.

Normally you just "run" the process, so if you want to modify the configuration or read the logs, just create a new container and make sure you write the logs outside of it by sharing directories, writing to stdout (so docker logs works) or something like that.

For debugging purposes you might want to start a shell, then your code, then press CTRL-p + CTRL-q to leave the shell intact. This way you can reattach using:

docker attach <container_id>

If you want to debug the container because it's doing something you haven't expect it to do, try to debug it: https://serverfault.com/questions/596994/how-can-i-debug-a-docker-container-initialization

swift How to remove optional String Character

print("imageURLString = " + imageURLString!)

just use !

use Lodash to sort array of object by value

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

How to add an onchange event to a select box via javascript?

Add

transport_select.setAttribute("onchange", function(){toggleSelect(transport_select_id);});

setAttribute

or try replacing onChange with onchange

Textarea Auto height

html

<textarea id="wmd-input" name="md-content"></textarea>

js

var textarea = $('#wmd-input'),
    top = textarea.scrollTop(),
    height = textarea.height();
    if(top > 0){
       textarea.css("height",top + height)
    }

css

#wmd-input{
    width: 100%;
    overflow: hidden;
    padding: 10px;
}

Multipart File upload Spring Boot

   @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("5120MB");
        factory.setMaxRequestSize("5120MB");
        return factory.createMultipartConfig();
    }

put it in class where you are defining beans

Vertical align text in block element

li a {
width: 300px;
height: 100px;
display: table-cell;
vertical-align: middle;
margin: auto 0;
background: red;

}

iPad WebApp Full Screen in Safari

  1. First, launch your Safari browser from the Home screen and go to the webpage that you want to view full screen.

  2. After locating the webpage, tap on the arrow icon at the top of your screen.

  3. In the drop-down menu, tap on the Add to Home Screen option.

  4. The Add to Home window should be displayed. You can customize the description that will appear as a title on the home screen of your iPad. When you are done, tap on the Add button.

  5. A new icon should now appear on your home screen. Tapping on the icon will open the webpage in the fullscreen mode.

Note: The icon on your iPad home screen only opens the bookmarked page in the fullscreen mode. The next page you visit will be contain the Safari address and title bars. This way of playing your webpage or HTML5 presentation in the fullscreen mode works if the source code of the webpage contains the following tag:

<meta name="apple-mobile-web-app-capable" content="yes">

You can add this tag to your webpage using a third-party tool, for example iWeb SEO Tool or any other you like. Please note that you need to add the tag first, refresh the page and then add a bookmark to your home screen.

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

How to get item count from DynamoDB?

You can use the Select parameter and use COUNT in the request. It "returns the number of matching items, rather than the matching items themselves". Important, as brought up by Saumitra R. Bhave in a comment, "If the size of the Query result set is larger than 1 MB, then ScannedCount and Count will represent only a partial count of the total items. You will need to perform multiple Query operations in order to retrieve all of the results".

I'm Not familiar with PHP but here is how you could use it with Java. And then instead of using Count (which I am guessing is a function in PHP) on the 'Items' you can use the Count value from the response - $result['Count']:

final String week = "whatever";
final Integer myPoint = 1337;
Condition weekCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.EQ)
        .withAttributeValueList(new AttributeValue().withS(week));
Condition myPointCondition = new Condition()
        .withComparisonOperator(ComparisonOperator.GE)
        .withAttributeValueList(new AttributeValue().withN(myPoint.toString()))

Map<String, Condition> keyConditions = new HashMap<>();
keyConditions.put("week", weekCondition);
keyConditions.put("point", myPointCondition);

QueryRequest request = new QueryRequest("game_table");
request.setIndexName("week-point-index");
request.setSelect(Select.COUNT);
request.setKeyConditions(keyConditions);

QueryResult result = dynamoDBClient.query(request);
Integer count = result.getCount();

If you don't need to emulate the WHERE clause, you can use a DescribeTable request and use the resulting item count to get an estimate.

The number of items in the specified table. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.

Also, an important note from the documentation as noted by Saumitra R. Bhave in the comments on this answer:

If the size of the Query result set is larger than 1 MB, ScannedCount and Count represent only a partial count of the total items. You need to perform multiple Query operations to retrieve all the results (see Paginating Table Query Results).

Slicing a dictionary

the dictionary

d = {1:2, 3:4, 5:6, 7:8}

the subset of keys I'm interested in

l = (1,5)

answer

{key: d[key] for key in l}

convert string into array of integers

var result = "14 2".split(" ").map(function(x){return parseInt(x)});

Is it correct to use DIV inside FORM?

It is wrong to have <input> as a direct child of a <form>

And by the way <input /> may fail on some doctype

Check it with http://validator.w3.org/check


document type does not allow element "INPUT" here; missing one of "P", "H1", "H2", "H3", "H4", "H5", "H6", "PRE", "DIV", "ADDRESS" start-tag

<input type="text" />

The mentioned element is not allowed to appear in the context in which you've placed it; the other mentioned elements are the only ones that are both allowed there and can contain the element mentioned. This might mean that you need a containing element, or possibly that you've forgotten to close a previous element.

One possible cause for this message is that you have attempted to put a block-level element (such as "<p>" or "<table>") inside an inline element (such as "<a>", "<span>", or "<font>").

CSS div 100% height

try setting the body style to:

body { position:relative;}

it worked for me

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

first,i used "localhost:port" format met this error.then I changed the address to "ip:port" format and the problem solved.

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

Fatal error: Call to undefined function mb_strlen()

On Centos, RedHat, Fedora and other yum-my systems it is much simpler than the PHP manual suggests:

yum install php-mbstring
service httpd restart

CheckBox in RecyclerView keeps on checking different items

public class TagYourDiseaseAdapter extends RecyclerView.Adapter { private ReCyclerViewItemClickListener mRecyclerViewItemClickListener; private Context mContext;

List<Datum> deviceList = Collections.emptyList();

/**
 * Initialize the values
 *
 * @param context : context reference
 * @param devices : data
 */

public TagYourDiseaseAdapter(Context context, List<Datum> devices,
                             ReCyclerViewItemClickListener mreCyclerViewItemClickListener) {
    this.mContext = context;
    this.deviceList = devices;
    this.mRecyclerViewItemClickListener = mreCyclerViewItemClickListener;
}


/**
 * @param parent   : parent ViewPgroup
 * @param viewType : viewType
 * @return ViewHolder
 * <p>
 * Inflate the Views
 * Create the each views and Hold for Reuse
 */
@Override
public TagYourDiseaseAdapter.OrderHistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag_disease, parent, false);
    TagYourDiseaseAdapter.OrderHistoryViewHolder myViewHolder = new TagYourDiseaseAdapter.OrderHistoryViewHolder(view);
    return myViewHolder;
}


/**
 * @param holder   :view Holder
 * @param position : position of each Row
 *                 set the values to the views
 */
@Override
public void onBindViewHolder(final TagYourDiseaseAdapter.OrderHistoryViewHolder holder, final int position) {
    Picasso.with(mContext).load(deviceList.get(position).getIconUrl()).into(holder.document);
    holder.name.setText(deviceList.get(position).getDiseaseName());

    holder.radioButton.setOnCheckedChangeListener(null);
    holder.radioButton.setChecked(deviceList.get(position).isChecked());

    //if true, your checkbox will be selected, else unselected
    //holder.radioButton.setChecked(objIncome.isSelected());

    holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            deviceList.get(position).setChecked(isChecked);
        }
    });


}

@Override
public int getItemCount() {
    return deviceList.size();
}


/**
 * Create The view First Time and hold for reuse
 * View Holder for Create and Hold the view for ReUse the views instead of create again
 * Initialize the views
 */

public class OrderHistoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    ImageView document;
    TextView name;
    CheckBox radioButton;

    public OrderHistoryViewHolder(View itemView) {
        super(itemView);
        document = itemView.findViewById(R.id.img_tag);
        name = itemView.findViewById(R.id.text_tag_name);
        radioButton = itemView.findViewById(R.id.rdBtn_tag_disease);
        radioButton.setOnClickListener(this);
        //this.setIsRecyclable(false);
    }


    @Override
    public void onClick(View view) {
        mRecyclerViewItemClickListener.onItemClickListener(this.getAdapterPosition(), view);
    }
}

}

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

Push commits to another branch

I got a bad result with git push origin branch1:branch2 command:

In my case, branch2 is deleted and branch1 has been updated with some new changes.

Hence, if you want only the changes push on the branch2 from the branch1, try procedures below:

  • On branch1: git add .
  • On branch1: git commit -m 'comments'
  • On branch1: git push origin branch1

  • On branch2: git pull origin branch1

  • On branch1: revert to the previous commit.

What is SOA "in plain english"?

I would suggest you read articles by Thomas Erl and Roger Sessions, this will give you a firm handle on what SOA is all about. These are also good resources, look at the SOA explained for your boss one for a layman explanation

Building a SOA

SOA Design Pattern

Achieving integrity in a SOA

Why your SOA should be like a VW Beetle

SOA explained for your boss

WCF Service Performance

Selenium WebDriver.get(url) does not open the URL

I was facing exactly the same issue, after browsing for sometime,I came to know that it is basically version compatibility issue between FireFox and selenium. I have got the latest FireFox but my Selenium imported was older which is causing the issue. Issue got resolved after upgrading selenium

pip install -U selenium

OS: windows Python 2.7

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

How to bind 'touchstart' and 'click' events but not respond to both?

Why not use the jQuery Event API?

http://learn.jquery.com/events/event-extensions/

I've used this simple event with success. It's clean, namespaceable and flexible enough to improve upon.

var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
var eventType = isMobile ? "touchstart" : "click";

jQuery.event.special.touchclick = {
  bindType: eventType,
  delegateType: eventType
};

Remove last character of a StringBuilder?

You may try to use 'Joiner' class instead of removing the last character from your generated text;

                List<String> textList = new ArrayList<>();
                textList.add("text1");
                textList.add("text2");
                textList.add("text3");

                Joiner joiner = Joiner.on(",").useForNull("null");
                String output = joiner.join(textList);

               //output : "text1,text2,text3"

How is returning the output of a function different from printing it?

I think you're confused because you're running from the REPL, which automatically prints out the value returned when you call a function. In that case, you do get identical output whether you have a function that creates a value, prints it, and throws it away, or you have a function that creates a value and returns it, letting the REPL print it.

However, these are very much not the same thing, as you will realize when you call autoparts with another function that wants to do something with the value that autoparts creates.

error while loading shared libraries: libncurses.so.5:

If you are absolutely sure that libncurses, aka ncurses, is installed, as in you've done a successful 'ls' of the library, then perhaps you are running a 64 bit Linux operating system and only have the 64 bit libncurses installed, when the program that is running (adb) is 32 bit.

If so, a 32 bit program can't link to a 64 bit library (and won't located it anyway), so you might have to install libcurses, or ncurses (32 bit version). Likewise, if you are running a 64 bit adb, perhaps your ncurses is 32 bit (a possible but less likely scenario).

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Using async/await with a forEach loop

One important caveat is: The await + for .. of method and the forEach + async way actually have different effect.

Having await inside a real for loop will make sure all async calls are executed one by one. And the forEach + async way will fire off all promises at the same time, which is faster but sometimes overwhelmed(if you do some DB query or visit some web services with volume restrictions and do not want to fire 100,000 calls at a time).

You can also use reduce + promise(less elegant) if you do not use async/await and want to make sure files are read one after another.

files.reduce((lastPromise, file) => 
 lastPromise.then(() => 
   fs.readFile(file, 'utf8')
 ), Promise.resolve()
)

Or you can create a forEachAsync to help but basically use the same for loop underlying.

Array.prototype.forEachAsync = async function(cb){
    for(let x of this){
        await cb(x);
    }
}

How do I make a checkbox required on an ASP.NET form?

Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

The .ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

And the codebehind:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub

Free c# QR-Code generator

Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code

QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);

Check if multiple strings exist in another string

Yet another solution with set. using set.intersection. For a one-liner.

subset = {"some" ,"words"} 
text = "some words to be searched here"
if len(subset & set(text.split())) == len(subset):
   print("All values present in text")

if subset & set(text.split()):
   print("Atleast one values present in text")

Remove old Fragment from fragment manager

If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Refer this post: Replacing a fragment with another fragment inside activity group

Refer1: Replace a fragment programmatically

Check existence of input argument in a Bash shell script

It is better to demonstrate this way

if [[ $# -eq 0 ]] ; then
    echo 'some message'
    exit 1
fi

You normally need to exit if you have too few arguments.

Latex Multiple Linebreaks

While verbatim might be the best choice, you can also try the commands \smallskip , \medskip or guess what, \bigskip .

Quoting from this page:

These commands can only be used after a paragraph break (which is made by one completely blank line or by the command \par). These commands output flexible or rubber space, approximately 3pt, 6pt, and 12pt high respectively, but these commands will automatically compress or expand a bit, depending on the demands of the rest of the page

Get loop count inside a Python FOR loop

Using zip function we can get both element and index.

countries = ['Pakistan','India','China','Russia','USA']

for index, element zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

See also :

Python.org

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

To even do better boolean mapping to Y/N, add to your hibernate configuration:

<!-- when using type="yes_no" for booleans, the line below allow booleans in HQL expressions: -->
<property name="hibernate.query.substitutions">true 'Y', false 'N'</property>

Now you can use booleans in HQL, for example:

"FROM " + SomeDomainClass.class.getName() + " somedomainclass " +
"WHERE somedomainclass.someboolean = false"

Reverting to a specific commit based on commit id with Git?

If you want to force the issue, you can do:

git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07

send you back to how your git clone looked like at the time of the checkin

eval command in Bash and its typical uses

I've recently had to use eval to force multiple brace expansions to be evaluated in the order I needed. Bash does multiple brace expansions from left to right, so

xargs -I_ cat _/{11..15}/{8..5}.jpg

expands to

xargs -I_ cat _/11/8.jpg _/11/7.jpg _/11/6.jpg _/11/5.jpg _/12/8.jpg _/12/7.jpg _/12/6.jpg _/12/5.jpg _/13/8.jpg _/13/7.jpg _/13/6.jpg _/13/5.jpg _/14/8.jpg _/14/7.jpg _/14/6.jpg _/14/5.jpg _/15/8.jpg _/15/7.jpg _/15/6.jpg _/15/5.jpg

but I needed the second brace expansion done first, yielding

xargs -I_ cat _/11/8.jpg _/12/8.jpg _/13/8.jpg _/14/8.jpg _/15/8.jpg _/11/7.jpg _/12/7.jpg _/13/7.jpg _/14/7.jpg _/15/7.jpg _/11/6.jpg _/12/6.jpg _/13/6.jpg _/14/6.jpg _/15/6.jpg _/11/5.jpg _/12/5.jpg _/13/5.jpg _/14/5.jpg _/15/5.jpg

The best I could come up with to do that was

xargs -I_ cat $(eval echo _/'{11..15}'/{8..5}.jpg)

This works because the single quotes protect the first set of braces from expansion during the parsing of the eval command line, leaving them to be expanded by the subshell invoked by eval.

There may be some cunning scheme involving nested brace expansions that allows this to happen in one step, but if there is I'm too old and stupid to see it.

Open a URL in a new tab (and not a new window)

enter image description here

I researched a lot of information about how to open new tab and stay on the same tab. I have found one small trick to do it. Lets assume you have url which you need to open - newUrl and old url - currentUrl, which you need to stay on after new tab opened. JS code will look something like next:

// init urls
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
// open window with url of current page, you will be automatically moved 
// by browser to a new opened tab. It will look like your page is reloaded
// and you will stay on same page but with new page opened
window.open(currentUrl , '_blank');
// on your current tab will be opened new url
location.href = newUrl;

Android Center text on canvas

In my case, I didn't have to put the text in the middle of a canvas, but in a wheel that spins. Though I had to use this code to succeed:

fun getTextRect(textSize: Float, textPaint: TextPaint, string: String) : PointF {
    val rect = RectF(left, top, right, bottom)
    val rectHeight = Rect()
    val cx = rect.centerX()
    val cy = rect.centerY()

    textPaint.getTextBounds(string, 0, string.length, rectHeight)
    val y = cy + rectHeight.height()/2
    val x = cx - textPaint.measureText(string)/2

    return PointF(x, y)
}

Then I call this method from the View class:

private fun drawText(canvas: Canvas, paint: TextPaint, text: String, string: String) {
    val pointF = getTextRect(paint.textSize, textPaint, string)
    canvas.drawText(text, pointF!!.x, pointF.y, paint)
}

identifier "string" undefined?

Perhaps you wanted to #include<string>, not <string.h>. std::string also needs a namespace qualification, or an explicit using directive.

.attr("disabled", "disabled") issue

Try

$(bla).click(function(){        
  if (something) {
     console.log("A:"+$target.prev("input")) // gives out the right object
     $target.toggleClass("open").prev("input").attr("disabled", "disabled");
  }else{
     console.log("A:"+$target.prev("input")) // any thing from there for a single click?
     $target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
  }
});

how to convert milliseconds to date format in android?

DateFormat.getDateInstance().format(dateInMS);

Custom Python list sorting

I know many have already posted some good answers. However I want to suggest one nice and easy method without importing any library.

l = [(2, 3), (3, 4), (2, 4)]
l.sort(key = lambda x: (-x[0], -x[1]) )
print(l)
l.sort(key = lambda x: (x[0], -x[1]) )
print(l)

Output will be

[(3, 4), (2, 4), (2, 3)]
[(2, 4), (2, 3), (3, 4)]

The output will be sorted based on the order of the parameters we provided in the tuple format

"The system cannot find the file specified" when running C++ program

if vs2010 installed correctly

check file type (.cpp)

just build it again It will automatically fix,, ( if you are using VS 2010 )

Why does javascript map function return undefined?

Since ES6 filter supports pointy arrow notation (like LINQ):

So it can be boiled down to following one-liner.

['a','b',1].filter(item => typeof item ==='string');

Django Server Error: port is already in use

Type 'fg' as command after that ctl-c.
Command:
Fg will show which is running on background. After that ctl-c will stop it.

fg
ctl-c

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

Can Mysql Split a column?

Usually substring_index does what you want:

mysql> select substring_index("[email protected]","@",-1);
+-----------------------------------------+
| substring_index("[email protected]","@",-1) |
+-----------------------------------------+
| gmail.com                               |
+-----------------------------------------+
1 row in set (0.00 sec)

Iterating over Numpy matrix rows to apply a function each?

Use numpy.apply_along_axis(). Assuming your matrix is 2D, you can use like:

import numpy as np
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])
def myfunction( x ):
    return sum(x)

print np.apply_along_axis( myfunction, axis=1, arr=mymatrix )
#[36 66 96]

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

How to specify a local file within html using the file: scheme?

The file: URL scheme refers to a file on the client machine. There is no hostname in the file: scheme; you just provide the path of the file. So, the file on your local machine would be file:///~User/2ndFile.html. Notice the three slashes; the hostname part of the URL is empty, so the slash at the beginning of the path immediately follows the double slash at the beginning of the URL. You will also need to expand the user's path; ~ does no expand in a file: URL. So you would need file:///home/User/2ndFile.html (on most Unixes), file:///Users/User/2ndFile.html (on Mac OS X), or file:///C:/Users/User/2ndFile.html (on Windows).

Many browsers, for security reasons, do not allow linking from a file that is loaded from a server to a local file. So, you may not be able to do this from a page loaded via HTTP; you may only be able to link to file: URLs from other local pages.

jQuery, checkboxes and .is(":checked")

In addition to Nick Craver's answer, for this to work properly on IE 8 you need to add a additional click handler to the checkbox:

// needed for IE 8 compatibility
if ($.browser.msie)
    $("#myCheckbox").click(function() { $(this).trigger('change'); });

$("#myCheckbox").change( function() {
    alert($(this).is(":checked"));
});

//Trigger by:
$("#myCheckbox").trigger('click').trigger('change');

Otherwise the callback will only be triggered when the checkbox loses focus, as IE 8 keeps focus on checkboxes and radios when they are clicked.

Haven't tested on IE 9 though.

How to remove selected commit log entries from a Git repository while keeping their changes?

Here is a way to remove a specific commit id knowing only the commit id you would like to remove.

git rebase --onto commit-id^ commit-id

Note that this actually removes the change that was introduced by the commit.

concatenate two database columns into one resultset column

Use ISNULL to overcome it.

Example:

SELECT (ISNULL(field1, '') + '' + ISNULL(field2, '')+ '' + ISNULL(field3, '')) FROM table1

This will then replace your NULL content with an empty string which will preserve the concatentation operation from evaluating as an overall NULL result.

Twitter bootstrap collapse: change display of toggle button

I liked the CSS-only solution from PSL, but in my case I needed to include some HTML in the button, and the content CSS property is showing the raw HTML with tags in this case.

In case that could help someone else, I've forked his fiddle to cover my use case: http://jsfiddle.net/brunoalla/99j11h40/2/

HTML:

<div class="row-fluid summary">
    <div class="span11">
        <h2>MyHeading</h2>  
    </div>
    <div class="span1">
        <button class="btn btn-success collapsed" data-toggle="collapse" data-target="#intro">
            <span class="show-ctrl">
                <i class="fa fa-chevron-down"></i> Expand
            </span>
            <span class="hide-ctrl">
                <i class="fa fa-chevron-up"></i> Collapse
            </span>            
        </button>
    </div>
</div>
<div class="row-fluid summary">
    <div id="intro" class="collapse"> 
        Here comes the text...
    </div>
</div>

CSS:

button.btn .show-ctrl{
    display: none;
}
button.btn .hide-ctrl{
    display: block;
}
button.btn.collapsed .show-ctrl{
    display: block;
}
button.btn.collapsed .hide-ctrl{
    display: none;
}

Php artisan make:auth command is not defined

In the Laravel 6 application the make:auth command no longer exists.

Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.

You can install the laravel/ui package via composer:

composer require laravel/ui

The ui:auth Command

Besides the new ui command, the laravel/ui package comes with another command for generating the auth scaffolding:

php artisan ui:auth

If you run the ui:auth command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.


If you want to generate the views alone, type the following command instead:

php artisan ui:auth --views

If you want to generate the auth scaffolding at the same time:

php artisan ui vue --auth
php artisan ui react --auth

php artisan ui vue --auth command will create all of the views you need for authentication and place them in the resources/views/auth directory

The ui command will also create a resources/views/layouts directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

More detail follow. laravel-news & documentation

Simply you've to follow this two-step.

composer require laravel/ui
php artisan ui:auth

How to set border's thickness in percentages?

You can use em for percentage instead of pixels,

Example:

border:10PX dotted #c1a9ff; /* In Pixels */
border:0.75em dotted #c1a9ff; /* Exact same as above in Percentage */

integrating barcode scanner into php application?

I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.

Escaping ampersand character in SQL string

straight from oracle sql fundamentals book

SET DEFINE OFF
select 'Coda & Sid' from dual;
SET DEFINE ON

how would one escape it without setting define.

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

What is VanillaJS?

The plain and simple answer is yes, VanillaJS === JavaScript, as prescribed by Dr B. Eich.

Convert a String to int?

let my_u8: u8 = "42".parse::<u8>().unwrap();
let my_u32: u32 = "42".parse::<u32>().unwrap();

// or, to be safe, match the `Err`
match "foobar".parse::<i32>() {
  Ok(n) => do_something_with(n),
  Err(e) => weep_and_moan(),
}

str::parse::<u32> returns a Result<u32, core::num::ParseIntError> and Result::unwrap "Unwraps a result, yielding the content of an Ok [or] panics if the value is an Err, with a panic message provided by the Err's value."

str::parse is a generic function, hence the type in angle brackets.

What is the difference between field, variable, attribute, and property in Java POJOs?

Actually these two terms are often used to represent same thing, but there are some exceptional situations. A field can store the state of an object. Also all fields are variables. So it is clear that there can be variables which are not fields. So looking into the 4 type of variables (class variable, instance variable, local variable and parameter variable) we can see that class variables and instance variables can affect the state of an object. In other words if a class or instance variable changes,the state of object changes. So we can say that class variables and instance variables are fields while local variables and parameter variables are not.

If you want to understand more deeply, you can head over to the source below:-

http://sajupauledayan.com/java/fields-vs-variables-in-java

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

Initialize class fields in constructor or at declaration?

Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"

Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.

In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.

So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

Web colors in an Android color xml resource file

Mostly used colors in Android

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#fa3d2f</color>
    <color name="colorPrimaryDark">#d9221f</color>
    <color name="colorAccent">#FF4081</color>

    <!-- Android -->
    <color name="myPrimaryColor">#4688F2</color>
    <color name="myPrimaryDarkColor">#366AD3</color>
    <color name="myAccentColor">#FF9800</color>
    <color name="myDrawerBackground">#F2F2F2</color>
    <color name="myWindowBackground">#DEDEDE</color>
    <color name="myTextPrimaryColor">#000000</color>
    <color name="myNavigationColor">#000000</color>

    <color name="dim_gray">#696969</color>

    <color name="white">#ffffff</color>

    <color name="cetagory_item_bg_01">#ffffff</color>
    <color name="cetagory_item_bg_02">#d3dce5</color>
    <color name="cetagory_item_bg_03">#aecce8</color>
    <color name="cetagory_item_more_bg">#88add9</color>

    <color name="item_details_fragment_bg">#ededed</color>
    <!-- common -->
    <color name="common_white_1">#ffffff</color>
    <color name="common_white_2">#feffff</color>
    <color name="common_white_30">#4dffffff</color>
    <color name="common_white_10">#1aFFFFFF</color>
    <color name="common_gray_txt">#514e4e</color>
    <color name="common_gray_bg">#9fa0a0</color>
    <color name="common_black_10">#1a000000</color>
    <color name="common_black_30_1">#4d000000</color>
    <color name="common_black_30_2">#4d010000</color>
    <color name="common_black_50">#80000000</color>
    <color name="common_black_70">#B3000000</color>
    <color name="common_black_15">#26000000</color>
    <color name="common_red">#ed2024</color>
    <color name="common_yellow">#fff51e</color>
    <color name="common_light_gray_txt">#b9b9ba</color>
    <color name="indicator_gray">#737172</color>
    <color name="common_red_txt">#ff4141</color>
    <color name="common_blue_bg">#0055bd</color>
    <color name="fragment_bg">#efefef</color>
    <color name="main_gray_color">#9d9e9e</color>
    <color name="hint_color">#ababac</color>
    <color name="troubleshooting_txt_color">#231815</color>
    <color name="common_sc_main_color">#0055bd</color>
    <color name="common_ec_blue_txt">#0055bd</color>

    <color name="main_dark">#000000</color>
    <color name="introduction_text">#9FA0A0</color>
    <color name="orange">#FFB600</color>
    <color name="btn_login_email_pressed">#ccFFB600</color>
    <color name="text_dark">#9FA0A0</color>
    <color name="btn_login_facebook">#2E5DAC</color>
    <color name="btn_login_facebook_pressed">#802E5DAC</color>
    <color name="btn_login_twitter">#59ADEC</color>
    <color name="btn_login_twitter_pressed">#8059ADEC</color>
    <color name="spinner_background">#808080</color>
    <color name="clock_remain">#3d3939</color>
    <color name="border_bottom">#C9CACA</color>
    <color name="dash_border">#C9CACA</color>
    <color name="date_color">#b5b5b6</color>

    <!--send trouble shooting-->
    <color name="send_trouble_back_ground">#eae9e8</color>
    <color name="send_trouble_background_header">#cccccc</color>
    <color name="send_trouble_text_color_header">#666666</color>
    <color name="send_trouble_edit_text_color_boder">#c4c3c3</color>
    <color name="send_trouble_bg">#9fa0a0</color>

    <!--copy code-->
    <color name="back_ground_dialog">#90000000</color>



    <!--ec detail product-->
    <color name="ec_btn_go_to_shop_page_off">#0055bd</color>
    <color name="ec_btn_go_to_shop_page_on">#800055bd</color>
    <color name="ec_btn_go_to_detail_page_on">#80FFFFFF</color>
    <color name="ec_btn_login_facebook_off">#2675d7</color>
    <color name="ec_btn_login_facebook_on">#802675d7</color>
    <color name="ec_btn_login_twitter_on">#8044baff</color>
    <color name="ec_btn_login_twitter_off">#44baff</color>
    <color name="ec_btn_login_email_on">#80ffffff</color>
    <color name="ec_btn_login_email_off">#ffffff</color>
    <color name="ec_text_login_email">#ff5500</color>

    <color name="ec_point_manager_text_chart">#0063dd</color>
    <color name="common_green">#45cc28</color>
    <color  name="green1">#139E91</color>
    <color name="blacklight">#212121</color>
    <color name="black_opacity_60">#99000000</color>
    <color name="white_50_percent_opacity">#7fffffff</color>
    <color name="line_config">#c9caca</color>

    <color name="black_semi_transparent">#B2000000</color>
    <color name="background">#e5e5e5</color>
    <color name="half_black">#808080</color>
    <color name="white_pressed">#f1f1f1</color>
    <color name="pink">#e91e63</color>
    <color name="pink_pressed">#ec407a</color>
    <color name="blue_semi_transparent">#805677fc</color>
    <color name="blue_semi_transparent_pressed">#80738ffe</color>
    <color name="black">#000000</color>
    <color name="gray">#A9A9A9</color>
    <color name="nav_header_background">#fdfdfe</color>
    <color name="video_thumbnail_placeholder_color">#d3d3d3</color>
    <color name="video_des_background_color">#cec8c8</color>
</resources>

SQL Server: How to check if CLR is enabled?

select *
from sys.configurations
where name = 'clr enabled'

Codeigniter LIKE with wildcard(%)

I'm using

$this->db->query("SELECT * FROM film WHERE film.title LIKE '%$query%'"); for such purposes

SQL Update Multiple Fields FROM via a SELECT Statement

You can use:

UPDATE s SET
  s.Field1 = q.Field1,
  s.Field2 = q.Field2,
  (list of fields...)
FROM (
  SELECT Field1, Field2, (list of fields...)
  FROM ProfilerTest.dbo.BookingDetails 
  WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

Junit 4.11 doesn't work with Spring Test framework. Also this link InitializationError When Use Spring + Junit explains how to debug junit initalizationError in eclipse.

Difference between dates in JavaScript

If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:

_x000D_
_x000D_
function interval(date1, date2) {_x000D_
    if (date1 > date2) { // swap_x000D_
        var result = interval(date2, date1);_x000D_
        result.years  = -result.years;_x000D_
        result.months = -result.months;_x000D_
        result.days   = -result.days;_x000D_
        result.hours  = -result.hours;_x000D_
        return result;_x000D_
    }_x000D_
    result = {_x000D_
        years:  date2.getYear()  - date1.getYear(),_x000D_
        months: date2.getMonth() - date1.getMonth(),_x000D_
        days:   date2.getDate()  - date1.getDate(),_x000D_
        hours:  date2.getHours() - date1.getHours()_x000D_
    };_x000D_
    if (result.hours < 0) {_x000D_
        result.days--;_x000D_
        result.hours += 24;_x000D_
    }_x000D_
    if (result.days < 0) {_x000D_
        result.months--;_x000D_
        // days = days left in date1's month, _x000D_
        //   plus days that have passed in date2's month_x000D_
        var copy1 = new Date(date1.getTime());_x000D_
        copy1.setDate(32);_x000D_
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
    }_x000D_
    if (result.months < 0) {_x000D_
        result.years--;_x000D_
        result.months+=12;_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
_x000D_
_x000D_

This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).

So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.

Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).

Get records of current month

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())

GROUP BY having MAX date

Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.

It's better to run the subquery once, in the FROM clause, to get the max date per control number.

SELECT n.* 
FROM tblpm n 
INNER JOIN (
  SELECT control_number, MAX(date_updated) AS date_updated
  FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);

Copy tables from one database to another in SQL Server

If there is existing table and we wants to copy only data, we can try this query.

insert into Destination_Existing_Tbl select col1,col2 FROM Source_Tbl

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"