Programs & Examples On #Rrdtool

RRDtool (acronym for round-robin database tool) aims to handle time-series data like network bandwidth, temperatures, CPU load etc.

Checking if an object is a given type in Swift

Just for the sake of completeness based on the accepted answer and some others:

let items : [Any] = ["Hello", "World", 1]

for obj in items where obj is String {
   // obj is a String. Do something with str
}

But you can also (compactMap also "maps" the values which filter doesn't):

items.compactMap { $0 as? String }.forEach{ /* do something with $0 */ ) }

And a version using switch:

for obj in items {
    switch (obj) {
        case is Int:
           // it's an integer
        case let stringObj as String:
           // you can do something with stringObj which is a String
        default:
           print("\(type(of: obj))") // get the type
    }
}

But sticking to the question, to check if it's an array (i.e. [String]):

let items : [Any] = ["Hello", "World", 1, ["Hello", "World", "of", "Arrays"]]

for obj in items {
  if let stringArray = obj as? [String] {
    print("\(stringArray)")
  }
}

Or more generally (see this other question answer):

for obj in items {
  if obj is [Any] {
    print("is [Any]")
  }

  if obj is [AnyObject] {
    print("is [AnyObject]")
  }

  if obj is NSArray {
    print("is NSArray")
  }
}

javascript unexpected identifier

I recommend using http://jsbeautifier.org/ - if you paste your code snippet into it and press beautify, the error is immediately visible.

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

Javascript Uncaught Reference error Function is not defined

Change the wrapping from "onload" to "No wrap - in <body>"

The function defined has a different scope.

Listing files in a specific "folder" of a AWS S3 bucket

Based on @davioooh answer. This code is worked for me.

ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName("your-bucket")
            .withPrefix("your/folder/path/").withDelimiter("/");

nodejs - How to read and output jpg image?

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

How to add a reference programmatically

Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.

The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.

The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).

What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub

The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.

How do you debug MySQL stored procedures?

There are GUI tools for debugging stored procedures / functions and scripts in MySQL. A decent tool that dbForge Studio for MySQL, has rich functionality and stability.

Storing data into list with class

And if you want to create the list with some elements to start with:

var emailList = new List<EmailData>
{
   new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
   new EmailData {.......}
};

Initial bytes incorrect after Java AES/CBC decryption

Online Editor Runnable version:-

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import org.apache.commons.codec.binary.Base64;
import java.util.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));

            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());

            //System.out.println("encrypted string: "
              //      + Base64.encodeBase64String(encrypted));

            //return Base64.encodeBase64String(encrypted);
            String s = new String(Base64.getEncoder().encode(encrypted));
            return s;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(encrypt(key, initVector, "Hello World"));
        System.out.println(decrypt(key, initVector, encrypt(key, initVector, "Hello World")));
    }
}

Connecting to remote URL which requires authentication using Java

You can set the default authenticator for http requests like this:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});

Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)

How to set environment variables in Jenkins?

We use groovy job file:

description('')
steps {
    environmentVariables {
        envs(PUPPETEER_SKIP_CHROMIUM_DOWNLOAD: true)
    }
}

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

Get value of Span Text

Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).

As for the correct approach to grabbing the span text from the client I recommend Johns answer.

These are a good place to get started.

JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript

PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php

Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/

Have a reloadData for a UITableView animate when changing

Swift Implementation:

let range = NSMakeRange(0, self.tableView!.numberOfSections())
let indexSet = NSIndexSet(indexesInRange: range)
self.tableView!.reloadSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic)

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

Android - implementing startForeground for a service?

From your main activity, start the service with the following code:

Intent i = new Intent(context, MyService.class); 
context.startService(i);

Then in your service for onCreate() you would build your notification and set it as foreground like so:

Intent notificationIntent = new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.app_icon)
                .setContentTitle("My Awesome App")
                .setContentText("Doing some work...")
                .setContentIntent(pendingIntent).build();

startForeground(1337, notification);

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

For example two class A,B having same method m1(). And class C extends both A, B.

 class C extends A, B // for explaining purpose.

Now, class C will search the definition of m1. First, it will search in class if it didn't find then it will check to parents class. Both A, B having the definition So here ambiguity occur which definition should choose. So JAVA DOESN'T SUPPORT MULTIPLE INHERITANCE.

How can I convert JSON to CSV?

I am assuming that your JSON file will decode into a list of dictionaries. First we need a function which will flatten the JSON objects:

def flattenjson(b, delim):
    val = {}
    for i in b.keys():
        if isinstance(b[i], dict):
            get = flattenjson(b[i], delim)
            for j in get.keys():
                val[i + delim + j] = get[j]
        else:
            val[i] = b[i]
            
    return val

The result of running this snippet on your JSON object:

flattenjson({
    "pk": 22, 
    "model": "auth.permission", 
    "fields": {
      "codename": "add_message", 
      "name": "Can add message", 
      "content_type": 8
    }
  }, "__")

is

{
    "pk": 22, 
    "model": "auth.permission", 
    "fields__codename": "add_message", 
    "fields__name": "Can add message", 
    "fields__content_type": 8
}

After applying this function to each dict in the input array of JSON objects:

input = map(lambda x: flattenjson( x, "__" ), input)

and finding the relevant column names:

columns = [x for row in input for x in row.keys()]
columns = list(set(columns))

it's not hard to run this through the csv module:

with open(fname, 'wb') as out_file:
    csv_w = csv.writer(out_file)
    csv_w.writerow(columns)

    for i_r in input:
        csv_w.writerow(map(lambda x: i_r.get(x, ""), columns))

I hope this helps!

Mongoose limit/offset and count query

After having to tackle this issue myself, I would like to build upon user854301's answer.

Mongoose ^4.13.8 I was able to use a function called toConstructor() which allowed me to avoid building the query multiple times when filters are applied. I know this function is available in older versions too but you'll have to check the Mongoose docs to confirm this.

The following uses Bluebird promises:

let schema = Query.find({ name: 'bloggs', age: { $gt: 30 } });

// save the query as a 'template'
let query = schema.toConstructor();

return Promise.join(
    schema.count().exec(),
    query().limit(limit).skip(skip).exec(),

    function (total, data) {
        return { data: data, total: total }
    }
);

Now the count query will return the total records it matched and the data returned will be a subset of the total records.

Please note the () around query() which constructs the query.

Cancel a UIView animation?

Use:

#import <QuartzCore/QuartzCore.h>

.......

[myView.layer removeAllAnimations];

Encode/Decode URLs in C++

The Windows API has the functions UrlEscape/UrlUnescape, exported by shlwapi.dll, for this task.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

I found out, that I need to set the public property of devServer, to my request's host value. Being that it will be displayed at that external address.

So I needed this in my webpack.config.js

devServer: {
  compress: true,
  public: 'store-client-nestroia1.c9users.io' // That solved it
}

Another solution is using it on the CLI:

webpack-dev-server --public $C9_HOSTNAME <-- var for Cloud9 external IP

Gradle build without tests

You can add the following lines to build.gradle, **/* excludes all the tests.

test {
    exclude '**/*'
}

How can I find all of the distinct file extensions in a folder hierarchy?

My awk-less, sed-less, Perl-less, Python-less POSIX-compliant alternative:

find . -type f | rev | cut -d. -f1 | rev  | tr '[:upper:]' '[:lower:]' | sort | uniq --count | sort -rn

The trick is that it reverses the line and cuts the extension at the beginning.
It also converts the extensions to lower case.

Example output:

   3689 jpg
   1036 png
    610 mp4
     90 webm
     90 mkv
     57 mov
     12 avi
     10 txt
      3 zip
      2 ogv
      1 xcf
      1 trashinfo
      1 sh
      1 m4v
      1 jpeg
      1 ini
      1 gqv
      1 gcs
      1 dv

How to get Time from DateTime format in SQL?

select cast (as time(0))

would be a good clause. For example:

(select cast(start_date as time(0))) AS 'START TIME'

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Git: Create a branch from unstaged/uncommitted changes on master

In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:

enter image description here

The same applies if you simply switch the branch too.

Assignment inside lambda expression in Python

UPDATE:

[o for d in [{}] for o in lst if o.name != "" or d.setdefault("", o) == o]

or using filter and lambda:

flag = {}
filter(lambda o: bool(o.name) or flag.setdefault("", o) == o, lst)

Previous Answer

OK, are you stuck on using filter and lambda?

It seems like this would be better served with a dictionary comprehension,

{o.name : o for o in input}.values()

I think the reason that Python doesn't allow assignment in a lambda is similar to why it doesn't allow assignment in a comprehension and that's got something to do with the fact that these things are evaluated on the C side and thus can give us an increase in speed. At least that's my impression after reading one of Guido's essays.

My guess is this would also go against the philosophy of having one right way of doing any one thing in Python.

Can I use conditional statements with EJS templates (in JMVC)?

You can also use else if syntax:

<% if (x === 1) { %>
    <p>Hello world!</p>
<% } else if (x === 2) { %>
    <p>Hi earth!</p>
<% } else { %>
    <p>Hey terra!</p>
<% } %>

How to import a SQL Server .bak file into MySQL?

SQL Server databases are very Microsoft proprietary. Two options I can think of are:

  1. Dump the database in CSV, XML or similar format that you'd then load into MySQL.

  2. Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.

did you specify the right host or port? error on Kubernetes

I had same error, this worked for me. Run

minikube status

if the response is

type: Control Plane
host: Stopped
kubelet: Stopped
apiserver: Stopped
kubeconfig: Stopped

run minikube start

type: Control Plane
host: Running
kubelet: Running
apiserver: Running
kubeconfig: Configured

You can proceed

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}

Draw Circle using css alone

  • Create a div with a set height and width (so, for a circle, use the same height and width), forming a square
  • add a border-radius of 50% which will make it circular in shape. (note: no prefix has been required for a long time)
  • You can then play around with background-color / gradients / (even pseudo elements) to create something like this:

_x000D_
_x000D_
.red {_x000D_
  background-color: red;_x000D_
}_x000D_
.green {_x000D_
  background-color: green;_x000D_
}_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}_x000D_
.yellow {_x000D_
  background-color: yellow;_x000D_
}_x000D_
.sphere {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  vertical-align: middle;_x000D_
  font-size: 500%;_x000D_
  position: relative;_x000D_
  box-shadow: inset -10px -10px 100px #000, 10px 10px 20px black, inset 0px 0px 10px black;_x000D_
  display: inline-block;_x000D_
  margin: 5%;_x000D_
}_x000D_
.sphere::after {_x000D_
  background-color: rgba(255, 255, 255, 0.3);_x000D_
  content: '';_x000D_
  height: 45%;_x000D_
  width: 12%;_x000D_
  position: absolute;_x000D_
  top: 4%;_x000D_
  left: 15%;_x000D_
  border-radius: 50%;_x000D_
  transform: rotate(40deg);_x000D_
}
_x000D_
<div class="sphere red"></div>_x000D_
<div class="sphere green"></div>_x000D_
<div class="sphere blue"></div>_x000D_
<div class="sphere yellow"></div>_x000D_
<div class="sphere"></div>
_x000D_
_x000D_
_x000D_

How do I find the caller of a method using stacktrace or reflection?

I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.

I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).

It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.

Formatting ISODate from Mongodb

MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.

You can still use all of the same methods as working with a normal JS Date, such as:

ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()

// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()

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

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

How to Set focus to first text input in a bootstrap modal after shown

Try to remove the tabIndex property of the modal, when your input/textbox is open. Set it back to what ever it was, when you close input/textbox. This would resolve the issue irrespective bootstrap version, and without compromising the user experience flow.

How to check if array is not empty?

If you are talking about Python's actual array (available through import array from array), then the principle of least astonishment applies and you can check whether it is empty the same way you'd check if a list is empty.

from array import array
an_array = array('i') # an array of ints

if an_array:
    print("this won't be printed")

an_array.append(3)

if an_array:
    print("this will be printed")

Making HTTP Requests using Chrome Developer tools

I know, old post ... but it might be helpful to leave this here.

Modern browsers are now supporting the Fetch API.

You can use it like this:

fetch("<url>")
    .then(data => data.json()) // could be .text() or .blob() depending on the data you are expecting
    .then(console.log); // print your data

ps: It will make all CORS checks, since it's an improved XmlHttpRequest.

Check for null variable in Windows batch

Late answer, but currently the accepted one is at least suboptimal.

Using quotes is ALWAYS better than using any other characters to enclose %1.
Because when %1 contains spaces or special characters like &, the IF [%1] == simply stops with a syntax error.

But for the case that %1 contains quotes, like in myBatch.bat "my file.txt", a simple IF "%1" == "" would fail.

But as you can't know if quotes are used or not, there is the syntax %~1, this removes enclosing quotes when necessary.

Therefore, the code should look like

set "file1=%~1"
IF "%~1"=="" set "file1=default file"

type "%file1%"   --- always enclose your variables in quotes

If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?

Do while loop in SQL Server 2008

If you are not very offended by the GOTO keyword, it can be used to simulate a DO / WHILE in T-SQL. Consider the following rather nonsensical example written in pseudocode:

SET I=1
DO
 PRINT I
 SET I=I+1
WHILE I<=10

Here is the equivalent T-SQL code using goto:

DECLARE @I INT=1;
START:                -- DO
  PRINT @I;
  SET @I+=1;
IF @I<=10 GOTO START; -- WHILE @I<=10

Notice the one to one mapping between the GOTO enabled solution and the original DO / WHILE pseudocode. A similar implementation using a WHILE loop would look like:

DECLARE @I INT=1;
WHILE (1=1)              -- DO
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF NOT (@I<=10) BREAK; -- WHILE @I<=10
 END

Now, you could of course rewrite this particular example as a simple WHILE loop, since this is not such a good candidate for a DO / WHILE construct. The emphasis was on example brevity rather than applicability, since legitimate cases requiring a DO / WHILE are rare.


REPEAT / UNTIL, anyone (does NOT work in T-SQL)?

SET I=1
REPEAT
  PRINT I
  SET I=I+1
UNTIL I>10

... and the GOTO based solution in T-SQL:

DECLARE @I INT=1;
START:                    -- REPEAT
  PRINT @I;
  SET @I+=1;
IF NOT(@I>10) GOTO START; -- UNTIL @I>10

Through creative use of GOTO and logic inversion via the NOT keyword, there is a very close relationship between the original pseudocode and the GOTO based solution. A similar solution using a WHILE loop looks like:

DECLARE @I INT=1;
WHILE (1=1)       -- REPEAT
 BEGIN
  PRINT @I;
  SET @I+=1;
  IF @I>10 BREAK; -- UNTIL @I>10
 END

An argument can be made that for the case of the REPEAT / UNTIL, the WHILE based solution is simpler, because the if condition is not inverted. On the other hand it is also more verbose.

If it wasn't for all of the disdain around the use of GOTO, these might even be idiomatic solutions for those few times when these particular (evil) looping constructs are necessary in T-SQL code for the sake of clarity.

Use these at your own discretion, trying not to suffer the wrath of your fellow developers when they catch you using the much maligned GOTO.

How can I reverse the order of lines in a file?

I really like the "tail -r" answer, but my favorite gawk answer is....

gawk '{ L[n++] = $0 } 
  END { while(n--) 
        print L[n] }' file

How to configure port for a Spring Boot application

Hope this one help

application.properties=> 

server.port=8090

application.yml=> 

server
  port:8090

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

node.js require() cache - possible to invalidate?

Following two step procedure is working perfectly for me.

After changing Model file i-e 'mymodule.js' dynamically, you need to Delete precompiled model in mongoose model first then reload it using require-reload

Example:
        // Delete mongoose model
        delete mongoose.connection.models[thisObject.singular('mymodule')]

        // Reload model
        var reload = require('require-reload')(require);
        var entityModel = reload('./mymodule.js');

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

How to check list A contains any value from list B?

I write a faster method for it can make the small one to set. But I test it in some data that some time it's faster that Intersect but some time Intersect fast that my code.

    public static bool Contain<T>(List<T> a, List<T> b)
    {
        if (a.Count <= 10 && b.Count <= 10)
        {
            return a.Any(b.Contains);
        }

        if (a.Count > b.Count)
        {
            return Contain((IEnumerable<T>) b, (IEnumerable<T>) a);
        }
        return Contain((IEnumerable<T>) a, (IEnumerable<T>) b);
    }

    public static bool Contain<T>(IEnumerable<T> a, IEnumerable<T> b)
    {
        HashSet<T> j = new HashSet<T>(a);
        return b.Any(j.Contains);
    }

The Intersect calls Set that have not check the second size and this is the Intersect's code.

        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in second) set.Add(element);
        foreach (TSource element in first)
            if (set.Remove(element)) yield return element;

The difference in two methods is my method use HashSet and check the count and Intersect use set that is faster than HashSet. We dont warry its performance.

The test :

   static void Main(string[] args)
    {
        var a = Enumerable.Range(0, 100000);
        var b = Enumerable.Range(10000000, 1000);
        var t = new Stopwatch();
        t.Start();
        Repeat(()=> { Contain(a, b); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//490ms

        var a1 = Enumerable.Range(0, 100000).ToList();
        var a2 = b.ToList();
        t.Restart();
        Repeat(()=> { Contain(a1, a2); });
        t.Stop();

        Console.WriteLine(t.ElapsedMilliseconds);//203ms

        t.Restart();
        Repeat(()=>{ a.Intersect(b).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//190ms

        t.Restart();
        Repeat(()=>{ b.Intersect(a).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//497ms

        t.Restart();
        a.Any(b.Contains);
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//600ms

    }

    private static void Repeat(Action a)
    {
        for (int i = 0; i < 100; i++)
        {
            a();
        }
    }

Get the Application Context In Fragment In Android?

You can get the context using getActivity().getApplicationContext();

Changing the resolution of a VNC session in linux

Perhaps the most ignorant answer I've posted but here goes: Use TigerVNC client/viewer and check 'Resize remote session to local window' under Screen tab of options.

I don't know what the $%#@ TigerVNC client tells remote vncserver or xrandr or Xvnc or gnome or ... but it resizes when I change the TigerVNC Client window.

My setup:

  • Tiger VNC Server running on CentOS 6. Hosting GNOME desktop. (Works with RHEL 6.6 too)
  • Windows some version with Tiger VNC Client.

With this the resolution changes to fit the size of the client window no matter what it is, and it's not zooming, it's actual resolution change (I can see the new resolution in xrandr output).

I tried all I could to add a new resolution to the xrandr, but to no avail, always end up with 'xrandr: Failed to get size of gamma for output default' error.

Versions with which it works for me right now (although I've not had issues with ANY versions in the past, I just install the latest using yum install gnome-* tigervnc-server and works fine):

OS: RHEL 6.6 (Santiago)
VNC Server:
Name        : tigervnc-server
Arch        : x86_64
Version     : 1.1.0
Release     : 16.el6

# May be this is relevant..
$ xrandr --version
xrandr program version       1.4.0
Server reports RandR version 1.4
$ 

# I start the server using vncserver -geometry 800x600
# Xvnc is started by vncserver with following args:
/usr/bin/Xvnc :1 -desktop plabb13.sgdcelab.sabre.com:1 (sg219898) -auth /login/sg219898/.Xauthority 
-geometry 800x600 -rfbwait 30000 -rfbauth /login/sg219898/.vnc/passwd -rfbport 5901 -fp catalogue:/e
tc/X11/fontpath.d -pn


# I'm running GNOME (installed using sudo yum install gnome-*)
Name        : gnome-desktop
Arch        : x86_64
Version     : 2.28.2
Release     : 11.el6

Name        : gnome-session
Arch        : x86_64
Version     : 2.28.0
Release     : 22.el6

Connect using Tiger 32-bit VNC Client v1.3.1 on Windows 7.

How do I convert hex to decimal in Python?

>>> int("0xff", 16)
255

or

>>> int("FFFF", 16)
65535

Read the docs.

Parsing HTML using Python

I would use EHP

https://github.com/iogf/ehp

Here it is:

from ehp import *

doc = '''<html>
<head>Heading</head>
<body attr1='val1'>
    <div class='container'>
        <div id='class'>Something here</div>
        <div>Something else</div>
    </div>
</body>
</html>
'''

html = Html()
dom = html.feed(doc)
for ind in dom.find('div', ('class', 'container')):
    print ind.text()

Output:

Something here
Something else

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.

https://developers.google.com/oauthplayground/

Adding text to a cell in Excel using VBA

Range("$A$1").Value = "'01/01/13 00:00" will do it.

Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.

Javascript onload not working

You can try use in javascript:

window.onload = function() {
 alert("let's go!");
}

Its a good practice separate javascript of html

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Spacing between elements

In general we use margins on one of the elements, not spacer elements.

PHP array delete by value (not key)

As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

Input:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

How to add a delay for a 2 or 3 seconds

Use a timer with an interval set to 2–3 seconds.

You have three different options to choose from, depending on which type of application you're writing:

  1. System.Timers.Timer
  2. System.Windows.Forms.Timer
  3. System.Threading.Timer

Don't use Thread.Sleep if your application need to process any inputs on that thread at the same time (WinForms, WPF), as Sleep will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just delaying an operation as you probably intended. Note that it may be fine to use Sleep in pure console application as there are no "events" to handle or on separate thread (also Task.Delay is better option).

In addition to timers and Sleep you can use Task.Delay which is asynchronous version of Sleep that does not block thread from processing events (if used properly - don't turn it into infinite sleep with .Wait()).

 public async void ClickHandler(...)
 {
      // whatever you need to do before delay goes here         

      await Task.Delay(2000);

      // whatever you need to do after delay.
 }

The same await Task.Delay(2000) can be used in a Main method of a console application if you use C# 7.1 (Async main on MSDN blogs).

Note: delaying operation with Sleep has benefit of avoiding race conditions that comes from potentially starting multiple operations with timers/Delay. Unfortunately freezing UI-based application is not acceptable so you need to think about what will happen if you start multiple delays (i.e. if it is triggered by a button click) - consider disabling such button, or canceling the timer/task or making sure delayed operation can be done multiple times safely.

operator << must take exactly one argument

If you define operator<< as a member function it will have a different decomposed syntax than if you used a non-member operator<<. A non-member operator<< is a binary operator, where a member operator<< is a unary operator.

// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);

struct MyObj
{
    // This is a member unary-operator, hence one argument
    MyObj& operator<<(std::ostream& os) { os << *this; return *this; }

    int value = 8;
};

// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
    return os << myObj.value;
}

So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...) syntax in your head to make things make sense.

MyObj mo;

// Calling the unary operator
mo << std::cout;

// which decomposes to...
mo.operator<<(std::cout);

Or you could attempt to call the non-member binary operator:

MyObj mo;

// Calling the binary operator
std::cout << mo;

// which decomposes to...
operator<<(std::cout, mo);

You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int) to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.

Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.

Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)

struct MyObj
{
    // Note that we now return the ostream
    std::ostream& operator<<(std::ostream& os) { os << *this; return os; }

    int value = 8;
};

This syntax will irritate many coders now....

MyObj mo;

mo << std::cout << "Words words words";

// this decomposes to...
mo.operator<<(std::cout) << "Words words words";

// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");

Note how the cout is the second argument in the chain here.... odd right?

“Unable to find manifest signing certificate in the certificate store” - even when add new key

If you need just build the project or solution locally then removing the signing might be a dead simple solution as others suggest.

But if you have this error on your automation build server like TeamCity where you build your actual release pieces for deployment or distribution you might want to consider how you can get this cert properly installed to the cert store on the build machine, so that you get a signed packages at the end of the build.

Generally it is not recommenced to check-in/commit any PFX certificates into source control, so how you get this files on your build server during the build process is a bit another question, but sometimes people do have this file stored along with the solution code, so you can find it in the project folder.

All you need to do is just install this certificate under proper account on your build server.

  1. Download PsExec from Windows Sysinternals.

  2. Open a command prompt, and enter the following. It will spawn a new command prompt, running as Local System (assuming that your TeamCity is running under the default Local System account):

    > psexec.exe -i -s cmd.exe

  3. In this new command prompt, change to the directory containing the certificate and enter the filename to install (change the name of the file to yours):

    > mykey.pfx

  4. The Import Certificate wizard will start up. Click through and select all the suggested defaults.

  5. Run the build.

All credits goes to Stuart Noble (and then further to Laurent Kempé I believe ?).

Opening port 80 EC2 Amazon web services

For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.

See here on how to completely disable it (for testing purposes only!). And here for specific rules

How can I get onclick event on webview in android?

I took a look at this and I found that a WebView doesn't seem to send click events to an OnClickListener. If anyone out there can prove me wrong or tell me why then I'd be interested to hear it.

What I did find is that a WebView will send touch events to an OnTouchListener. It does have its own onTouchEvent method but I only ever seemed to get MotionEvent.ACTION_MOVE using that method.

So given that we can get events on a registered touch event listener, the only problem that remains is how to circumvent whatever action you want to perform for a touch when the user clicks a URL.

This can be achieved with some fancy Handler footwork by sending a delayed message for the touch and then removing those touch messages if the touch was caused by the user clicking a URL.

Here's an example:

public class WebViewClicker extends Activity implements OnTouchListener, Handler.Callback {

private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;

private final Handler handler = new Handler(this);

private WebView webView;
private WebViewClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web_view_clicker);

    webView = (WebView)findViewById(R.id.web);
    webView.setOnTouchListener(this);

    client = new WebViewClient(){ 
        @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            handler.sendEmptyMessage(CLICK_ON_URL);
            return false;
        } 
    }; 

    webView.setWebViewClient(client);
    webView.setVerticalScrollBarEnabled(false);
    webView.loadUrl("http://www.example.com");
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (v.getId() == R.id.web && event.getAction() == MotionEvent.ACTION_DOWN){
        handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
    }
    return false;
}

@Override
public boolean handleMessage(Message msg) {
    if (msg.what == CLICK_ON_URL){
        handler.removeMessages(CLICK_ON_WEBVIEW);
        return true;
    }
    if (msg.what == CLICK_ON_WEBVIEW){
        Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}
}


Hope this helps.

What is the parameter "next" used for in Express?

I also had problem understanding next() , but this helped

var app = require("express")();

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write("Hello");
    next(); //remove this and see what happens 
});

app.get("/", function(httpRequest, httpResponse, next){
    httpResponse.write(" World !!!");
    httpResponse.end();
});

app.listen(8080);

Write Array to Excel Range

The kind of array definition seems the key: In my case it is a one dimension array of 17 items which have to convert to a two dimension array

Defintion for columns: object[,] Array = new object[17, 1];

Defintion for rows object[,] Array= new object[1,17];

The code for value2 is in both cases the same Excel.Range cell = activeWorksheet.get_Range(Range); cell.Value2 = Array;

LG Georg

Can I run a 64-bit VMware image on a 32-bit machine?

If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.

Get all parameters from JSP page

The fastest way should be:

<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
    if (entry.getKey().startsWith("question")) {
        String[] values = entry.getValue();
        // etc.

Note that you can't do:

for (Map.Entry<String, String[]> entry : 
     request.getParameterMap().entrySet()) { // WRONG!

for reasons explained here.

What are .NumberFormat Options In Excel VBA?

dovers gives us his great answer and based on it you can try use it like

public static class CellDataFormat
{
        public static string General { get { return "General"; } }
        public static string Number { get { return "0"; } }

        // Your custom format 
        public static string NumberDotTwoDigits { get { return "0.00"; } }

        public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
        public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
        public static string Date { get { return "m/d/yy"; } }
        public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
        public static string Percentage { get { return "0.00%"; } }
        public static string Fraction { get { return "# ?/?"; } }
        public static string Scientific { get { return "0.00E+00"; } }
        public static string Text { get { return "@"; } }
        public static string Special { get { return ";;"; } }
        public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}

Execute PowerShell Script from C# with Commandline Arguments

I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));

string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));

With the contents of the script being:

$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable

How to split a string in shell and get the last field

A solution using the read builtin:

IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"

Or, to make it more generic:

echo "${fields[-1]}" # prints the last item

How to append rows to an R data frame

Let's benchmark the three solutions proposed:

# use rbind
f1 <- function(n){
  df <- data.frame(x = numeric(), y = character())
  for(i in 1:n){
    df <- rbind(df, data.frame(x = i, y = toString(i)))
  }
  df
}
# use list
f2 <- function(n){
  df <- data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)
  for(i in 1:n){
    df[i,] <- list(i, toString(i))
  }
  df
}
# pre-allocate space
f3 <- function(n){
  df <- data.frame(x = numeric(1000), y = character(1000), stringsAsFactors = FALSE)
  for(i in 1:n){
    df$x[i] <- i
    df$y[i] <- toString(i)
  }
  df
}
system.time(f1(1000))
#   user  system elapsed 
#   1.33    0.00    1.32 
system.time(f2(1000))
#   user  system elapsed 
#   0.19    0.00    0.19 
system.time(f3(1000))
#   user  system elapsed 
#   0.14    0.00    0.14

The best solution is to pre-allocate space (as intended in R). The next-best solution is to use list, and the worst solution (at least based on these timing results) appears to be rbind.

Unsupported major.minor version 52.0 in my app

The problem specified:

Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.

is caused when is declared inside the build.gradle, buildToolsVersion 24 and we don´t have Java 8 installed that is required for this version. To solve this problem we have to change from buildToolsVersion from 24 to maximum 23:

enter image description here

Java 8 must be required in the future for Android Studio, so we have to start using Java 8.

How to do a SOAP wsdl web services call from the command line

curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:ACTION_YOU_WANT_TO_CALL" --data @FILE_NAME URL_OF_THE_SERVICE 

Above command was helpful for me

Example

curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:urn:GetVehicleLimitedInfo" --data @request.xml http://11.22.33.231:9080/VehicleInfoQueryService.asmx 

More info

stdlib and colored output in C

You can assign one color to every functionality to make it more useful.

#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)

foo()
{
LOG_RED("This is in Red Color");
}

Like wise you can select different color codes and make this more generic.

If statement in aspx page

To use C# (C# Script was initialized at 2015) on ASPX page you can make use the following syntax.

Start Tag:- <% End tag:- %> Please make sure that all the C# code must reside inside this <%%> .

Syntax Example:-

  • <%@ Import Namespace="System.Web.UI.WebControls" %> (For importing Namespace) Reference to some basic namespaces for working with ASPX page.

    <%@ Import Namespace="System.Web.UI.WebControls" %> <%@ Import Namespace="System.Diagnostics" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.UI" %> <%@ Import Namespace="System.IO" %>

C# Code:-

`<%
if (Session["New"] != null)
{
    Page.Title = ActionController.GetName(Session["New"].ToString());
}
%>`

Features of C# Script:

  • No need of compilation. Run time execution is occurred like Java Script.

Before using C# script make sure the following things:-

  • You are on WebForm. Not on WebForm with master page.
  • If you are in WebForm with master page make sure that you have written your C# script at Master page file.
  • C# script can be inserted anywhere in the aspx page but after the page meta declaration like

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Profile.master.cs" Inherits="OOSDDemo.Profile" %>

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %> (For WebForm)

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

Floating point exception( core dump

Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php

In a nutshell, these commands might be useful...

gcc -g myprog.c

gdb a.out

gdb core a.out

ddd a.out

How to convert a string to ASCII

Try Linq:

Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));

This will filter out all non ascii characters. Now if you want an equivalent, try the following:

Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));

Pressing Ctrl + A in Selenium WebDriver

It works for me:

OpenQA.Selenium.Interactions.Actions action 
    = new OpenQA.Selenium.Interactions.Actions(browser);
action.KeyDown(OpenQA.Selenium.Keys.Control)
    .SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).Perform();

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

_x000D_
_x000D_
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
  color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
_x000D_
_x000D_

How do I remove a property from a JavaScript object?

If you don't want to modify the original object.

Remove a property without mutating the object

If mutability is a concern, you can create a completely new object by copying all the properties from the old, except the one you want to remove.

_x000D_
_x000D_
let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

let prop = 'regex';
const updatedObject = Object.keys(myObject).reduce((object, key) => {
  if (key !== prop) {
    object[key] = myObject[key]
  }
  return object
}, {})

console.log(updatedObject);
_x000D_
_x000D_
_x000D_

Create a list with initial capacity in Python

Short version: use

pre_allocated_list = [None] * size

to preallocate a list (that is, to be able to address 'size' elements of the list instead of gradually forming the list by appending). This operation is very fast, even on big lists. Allocating new objects that will be later assigned to list elements will take much longer and will be the bottleneck in your program, performance-wise.

Long version:

I think that initialization time should be taken into account.

Since in Python everything is a reference, it doesn't matter whether you set each element into None or some string - either way it's only a reference. Though it will take longer if you want to create a new object for each element to reference.

For Python 3.2:

import time
import copy

def print_timing (func):
  def wrapper (*arg):
    t1 = time.time()
    res = func (*arg)
    t2 = time.time ()
    print ("{} took {} ms".format (func.__name__, (t2 - t1) * 1000.0))
    return res

  return wrapper

@print_timing
def prealloc_array (size, init = None, cp = True, cpmethod = copy.deepcopy, cpargs = (), use_num = False):
  result = [None] * size
  if init is not None:
    if cp:
      for i in range (size):
          result[i] = init
    else:
      if use_num:
        for i in range (size):
            result[i] = cpmethod (i)
      else:
        for i in range (size):
            result[i] = cpmethod (cpargs)
  return result

@print_timing
def prealloc_array_by_appending (size):
  result = []
  for i in range (size):
    result.append (None)
  return result

@print_timing
def prealloc_array_by_extending (size):
  result = []
  none_list = [None]
  for i in range (size):
    result.extend (none_list)
  return result

def main ():
  n = 1000000
  x = prealloc_array_by_appending(n)
  y = prealloc_array_by_extending(n)
  a = prealloc_array(n, None)
  b = prealloc_array(n, "content", True)
  c = prealloc_array(n, "content", False, "some object {}".format, ("blah"), False)
  d = prealloc_array(n, "content", False, "some object {}".format, None, True)
  e = prealloc_array(n, "content", False, copy.deepcopy, "a", False)
  f = prealloc_array(n, "content", False, copy.deepcopy, (), False)
  g = prealloc_array(n, "content", False, copy.deepcopy, [], False)

  print ("x[5] = {}".format (x[5]))
  print ("y[5] = {}".format (y[5]))
  print ("a[5] = {}".format (a[5]))
  print ("b[5] = {}".format (b[5]))
  print ("c[5] = {}".format (c[5]))
  print ("d[5] = {}".format (d[5]))
  print ("e[5] = {}".format (e[5]))
  print ("f[5] = {}".format (f[5]))
  print ("g[5] = {}".format (g[5]))

if __name__ == '__main__':
  main()

Evaluation:

prealloc_array_by_appending took 118.00003051757812 ms
prealloc_array_by_extending took 102.99992561340332 ms
prealloc_array took 3.000020980834961 ms
prealloc_array took 49.00002479553223 ms
prealloc_array took 316.9999122619629 ms
prealloc_array took 473.00004959106445 ms
prealloc_array took 1677.9999732971191 ms
prealloc_array took 2729.999780654907 ms
prealloc_array took 3001.999855041504 ms
x[5] = None
y[5] = None
a[5] = None
b[5] = content
c[5] = some object blah
d[5] = some object 5
e[5] = a
f[5] = []
g[5] = ()

As you can see, just making a big list of references to the same None object takes very little time.

Prepending or extending takes longer (I didn't average anything, but after running this a few times I can tell you that extending and appending take roughly the same time).

Allocating new object for each element - that is what takes the most time. And S.Lott's answer does that - formats a new string every time. Which is not strictly required - if you want to preallocate some space, just make a list of None, then assign data to list elements at will. Either way it takes more time to generate data than to append/extend a list, whether you generate it while creating the list, or after that. But if you want a sparsely-populated list, then starting with a list of None is definitely faster.

From Now() to Current_timestamp in Postgresql

Here is what the MySQL docs say about NOW():

Returns the current date and time as a value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone.

mysql> SELECT NOW();
        -> '2007-12-15 23:50:26'
mysql> SELECT NOW() + 0;
        -> 20071215235026.000000

Now, you can certainly reduce your smart date to something less...

SELECT (
 date_part('year', NOW())::text
 || date_part('month', NOW())::text
 || date_part('day', NOW())::text
 || date_part('hour', NOW())::text
 || date_part('minute', NOW())::text
 || date_part('second', NOW())::text
)::float8 + foo;

But, that would be a really bad idea, what you need to understand is that times and dates are not stupid unformated numbers, they are their own type with their own set of functions and operators

So the MySQL time essentially lets you treat NOW() as a dumber type, or it overrides + to make a presumption that I can't find in the MySQL docs. Eitherway, you probably want to look at the date and interval types in pg.

ORA-00972 identifier is too long alias column name

As others have referred, names in Oracle SQL must be less or equal to 30 characters. I would add that this rule applies not only to table names but to field names as well. So there you have it.

Use URI builder in Android or create URL with variables

Let's say that I want to create the following URL:

https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name

To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.myawesomesite.com")
    .appendPath("turtles")
    .appendPath("types")
    .appendQueryParameter("type", "1")
    .appendQueryParameter("sort", "relevance")
    .fragment("section-name");
String myUrl = builder.build().toString();

SVN Error - Not a working copy

You must have deleted a SVN - base file from your project (which are read-only files). Due to this you get this error.

Check out a fresh project again, merge the changes (if any) of your older SVN project with new one using "Winmerge" and commit the changes in your latest check out.

How to fix a Div to top of page with CSS only

You can do something like this:

<html>
<head><title>My Glossary</title></head>
<body style="margin:0px;">
        <div id="top" style="position:fixed;background:white;width:100%;">
            <a href="#A">A</a> |
             <a href="#B">B</a> |
            <a href="#Z">Z</a>
        </div>

        <div id="term-defs" style="padding-top:1em;">
           <dl>
               <span id="A"></span>
               <dt>foo</dt>
               <dd>This is the sound made by a fool</dd>
               <!-- and so on ... ->
           </dl>
        </div>
</body>
</html>

It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.

Hope this helps.

JavaScript: What are .extend and .prototype used for?

Javascript inheritance seems to be like an open debate everywhere. It can be called "The curious case of Javascript language".

The idea is that there is a base class and then you extend the base class to get an inheritance-like feature (not completely, but still).

The whole idea is to get what prototype really means. I did not get it until I saw John Resig's code (close to what jQuery.extend does) wrote a code chunk that does it and he claims that base2 and prototype libraries were the source of inspiration.

Here is the code.

    /* Simple JavaScript Inheritance
     * By John Resig http://ejohn.org/
     * MIT Licensed.
     */  
     // Inspired by base2 and Prototype
    (function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

There are three parts which are doing the job. First, you loop through the properties and add them to the instance. After that, you create a constructor for later to be added to the object.Now, the key lines are:

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

You first point the Class.prototype to the desired prototype. Now, the whole object has changed meaning that you need to force the layout back to its own one.

And the usage example:

var Car = Class.Extend({
  setColor: function(clr){
    color = clr;
  }
});

var volvo = Car.Extend({
   getColor: function () {
      return color;
   }
});

Read more about it here at Javascript Inheritance by John Resig 's post.

How to set background color of view transparent in React Native

The following works fine:

backgroundColor: 'rgba(52, 52, 52, alpha)'

You could also try:

backgroundColor: 'transparent'

SQL Query to add a new column after an existing column in SQL Server 2005

If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.

How to force div to appear below not next to another?

use clear:left; or clear:both in your css.

#map { float:left; width:700px; height:500px; }
 #list { float:left; width:200px; background:#eee; list-style:none; padding:0; }
 #similar { float:left; width:200px; background:#000; clear:both; } 


<div id="map"></div>        
<ul id="list"></ul>
<div id ="similar">
 this text should be below, not next to ul.
</div>

Find the most popular element in int[] array

public int getPopularElement(int[] a)
{
  int count = 1, tempCount;
  int popular = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > count)
    {
      popular = temp;
      count = tempCount;
    }
  }
  return popular;
}

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

SQL Query - how do filter by null or not null

How about statusid = statusid. Null is never equal to null.

How do I specify new lines on Python, when writing on files?

Simplest solution

If you only call print without any arguments, it will output a blank line.

print

You can pipe the output to a file like this (considering your example):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()

Not only is it OS-agnostic (without even having to use the os package), it's also more readable than putting \n within strings.

Explanation

The print() function has an optional keyword argument for the end of the string, called end, which defaults to the OS's newline character, for eg. \n. So, when you're calling print('hello'), Python is actually printing 'hello' + '\n'. Which means that when you're calling just print without any arguments, it's actually printing '' + '\n', which results in a newline.

Alternative

Use multi-line strings.

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()

Javascript: set label text

InnerHTML should be innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft;

You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});

You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:

function checkLength(obj, maxlength, label) {
    charsleft = (maxlength - obj.val().length);
    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }
    // I'm trying to set the value of charsleft into the label
    label.text(charsleft);
    $('#LblAboutMeCount').html(charsleft);
}

So if you apply the above, you can change your markup to:

<textarea name="text"></textarea>

How to set child process' environment variable in Makefile

Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export to force them to do so. Change:

test: NODE_ENV = test

to this:

test: export NODE_ENV = test

(assuming you have a sufficiently modern version of GNU make >= 3.77 ).

Objective-C ARC: strong vs retain and weak vs assign

After reading so many articles Stackoverflow posts and demo applications to check variable property attributes, I decided to put all the attributes information together:

  1. atomic //default
  2. nonatomic
  3. strong=retain //default
  4. weak
  5. retain
  6. assign //default
  7. unsafe_unretained
  8. copy
  9. readonly
  10. readwrite //default

Below is the detailed article link where you can find above mentioned all attributes, that will definitely help you. Many thanks to all the people who give best answers here!!

Variable property attributes or Modifiers in iOS

1.strong (iOS4 = retain )

  • it says "keep this in the heap until I don't point to it anymore"
  • in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain"
  • You use strong only if you need to retain the object.
  • By default all instance variables and local variables are strong pointers.
  • We generally use strong for UIViewControllers (UI item's parents)
  • strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

Example:

@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;

2.weak -

  • it says "keep this as long as someone else points to it strongly"
  • the same thing as assign, no retain or release
  • A "weak" reference is a reference that you do not retain.
  • We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does.
  • a weak reference is a reference that does not protect the referenced object from collection by a garbage collector.
  • Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;

Strong & Weak Explanation, Thanks to BJ Homer:

Imagine our object is a dog, and that the dog wants to run away (be deallocated).

Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.

Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.

As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.

When we use weak?

The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

3.retain = strong

  • it is retained, old value is released and it is assigned retain specifies the new value should be sent
  • retain on assignment and the old value sent -release
  • retain is the same as strong.
  • apple says if you write retain it will auto converted/work like strong only.
  • methods like "alloc" include an implicit "retain"

Example:

@property (nonatomic, retain) NSString *name;

@synthesize name;

4.assign

  • assign is the default and simply performs a variable assignment
  • assign is a property attribute that tells the compiler how to synthesize the property's setter implementation
  • I would use assign for C primitive properties and weak for weak references to Objective-C objects.

Example:

@property (nonatomic, assign) NSString *address;

@synthesize address;

XPath query to get nth instance of an element

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

MySQL SELECT query string matching

You can use regular expressions like this:

SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

I ran into this when checking on a null or empty string

if (x == NULL || x == '') {

changed it to

if (is.null(x) || x == '') {

MAMP mysql server won't start. No mysql processes are running

This is what worked for me (Windows 10) :

  1. Click on Start Servers in MAMP
  2. Manually click on mysql.exe in MAMP installation folder (C:\MAMP\bin\mysql\bin\mysql.exe)

Tip : You can pin mysql.exe to Start Menu so you don't always have to search for this folder

Reading CSV file and storing values into an array

Hi all, I created a static class for doing this. + column check + quota sign removal

public static class CSV
{
    public static List<string[]> Import(string file, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        return ReadCSVFile(file, csvDelimiter, ignoreHeadline, removeQuoteSign);
    }

    private static List<string[]> ReadCSVFile(string filename, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
    {
        string[] result = new string[0];
        List<string[]> lst = new List<string[]>();

        string line;
        int currentLineNumner = 0;
        int columnCount = 0;

        // Read the file and display it line by line.  
        using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
        {
            while ((line = file.ReadLine()) != null)
            {
                currentLineNumner++;
                string[] strAr = line.Split(csvDelimiter);
                // save column count of dirst line
                if (currentLineNumner == 1)
                {
                    columnCount = strAr.Count();
                }
                else
                {
                    //Check column count of every other lines
                    if (strAr.Count() != columnCount)
                    {
                        throw new Exception(string.Format("CSV Import Exception: Wrong column count in line {0}", currentLineNumner));
                    }
                }

                if (removeQuoteSign) strAr = RemoveQouteSign(strAr);

                if (ignoreHeadline)
                {
                    if(currentLineNumner !=1) lst.Add(strAr);
                }
                else
                {
                    lst.Add(strAr);
                }
            }

        }

        return lst;
    }
    private static string[] RemoveQouteSign(string[] ar)
    {
        for (int i = 0;i< ar.Count() ; i++)
        {
            if (ar[i].StartsWith("\"") || ar[i].StartsWith("'")) ar[i] = ar[i].Substring(1);
            if (ar[i].EndsWith("\"") || ar[i].EndsWith("'")) ar[i] = ar[i].Substring(0,ar[i].Length-1);

        }
        return ar;
    }

}

Code line wrapping - how to handle long lines

IMHO this is the best way to write your line :

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
        new HashMap<Class<? extends Persistent>, PersistentHelper>();

This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.

Solve Cross Origin Resource Sharing with Flask

I used decorator given by Armin Ronacher with little modifications (due to different headers that are requested by the client).And that worked for me. (where I use angular as the requester requesting application/json type).

The code is slightly modified at below places,

from flask import jsonify

@app.route('/my_service', methods=['POST', 'GET','OPTIONS'])
@crossdomain(origin='*',headers=['access-control-allow-origin','Content-Type'])
def my_service():
    return jsonify(foo='cross domain ftw')

jsonify will send a application/json type, else it will be text/html. headers are added as the client in my case request for those headers

 const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin':'*'
      })
    };
    return this.http.post<any>(url, item,httpOptions)

How do I separate an integer into separate digits in an array in JavaScript?

var num = 123456789;
num = num.toString(); //'123456789'
var digits = num.split(""); //[ '1', '2', '3', '4', '5', '6', '7', '8', '9' ]

Git cli: get user info from username

Use this to see the logged in user (the actual git account):

git config credential.username

And as other answers the user email and user name (this is differenct from user credentials):

git config user.name
git config user.email

To see the list of all configs:

git config --list

Checking to see if one array's elements are in another array in PHP

Performance test for in_array vs array_intersect:

$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);

$a2 = array(3,20);

$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
    /***** TEST ONE array_intersect *******/
    $t = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = array_intersect($a1,$a2);
        $x = empty($x);
    }
    $intersect_times[] = microtime(true) - $t;


    /***** TEST TWO in_array *******/
    $t2 = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = false;
        foreach($a2 as $v){
            if(in_array($v,$a1))
            {
                $x = true;
                break;
            }
        }
    }
    $in_array_times[] = microtime(true) - $t2;
}

echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;

Here are the results:

0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354

0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906

in_array is at least 5 times faster. Note that we "break" as soon as a result is found.

How to create an empty array in PHP with predefined size?

There is no way to create an array of a predefined size without also supplying values for the elements of that array.


The best way to initialize an array like that is array_fill. By far preferable over the various loop-and-insert solutions.

$my_array = array_fill(0, $size_of_the_array, $some_data);

Every position in the $my_array will contain $some_data.

The first zero in array_fill just indicates the index from where the array needs to be filled with the value.

How to implement a secure REST API with node.js

If you want to secure your application, then you should definitely start by using HTTPS instead of HTTP, this ensures a creating secure channel between you & the users that will prevent sniffing the data sent back & forth to the users & will help keep the data exchanged confidential.

You can use JWTs (JSON Web Tokens) to secure RESTful APIs, this has many benefits when compared to the server-side sessions, the benefits are mainly:

1- More scalable, as your API servers will not have to maintain sessions for each user (which can be a big burden when you have many sessions)

2- JWTs are self contained & have the claims which define the user role for example & what he can access & issued at date & expiry date (after which JWT won't be valid)

3- Easier to handle across load-balancers & if you have multiple API servers as you won't have to share session data nor configure server to route the session to same server, whenever a request with a JWT hit any server it can be authenticated & authorized

4- Less pressure on your DB as well as you won't have to constantly store & retrieve session id & data for each request

5- The JWTs can't be tampered with if you use a strong key to sign the JWT, so you can trust the claims in the JWT that is sent with the request without having to check the user session & whether he is authorized or not, you can just check the JWT & then you are all set to know who & what this user can do.

Many libraries provide easy ways to create & validate JWTs in most programming languages, for example: in node.js one of the most popular is jsonwebtoken

Since REST APIs generally aims to keep the server stateless, so JWTs are more compatible with that concept as each request is sent with Authorization token that is self contained (JWT) without the server having to keep track of user session compared to sessions which make the server stateful so that it remembers the user & his role, however, sessions are also widely used & have their pros, which you can search for if you want.

One important thing to note is that you have to securely deliver the JWT to the client using HTTPS & save it in a secure place (for example in local storage).

You can learn more about JWTs from this link

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

How to get the unix timestamp in C#

This is what I use:

public long UnixTimeNow()
{
    var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
    return (long)timeSpan.TotalSeconds;
}

Keep in mind that this method will return the time as Coordinated Univeral Time (UTC).

if (boolean == false) vs. if (!boolean)

Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE) instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false).

GenyMotion Unable to start the Genymotion virtual device

I know this post is old, but in case someone is searching google i think i should mention what fixed my problem. After the 3 steps from above the error message was gone but the screen still stayed black and opening an .apk got stuck on file transfer. It had something to do with a VPN application (in my case Hamachi). I just closed it and then the emulator ran fine. This post prompted me to do so: https://groups.google.com/forum/#!searchin/genymotion-users/network/genymotion-users/QAX_UrAzEn0/o947IXpsDuIJ

How to add icon to mat-icon-button

All you need to do is add the mat-icon-button directive to the button element in your template. Within the button element specify your desired icon with a mat-icon component.

You'll need to import MatButtonModule and MatIconModule in your app module file.

From the Angular Material buttons example page, hit the view code button and you'll see several examples which use the material icons font, eg.

<button mat-icon-button>
  <mat-icon aria-label="Example icon-button with a heart icon">favorite</mat-icon>
</button>

In your case, use

<mat-icon>thumb_up</mat-icon>

As per the getting started guide at https://material.angular.io/guide/getting-started, you'll need to load the material icon font in your index.html.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Or import it in your global styles.scss.

@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

As it mentions, any icon font can be used with the mat-icon component.

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

What's the difference between Sender, From and Return-Path?

A minor update to this: a sender should never set the Return-Path: header. There's no such thing as a Return-Path: header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From unless the local system needs some kind of quirky routing.

It's a common misunderstanding because users rarely see an email without a Return-Path: header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path: header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4

Regular expression to detect semi-colon terminated C++ for & while loops

Another thought that ignores parentheses and treats the for as a construct holding three semicolon-delimited values:

for\s*\([^;]+;[^;]+;[^;]+\)\s*;

This option works even when split over multiple lines (once MULTILINE enabled), but assumes that for ( ... ; ... ; ... ) is the only valid construct, so wouldn't work with a for ( x in y ) construct, or other deviations.

Also assumes that there are no functions containing semi-colons as arguments, such as:

for ( var i = 0; i < ListLen('a;b;c',';') ; i++ );

Whether this is a likely case depends on what you're actually doing this for.

When should I use the Visitor Design Pattern?

As Konrad Rudolph already pointed out, it is suitable for cases where we need double dispatch

Here is an example to show a situation where we need double dispatch & how visitor helps us in doing so.

Example :

Lets say I have 3 types of mobile devices - iPhone, Android, Windows Mobile.

All these three devices have a Bluetooth radio installed in them.

Lets assume that the blue tooth radio can be from 2 separate OEMs – Intel & Broadcom.

Just to make the example relevant for our discussion, lets also assume that the APIs exposes by Intel radio are different from the ones exposed by Broadcom radio.

This is how my classes look –

enter image description here enter image description here

Now, I would like to introduce an operation – Switching On the Bluetooth on mobile device.

Its function signature should like something like this –

 void SwitchOnBlueTooth(IMobileDevice mobileDevice, IBlueToothRadio blueToothRadio)

So depending upon Right type of device and Depending upon right type of Bluetooth radio, it can be switched on by calling appropriate steps or algorithm.

In principal, it becomes a 3 x 2 matrix, where-in I’m trying to vector the right operation depending upon the right type of objects involved.

A polymorphic behaviour depending upon the type of both the arguments.

enter image description here

Now, Visitor pattern can be applied to this problem. Inspiration comes from the Wikipedia page stating – “In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.”

Double dispatch is a necessity here due to the 3x2 matrix

Here is how the set up will look like - enter image description here

I wrote the example to answer another question, the code & its explanation is mentioned here.

How to add new line into txt file

You could do it easily using

File.AppendAllText("date.txt", DateTime.Now.ToString());

If you need newline

File.AppendAllText("date.txt", 
                   DateTime.Now.ToString() + Environment.NewLine);

Anyway if you need your code do this:

TextWriter tw = new StreamWriter("date.txt", true);

with second parameter telling to append to file.
Check here StreamWriter syntax.

How to add a Hint in spinner in XML

You can set the spinner prompt:

spinner.setPrompt("Select gender...");

How to hide code from cells in ipython notebook visualized with nbviewer?

This can be done using an IPython ToggleButton widget and a little bit of JavaScript. The following code should be placed into a code cell at the top of the document:

import ipywidgets as widgets
from IPython.display import display, HTML

javascript_functions = {False: "hide()", True: "show()"}
button_descriptions  = {False: "Show code", True: "Hide code"}


def toggle_code(state):

    """
    Toggles the JavaScript show()/hide() function on the div.input element.
    """

    output_string = "<script>$(\"div.input\").{}</script>"
    output_args   = (javascript_functions[state],)
    output        = output_string.format(*output_args)

    display(HTML(output))


def button_action(value):

    """
    Calls the toggle_code function and updates the button description.
    """

    state = value.new

    toggle_code(state)

    value.owner.description = button_descriptions[state]


state = False
toggle_code(state)

button = widgets.ToggleButton(state, description = button_descriptions[state])
button.observe(button_action, "value")

display(button)

This creates the following button to toggle showing/hiding the code for the Jupyter Notebook, defaulted to the "hide" state:

Hide code state

When set to the "show" state, you can then see the code for the Jupyter Notebook:

Show code state

As an aside, while much of this code should be placed at the beginning of the Notebook, the location of the toggle button is optional. Personally, I prefer to keep it at the bottom of the document. To do so, simply move the display(button) line to a separate code cell at the bottom of the page:

Relocated toggle button

How to override !important?

This can help too

td[style] {height: 50px !important;}

This will override any inline style

How can I transition height: 0; to height: auto; using CSS?

I posted an answer with some JavaScript and got downvoted, so got annoyed and tried again, and have cracked it with CSS only!

This solution uses a few 'techniques':

  • padding-bottom:100% 'hack' where percentages are defined in terms of the current width of the element. More info on this technique.
  • float shrink-wrapping, (necessitating an extra div to apply the float clearing hack)
  • unsemantic use of https://caniuse.com/#feat=css-writing-mode and some transformations to undo it (this allows use of the padding hack above in a vertical context)

The upshot though is that we get performant transitioning using CSS only, and a single transition function to smoothly achieve the transition; the holy grail!

Of course, there's a downside! I can't work out how to control the width at which content gets cut off (overflow:hidden); because of the padding-bottom hack, the width and height are intimately related. There may be a way though, so will come back to it.

https://jsfiddle.net/EoghanM/n1rp3zb4/28/

_x000D_
_x000D_
body {_x000D_
  padding: 1em;_x000D_
}_x000D_
_x000D_
.trigger {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
/* .expander is there for float clearing purposes only */_x000D_
.expander::after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
  float: left; /* purpose: shrink to fit content */_x000D_
  border: 1px solid green;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  transition: padding-bottom 0.3s ease-in-out;  /* or whatever crazy transition function you can come up with! */_x000D_
  padding-bottom: 0%;  /* percentage padding is defined in terms of width. The width at this level is equal to the height of the content */_x000D_
  height: 0;_x000D_
_x000D_
  /* unfortunately, change of writing mode has other bad effects like orientation of cursor */_x000D_
  writing-mode: vertical-rl;_x000D_
  cursor: default; /* don't want the vertical-text (sideways I-beam) */_x000D_
  transform: rotate(-90deg) translateX(-100%);  /* undo writing mode */_x000D_
  transform-origin: 0 0;_x000D_
  margin: 0;  /* left/right margins here will add to height */_x000D_
}_x000D_
_x000D_
.inner > div { white-space: nowrap; }_x000D_
_x000D_
.expander:hover .inner,  /* to keep open when expanded */_x000D_
.trigger:hover+.expander .inner {_x000D_
  padding-bottom: 100%;_x000D_
}
_x000D_
<div class="trigger">HoverMe</div>_x000D_
<div class="expander">_x000D_
  <div class="outer">_x000D_
    <div class="inner">_x000D_
      <div>First Item</div>_x000D_
      <div>Content</div>_x000D_
      <div>Content</div>_x000D_
      <div>Content</div>_x000D_
      <div>Long Content can't be wider than outer height unfortunately</div>_x000D_
      <div>Last Item</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
<div>_x000D_
  after content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Default background color of SVG root element

Another workaround might be to use <div> of the same size to wrap the <svg>. After that, you will be able to apply "background-color", and "background-image" that will affect thesvg.

<div class="background">
  <svg></svg>
</div>

<style type="text/css">
.background{
  background-color: black; 
  /*background-image: */
}
</style>

Open a file with Notepad in C#

You can use Process.Start, calling notepad.exe with the file as a parameter.

 Process.Start(@"notepad.exe", pathToFile);

How to add a boolean datatype column to an existing table in sql?

Below query worked for me with default value false;

ALTER TABLE cti_contract_account ADD ready_to_audit BIT DEFAULT 0 NOT NULL;

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How to call a JavaScript function within an HTML body

Just to clarify things, you don't/can't "execute it within the HTML body".

You can modify the contents of the HTML using javascript.

You decide at what point you want the javascript to be executed.

For example, here is the contents of a html file, including javascript, that does what you want.

<html>
  <head>
    <script>
    // The next line document.addEventListener....
    // tells the browser to execute the javascript in the function after
    // the DOMContentLoaded event is complete, i.e. the browser has
    // finished loading the full webpage
    document.addEventListener("DOMContentLoaded", function(event) { 
      var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below  $500.00" ];
      var col2 = ["None", "None", "$8.00"];
      var TheInnerHTML ="";
      for (var j = 0; j < col1.length; j++) {
        TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
    }
    document.getElementById("TheBody").innerHTML = TheInnerHTML;});
    </script>
  </head>
  <body>
    <table>
    <thead>
      <tr>
        <th>Balance</th>
        <th>Fee</th>        
      </tr>
    </thead>
    <tbody id="TheBody">
    </tbody>
  </table>
</body>

Enjoy !

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

Adding Multiple Values in ArrayList at a single index

import java.util.*;
public class HelloWorld{

 public static void main(String []args){
  List<String> threadSafeList = new ArrayList<String>();
    threadSafeList.add("A");
    threadSafeList.add("D");
    threadSafeList.add("F");

Set<String> threadSafeList1 = new TreeSet<String>();
    threadSafeList1.add("B");
    threadSafeList1.add("C");
    threadSafeList1.add("E");
    threadSafeList1.addAll(threadSafeList);


 List mainList = new ArrayList();   
 mainList.addAll(Arrays.asList(threadSafeList1));
 Iterator<String> mainList1 = mainList.iterator();
 while(mainList1.hasNext()){
 System.out.printf("total : %s %n", mainList1.next());
 }
}
}

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Can I write native iPhone apps using Python?

It seems this is now something developers are allowed to do: the iOS Developer Agreement was changed yesterday and appears to have been ammended in a such a way as to make embedding a Python interpretter in your application legal:

SECTION 3.3.2 — INTERPRETERS

Old:

3.3.2 An Application may not itself install or launch other executable code by any means, including without limitation through the use of a plug-in architecture, calling other frameworks, other APIs or otherwise. Unless otherwise approved by Apple in writing, no interpreted code may be downloaded or used in an Application except for code that is interpreted and run by Apple’s Documented APIs and built-in interpreter(s). Notwithstanding the foregoing, with Apple’s prior written consent, an Application may use embedded interpreted code in a limited way if such use is solely for providing minor features or functionality that are consistent with the intended and advertised purpose of the Application.

New:

3.3.2 An Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded. The only exception to the foregoing is scripts and code downloaded and run by Apple’s built-in WebKit framework.

How to safely open/close files in python 2.4

No need to close the file according to the docs if you use with:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

Bootstrap Navbar toggle button not working

If you will change the ID then Toggle will not working same problem was with me i just change

<div class="collapse navbar-collapse" id="defaultNavbar1">
    <ul class="nav navbar-nav">

id="defaultNavbar1" then toggle is working

Using find command in bash script

Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)

The option you're asking about is for the find command though, not for bash. From your command line, you can man find to see the options.

The one you're looking for is -o for "or":

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp

The Bash FAQ has lots of other excellent tips about programming in bash.

Transport security has blocked a cleartext HTTP

Development Example

Here is a screenshot of a plist which keeps ATS intact (=secure), but allows that connections to localhost can be made via HTTP instead of HTTPS. It works in Xcode 7.1.1.

Enter image description here

Relative URLs in WordPress

Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.

I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.

Importing CSV with line breaks in Excel 2007

In my case opening CSV in notepad++ and adding SEP="," as the first line allows me open CSV with line breaks and utf-8 in Excel without issues

Extracting text from a PDF file using PDFMiner in python?

this code is tested with pdfminer for python 3 (pdfminer-20191125)

from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LTTextBoxHorizontal

def parsedocument(document):
    # convert all horizontal text into a lines list (one entry per line)
    # document is a file stream
    lines = []
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.get_pages(document):
            interpreter.process_page(page)
            layout = device.get_result()
            for element in layout:
                if isinstance(element, LTTextBoxHorizontal):
                    lines.extend(element.get_text().splitlines())
    return lines

Converting Columns into rows with their respective data in sql server

DECLARE @TABLE TABLE 
  (RowNo INT,ScripName  VARCHAR(10),ScripCode  VARCHAR(10)
  ,Price  VARCHAR(10))      
INSERT INTO @TABLE VALUES
  (1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
 Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H

What's the most efficient way to check if a record exists in Oracle?

select count(1) into existence 
   from sales where sales_type = 'Accessories' and rownum=1;

Oracle plan says that it costs 1 if seles_type column is indexed.

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

Grep characters before and after match?

grep -E -o ".{0,5}test_pattern.{0,5}" test.txt 

This will match up to 5 characters before and after your pattern. The -o switch tells grep to only show the match and -E to use an extended regular expression. Make sure to put the quotes around your expression, else it might be interpreted by the shell.

How do I break a string across more than one line of code in JavaScript?

A good solution here for VSCode users, if a string breaking down into multiple lines causes the problem (I faced this when I had to test a long JWT token, and somehow using template literals didn't do the trick.)

What is wrong with my SQL here? #1089 - Incorrect prefix key

Problem is the same for me in phpMyAdmin. I just created a table without any const. Later I modified the ID to a Primary key. Then I changed the ID to Auto-inc. That solved the issue.

ALTER TABLE `users` CHANGE `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT;

New warnings in iOS 9: "all bitcode will be dropped"

To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9

Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/

How to convert Excel values into buckets?

The right tool for that is to create a range with your limits and the corresponding names. You can then use the vlookup() function, with the 4th parameter set to Trueto create a range lookup.

enter image description here

Note: my PC uses ; as separator, yours might use ,.
Adjust formula according to your regional settings.

How do I activate a virtualenv inside PyCharm's terminal?

I wanted a separate virtual environment for each project, and didn't care much for having additional files to facilitate this. A solution which you only need to do once and works for all projects is then adding the following to your .bashrc or .bash_profile:

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

This checks if there is a virtual environment where the terminal is being opened, and if so activates it (and of course other relative paths could be used). PyCharm's terminal settings can be left as their default.

How can I pass a class member function as a callback?

Necromancing.
I think the answers to date are a little unclear.

Let's make an example:

Supposed you have an array of pixels (array of ARGB int8_t values)

// A RGB image
int8_t* pixels = new int8_t[1024*768*4];

Now you want to generate a PNG. To do so, you call the function toJpeg

bool ok = toJpeg(writeByte, pixels, width, height);

where writeByte is a callback-function

void writeByte(unsigned char oneByte)
{
    fputc(oneByte, output);
}

The problem here: FILE* output has to be a global variable.
Very bad if you're in a multithreaded environment (e.g. a http-server).

So you need some way to make output a non-global variable, while retaining the callback signature.

The immediate solution that springs into mind is a closure, which we can emulate using a class with a member function.

class BadIdea {
private:
    FILE* m_stream;
public:
    BadIdea(FILE* stream)  {
        this->m_stream = stream;
    }

    void writeByte(unsigned char oneByte){
            fputc(oneByte, this->m_stream);
    }

};

And then do

FILE *fp = fopen(filename, "wb");
BadIdea* foobar = new BadIdea(fp);

bool ok = TooJpeg::writeJpeg(foobar->writeByte, image, width, height);
delete foobar;
fflush(fp);
fclose(fp);

However, contrary to expectations, this does not work.

The reason is, C++ member functions are kinda implemented like C# extension functions.

So you have

class/struct BadIdea
{
    FILE* m_stream;
}

and

static class BadIdeaExtensions
{
    public static writeByte(this BadIdea instance, unsigned char oneByte)
    {
         fputc(oneByte, instance->m_stream);
    }

}

So when you want to call writeByte, you need pass not only the address of writeByte, but also the address of the BadIdea-instance.

So when you have a typedef for the writeByte procedure, and it looks like this

typedef void (*WRITE_ONE_BYTE)(unsigned char);

And you have a writeJpeg signature that looks like this

bool writeJpeg(WRITE_ONE_BYTE output, uint8_t* pixels, uint32_t 
 width, uint32_t height))
    { ... }

it's fundamentally impossible to pass a two-address member function to a one-address function pointer (without modifying writeJpeg), and there's no way around it.

The next best thing that you can do in C++, is using a lambda-function:

FILE *fp = fopen(filename, "wb");
auto lambda = [fp](unsigned char oneByte) { fputc(oneByte, fp);  };
bool ok = TooJpeg::writeJpeg(lambda, image, width, height);

However, because lambda is doing nothing different, than passing an instance to a hidden class (such as the "BadIdea"-class), you need to modify the signature of writeJpeg.

The advantage of lambda over a manual class, is that you just need to change one typedef

typedef void (*WRITE_ONE_BYTE)(unsigned char);

to

using WRITE_ONE_BYTE = std::function<void(unsigned char)>; 

And then you can leave everything else untouched.

You could also use std::bind

auto f = std::bind(&BadIdea::writeByte, &foobar);

But this, behind the scene, just creates a lambda function, which then also needs the change in typedef.

So no, there is no way to pass a member function to a method that requires a static function-pointer.

But lambdas are the easy way around, provided that you have control over the source.
Otherwise, you're out of luck.
There's nothing you can do with C++.

Note:
std::function requires #include <functional>

However, since C++ allows you to use C as well, you can do this with libffcall in plain C, if you don't mind linking a dependency.

Download libffcall from GNU (at least on ubuntu, don't use the distro-provided package - it is broken), unzip.

./configure
make
make install

gcc main.c -l:libffcall.a -o ma

main.c:

#include <callback.h>

// this is the closure function to be allocated 
void function (void* data, va_alist alist)
{
     int abc = va_arg_int(alist);

     printf("data: %08p\n", data); // hex 0x14 = 20
     printf("abc: %d\n", abc);

     // va_start_type(alist[, return_type]);
     // arg = va_arg_type(alist[, arg_type]);
     // va_return_type(alist[[, return_type], return_value]);

    // va_start_int(alist);
    // int r = 666;
    // va_return_int(alist, r);
}



int main(int argc, char* argv[])
{
    int in1 = 10;

    void * data = (void*) 20;
    void(*incrementer1)(int abc) = (void(*)()) alloc_callback(&function, data);
    // void(*incrementer1)() can have unlimited arguments, e.g. incrementer1(123,456);
    // void(*incrementer1)(int abc) starts to throw errors...
    incrementer1(123);
    // free_callback(callback);
    return EXIT_SUCCESS;
}

And if you use CMake, add the linker library after add_executable

add_library(libffcall STATIC IMPORTED)
set_target_properties(libffcall PROPERTIES
        IMPORTED_LOCATION /usr/local/lib/libffcall.a)
target_link_libraries(BitmapLion libffcall)

or you could just dynamically link libffcall

target_link_libraries(BitmapLion ffcall)

Note:
You might want to include the libffcall headers and libraries, or create a cmake project with the contents of libffcall.

Regular expression to match standard 10 digit phone number

I ended up with

const regexBase = '(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})?[-. )]*(\\d{3})[-. ]*(\\d{4,5})(?: *x(\\d+))?'; const phoneRegex = new RegExp('\\s*' + regexBase + '\\s*', 'g');

this was to allow for things like dutch numbers, for example

+358 300 20200

How can I use custom fonts on a website?

You can use CSS3 font-face or webfonts

@font-face usage

@font-face {
   font-family: Delicious; 
   src: url('Delicious-Roman.otf');
} 

webfonts

take a look at Google Webfonts, http://www.google.com/webfonts

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

How do I rename the android package name?

This modification needs three steps :

  1. Change the package name in the manifest
  2. Refactor the name of your package with right click -> refactor -> rename in the tree view, then Android studio will display a window, select "rename package"
  3. Change manually the application Id in the build.gradle file : android / defaultconfig / application ID

Then clean / rebuild the project

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

What do these three dots in React do?

spread operator(triple operator) introduce in ecama script 6(ES6).Ecama script(ES6) is a wrapper of javascript.

spread operator enumerable properties in props. this.props = { firstName: 'Dan', lastName: 'Abramov', city: 'New York', country: 'USA' }

{...this.props} = { firstName: 'Dan', lastName: 'Abramov', city: 'New York', country: 'USA' }

But the main feature spread operator is used for a reference type.

For example
let person= {
    name: 'Alex',
    age: 35 
}
person1= person;

person1.name = "Raheel";

console.log( person.name); // output: Raheel

This is called reference type, one object affects other objects because they are shareable in memory. If you getting value independently mean spread memory both use spread operator.

 let person= {
        name: 'Alex',
        age: 35 
    }
person2 = {...person};

person2.name = "Shahzad";

console.log(person.name); // output: Alex

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

Display array values in PHP

use implode(',', $array); for output as apple,banana,orange

Or

foreach($array as $key => $value)
{
   echo $key." is ". $value;
}

Get my phone number in android

Method 1:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

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

Method 2:

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

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

Hope this helps, Thanks!

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

How do I minimize the command prompt from my bat file

One way to 'minimise' the cmd window is to reduce the size of the console using something like...

echo DO NOT CLOSE THIS WINDOW
MODE CON COLS=30 LINES=2

You can reduce the COLS to about 18 and the LINES to 1 if you wish. The advantage is that it works under WinPE, 32-bit or 64-bit, and does not require any 3rd party utility.

How to detect when an @Input() value changes in Angular?

You can also , have an observable which triggers on changes in the parent component(CategoryComponent) and do what you want to do in the subscribtion in the child component. (videoListComponent)

service.ts

public categoryChange$ : ReplaySubject<any> = new ReplaySubject(1);

CategoryComponent.ts

public onCategoryChange(): void {
  service.categoryChange$.next();
}

videoListComponent.ts

public ngOnInit(): void {
  service.categoryChange$.subscribe(() => {
   // do your logic
  });
}

How to calculate time difference in java?

Java 8 has a cleaner solution - Instant and Duration

Example:

import java.time.Duration;
import java.time.Instant;
...
Instant start = Instant.now();
//your code
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds");

How to solve maven 2.6 resource plugin dependency?

If a download fails for some reason Maven will not try to download it within a certain time frame (it leaves a file with a timestamp).

To fix this you can either

  • Clear (parts of) your .m2 repo
  • Run maven with -U to force an update

How many files can I put in a directory?

It depends a bit on the specific filesystem in use on the Linux server. Nowadays the default is ext3 with dir_index, which makes searching large directories very fast.

So speed shouldn't be an issue, other than the one you already noted, which is that listings will take longer.

There is a limit to the total number of files in one directory. I seem to remember it definitely working up to 32000 files.

Displaying one div on top of another

Have the style for the parent div and the child divs' set as following. It worked for my case, hope it helps you as well..

<div id="parentDiv">
  <div id="backdrop"><img alt="" src='/backdrop.png' /></div>
  <div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div>
</div>

in your JS:

document.getElementById('parentDiv').style.position = 'relative';
document.getElementById('backdrop').style.position = 'absolute';
document.getElementById('curtain').style.position = 'absolute';
document.getElementById('curtain').style.zIndex= '2';//this number has to be greater than the zIndex of 'backdrop' if you are setting any

or in your CSS as in this working example:::

_x000D_
_x000D_
#parentDiv{_x000D_
  background: yellow;_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  position: relative;_x000D_
}_x000D_
#backdrop{_x000D_
  background: red;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  position: absolute;_x000D_
}_x000D_
#curtain{_x000D_
  background: green;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  position: absolute;_x000D_
  z-index: 2;_x000D_
  margin: 100px 0px 150px 100px;_x000D_
}
_x000D_
<div id="parentDiv"><h2>_x000D_
  THIS IS PARENT DIV_x000D_
  </h2>_x000D_
  <div id="backdrop"><h4>_x000D_
  THIS IS BACKDROP DIV_x000D_
  </h4></div>_x000D_
  <div id="curtain"><h6>_x000D_
  THIS IS CURTAIN DIV_x000D_
  </h6></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL Server - Case Statement

We can use case statement Like this

select Name,EmailId,gender=case 
when gender='M' then 'F'
when gender='F' then 'M'
end
 from [dbo].[Employees]

WE can also it as follow.

select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
 from [dbo].[Employees]

String Pattern Matching In Java

You can do it using string.indexOf("{item}"). If the result is greater than -1 {item} is in the string

Running Google Maps v2 on the Android emulator

Please try the following. It was successfully for me.

Steps:

  1. Create a new emulator with this configuration: AVD configuration

  2. Start the emulator and install the following APK files: GoogleLoginService.apk, GoogleServicesFramework.apk, and Phonesky.apk. You can do this with the following commands:

    adb shell mount -o remount,yourAvdName -t yaffs2 /dev/block/mtdblock0 /system
    adb shell chmod 777 /system/app
    adb push GoogleLoginService.apk /system/app/
    adb push GoogleServicesFramework.apk /system/app/
    adb push Phonesky.apk /system/app/
    

    Links for APKs:

    1. GoogleLoginService.apk
    2. GoogleServicesFramework.apk
    3. Phonesky.apk AKA Google Play Store, v.3.5.16
    4. Google Maps, v.6.14.1
    5. Google Play services, v.2.0.10
  3. Install Google Play services and Google Maps in the emulator

    adb install com.google.android.apps.maps-1.apk
    adb install com.google.android.gms-2.apk
    
  4. Download Google Play Service revision 4 from this link and extra to folder sdkmanager->extra->google play service.
  5. Import google-play-services_lib from androidsdk\extras\google\google_play_services.
  6. Create a new project and reference the above project as a library project.
  7. Run the project.

When to use React "componentDidUpdate" method?

A simple example would be an app that collects input data from the user and then uses Ajax to upload said data to a database. Here's a simplified example (haven't run it - may have syntax errors):

export default class Task extends React.Component {
  
  constructor(props, context) {
    super(props, context);
    this.state = {
      name: "",
      age: "",
      country: ""
    };
  }

  componentDidUpdate() {
    this._commitAutoSave();
  }

  _changeName = (e) => {
    this.setState({name: e.target.value});
  }

  _changeAge = (e) => {
    this.setState({age: e.target.value});
  }

  _changeCountry = (e) => {
    this.setState({country: e.target.value});
  }

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave', {
      name: this.state.name,
      age: this.state.age,
      country: this.state.country
    });
  }

  render() {
    let {name, age, country} = this.state;
    return (
      <form>
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />
      </form>
    );
  }
}

So whenever the component has a state change it will autosave the data. There are other ways to implement it too. The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It's probably most useful on complex renders and state or DOM changes or when you need something to be the absolutely last thing to be executed.

The example above is rather simple though, but probably proves the point. An improvement could be to limit the amount of times the autosave can execute (e.g max every 10 seconds) because right now it will run on every key-stroke.

I made a demo on this fiddle as well to demonstrate.


For more info, refer to the official docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

Python's equivalent of && (logical-and) in an if-statement

Python uses and and or conditionals.

i.e.

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something

Excel: VLOOKUP that returns true or false?

You could wrap your VLOOKUP() in an IFERROR()

Edit: before Excel 2007, use =IF(ISERROR()...)

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

I couldn't add a comment to Abhijit Rao's answer above, so I am submitting this as an additional answer.

I needed to have the table column scroll into view on a wide table, so I added the scroll left features into the function. As someone mentioned, it jumps when it scrolls, but it worked for my purposes.

function scrollIntoView(element, container) {
  var containerTop = $(container).scrollTop();
  var containerLeft = $(container).scrollLeft();
  var containerBottom = containerTop + $(container).height();
  var containerRight = containerLeft + $(container).width();

  var elemTop = element.offsetTop;
  var elemLeft = element.offsetLeft;
  var elemBottom = elemTop + $(element).height();
  var elemRight = elemLeft + $(element).width();

  if (elemTop < containerTop) {
    $(container).scrollTop(elemTop);
  } else if (elemBottom > containerBottom) {
    $(container).scrollTop(elemBottom - $(container).height());
  }

  if(elemLeft < containerLeft) {
    $(container).scrollLeft(elemLeft);
  } else if(elemRight > containerRight) {
    $(container).scrollLeft(elemRight - $(container).width());
  }
}

WinForms DataGridView font size

I too experienced same problem in the DataGridView but figured out that the DefaultCell style was inheriting the font of the groupbox (Datagrid is placed in groupbox). So changing the font of the groupbox changed the DefaultCellStyle too.

Regards

pass **kwargs argument to another function with **kwargs

For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.

If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args

check this out for more detail on using **kw

http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

I was looking for an answer to this and almost implemented one of these solutions, but a colleague reminded me to check the react-intl library since we were already using it.

So adding to the solutions...in the case you are using the react-intl library, they have a <FormattedRelative> component for this.

https://github.com/yahoo/react-intl/wiki/Components#formattedrelative

MySql export schema without data

Beware though that --no-data option will not include the view definition. So if yo had a view like following

create view v1 
 select `a`.`id` AS `id`,
 `a`.`created_date` AS `created_date` 
from t1;

with --no-data option, view definition will get changed to following

create view v1
 select 1 AS `id`, 1 AS `created_date`

How do I trim a file extension from a String in Java?

BTW, in my case, when I wanted a quick solution to remove a specific extension, this is approximately what I did:

  if (filename.endsWith(ext))
    return filename.substring(0,filename.length() - ext.length());
  else
    return filename;

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Downloading a picture via urllib and python

Using requests

import requests
import shutil,os

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder

def ImageDl(url):
    attempts = 0
    while attempts < 5:#retry 5 times
        try:
            filename = url.split('/')[-1]
            r = requests.get(url,headers=headers,stream=True,timeout=5)
            if r.status_code == 200:
                with open(os.path.join(path,filename),'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw,f)
            print(filename)
            break
        except Exception as e:
            attempts+=1
            print(e)

if __name__ == '__main__':
    ImageDl(url)

How to copy a huge table data into another table in SQL Server

If you are copying into a new table, the quickest way is probably what you have in your question, unless your rows are very large.

If your rows are very large, you may want to use the bulk insert functions in SQL Server. I think you can call them from C#.

Or you can first download that data into a text file, then bulk-copy (bcp) it. This has the additional benefit of allowing you to ignore keys, indexes etc.

Also try the Import/Export utility that comes with the SQL Management Studio; not sure whether it will be as fast as a straight bulk-copy, but it should allow you to skip the intermediate step of writing out as a flat file, and just copy directly table-to-table, which might be a bit faster than your SELECT INTO statement.

How to remove newlines from beginning and end of a string?

This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":

String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

Remove newlines only from the end of the line:

String.replaceAll("[\n\r]$", "")

Remove newlines only from the beginning of the line:

String.replaceAll("^[\n\r]", "")

Error in plot.new() : figure margins too large, Scatter plot

If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.

Moreover Execute the command

graphics.off()

Fitting a Normal distribution to 1D data

You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows.

import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt


# Generate some data for this demonstration.
data = norm.rvs(10.0, 2.5, size=500)

# Fit a normal distribution to the data:
mu, std = norm.fit(data)

# Plot the histogram.
plt.hist(data, bins=25, density=True, alpha=0.6, color='g')

# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Fit results: mu = %.2f,  std = %.2f" % (mu, std)
plt.title(title)

plt.show()

Here's the plot generated by the script:

Plot

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

phpMyAdmin says no privilege to create database, despite logged in as root user

This worked for me(in Chrome):

Login to phpmyadmin, and follow "Home" -> "Privileges" -> "Reload the Privileges". After this, clear your browser's cache and retry.

Regards, Pedro Sousa

Shell command to sum integers, one per line?

Cannot avoid submitting this:

jot 1000000 | sed '2,$s/$/+/;$s/$/p/' | dc

It is found over here:
Most elegant unix shell one-liner to sum list of numbers of arbitrary precision?

And here are its special advantages over awk, bc and friends:

  • it does not depend on buffering and thus does not choke with really big inputs
  • it implies no particular precision -or integer size for that matter- limits (hello AWK!)
  • no need for different code, if floating point numbers need to be added

Python DNS module import error

This issue can be generated by Symantec End Point Protection (SEP). And I suspect most EPP products could potentially impact your running of scripts.

If SEP is disabled, the script will run instantly.

Therefore you may need to update the SEP policy to not block python scripts accessing stuff.

mysql -> insert into tbl (select from another table) and some default values

You simply have to do:

INSERT INTO def (catid, title, page, publish) 
SELECT catid, title, 'page','yes' from `abc`

Fork() function in C

First a link to some documentation of fork()

http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.

So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.

If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().

pid_t pid = fork()
if(pid == 0) {
    printf("this is a child: my new unique pid is %d\n", getpid());
} else {
    printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}

and below is some inline comments on your code

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1 == 0){
        /* This is child A */
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        /* This is parent A */
        /* Child B and C will never reach this code */
        pid3=fork(); /* D */
        if(pid3==0) {
            /* This is child D fork'ed from parent A */
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0)) {
            /* pid1 will never be 0 here so this is dead code */
            printf("Level 1\n");
        }
        if(pid1 !=0) {
            /* This is always true for both parent and child E */
            printf("Level 2\n");
        }
        if(pid2 !=0) {
           /* This is parent E (same as parent A) */
           printf("Level 3\n");
        }
        if(pid3 !=0) {
           /* This is parent D (same as parent A) */
           printf("Level 4\n");
        }
    }
    return 0;
}