Programs & Examples On #Dbdeploy

Split string on whitespace in Python

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.

Example:

>>> "ark".split()
['ark']

How can I compare two lists in python and return matches

I just used the following and it worked for me:

group1 = [1, 2, 3, 4, 5]
group2 = [9, 8, 7, 6, 5]

for k in group1:
    for v in group2:
        if k == v:
            print(k)

this would then print 5 in your case. Probably not great performance wise though.

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

docker: "build" requires 1 argument. See 'docker build --help'

On older versions of Docker it seems you need to use this order:

docker build -t tag .

and not

docker build . -t tag

replace String with another in java

The replace method is what you're looking for.

For example:

String replacedString = someString.replace("HelloBrother", "Brother");

Event on a disabled input

Disabled elements don't fire mouse events. Most browsers will propagate an event originating from the disabled element up the DOM tree, so event handlers could be placed on container elements. However, Firefox doesn't exhibit this behaviour, it just does nothing at all when you click on a disabled element.

I can't think of a better solution but, for complete cross browser compatibility, you could place an element in front of the disabled input and catch the click on that element. Here's an example of what I mean:

<div style="display:inline-block; position:relative;">
  <input type="text" disabled />
  <div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>?

jq:

$("div > div").click(function (evt) {
    $(this).hide().prev("input[disabled]").prop("disabled", false).focus();
});?

Example: http://jsfiddle.net/RXqAm/170/ (updated to use jQuery 1.7 with prop instead of attr).

How to remove all non-alpha numeric characters from a string in MySQL?

The fastest way I was able to find (and using ) is with convert().

from Doc. CONVERT() with USING is used to convert data between different character sets.

Example:

convert(string USING ascii)

In your case the right character set will be self defined

NOTE from Doc. The USING form of CONVERT() is available as of 4.1.0.

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

Defining array with multiple types in TypeScript

My TS lint was complaining about other solutions, so the solution that was working for me was:

item: Array<Type1 | Type2>

if there's only one type, it's fine to use:

item: Type1[]

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

Android - Center TextView Horizontally in LinearLayout

If you set <TextView> in center in <Linearlayout> then first put android:layout_width="fill_parent" compulsory
No need of using any other gravity

    <LinearLayout
            android:layout_toRightOf="@+id/linear_profile" 
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:orientation="vertical"
            android:gravity="center_horizontal">
            <TextView 
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="It's.hhhhhhhh...."
                android:textColor="@color/Black"

                />
    </LinearLayout>

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.

Use the subplots_adjust() function to move the bottom of the subplot up:

fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.

Then play with the offset in the legend bbox_to_anchor part of the legend command, to get the legend box where you want it. Some combination of setting the figsize and using the subplots_adjust(bottom=...) should produce a quality plot for you.

Alternative: I simply changed the line:

fig = plt.figure(1)

to:

fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')

and changed

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))

to

lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))

and it shows up fine on my screen (a 24-inch CRT monitor).

Here figsize=(M,N) sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport option when including graphics.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

Loading basic HTML in Node.js

we can load the html document with connect frame work. I have placed my html document and the related images in the public folder of my project where the below code and node modules present.

//server.js
var http=require('http');
var connect=require('connect');

var app = connect()
  .use(connect.logger('dev'))
  .use(connect.static('public'))
  .use(function(req, res){
   res.end('hello world\n');
 })

http.createServer(app).listen(3000);

I have tried the readFile() method of fs, but it fails to load the images, that's why i have used the connect framework.

What is the purpose of Looper and how to use it?

Life span of java Thread is over after completion of run() method. Same thread can't be started again.

Looper transforms normal Thread into a message loop. Key methods of Looper are :

void prepare ()

Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().

void loop ()

Run the message queue in this thread. Be sure to call quit() to end the loop.

void quit()

Quits the looper.

Causes the loop() method to terminate without processing any more messages in the message queue.

This mindorks article by Janishar explains the core concepts in nice way.

enter image description here

Looper is associated with a Thread. If you need Looper on UI thread, Looper.getMainLooper() will return associated thread.

You need Looper to be associated with a Handler.

Looper, Handler, and HandlerThread are the Android’s way of solving the problems of asynchronous programming.

Once you have Handler, you can call below APIs.

post (Runnable r)

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

boolean sendMessage (Message msg)

Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.

HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes

In some scenarios, you can't run Runnable tasks on UI Thread. e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream

In these cases, HandlerThread is useful. You can get Looper object from HandlerThread and create a Handler on HandlerThread instead of main thread.

The HandlerThread code will be like this:

@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

Refer to below post for example code:

Android: Toast in a thread

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

Just rename the command or file name ln -s /usr/bin/nodejs /usr/bin/node by this command

Change font-weight of FontAwesome icons?

The author appears to have taken a freemium approach to the font library and provides Black Tie to give different weights to the Font-Awesome library.

What is Node.js' Connect, Express and "middleware"?

Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.

Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.

combining two data frames of different lengths

It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.

But let's assume that we're really after a way to cbind multiple data frames of differing lengths.

cbind will eventually call data.frame, whose help files says:

Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).

so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)

I get no errors and the shorter data frame is recycled as expected. However, when I run this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)

I get the following error:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 50, 9

But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind data frames of uneven length and automatically pad the shorter ones with NAs:

cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
    if (nrow(x) < mx){
        nms <- colnames(x)
        padTemp <- matrix(NA, mx - nrow(x), ncol(x))
        colnames(padTemp) <- nms
        if (ncol(x)==0) {
          return(padTemp)
        } else {
        return(rbind(x,padTemp))
          }
    }
    else{
        return(x)
    }
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}

which can be used like this:

set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)

I make no guarantees that this function works in all cases; it is meant as an example only.

EDIT

If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using "" rather than NA and then do something like this:

dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))

and then use write.table on rs.

How to create a md5 hash of a string in C?

I don't know this particular library, but I've used very similar calls. So this is my best guess:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.

char md5string[33];
for(int i = 0; i < 16; ++i)
    sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

How do you get a query string on Flask?

This can be done using request.args.get(). For example if your query string has a field date, it can be accessed using

date = request.args.get('date')

Don't forget to add "request" to list of imports from flask, i.e.

from flask import request

How to read a file without newlines?

Try this:

u=open("url.txt","r")  
url=u.read().replace('\n','')  
print(url)  

ERROR 1049 (42000): Unknown database

Its a common error which happens when we try to access a database which doesn't exist. So create the database using

CREATE DATABASE blog_development;

The error commonly occours when we have dropped the database using

DROP DATABASE blog_development;

and then try to access the database.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

In the head section of your html document:

<link rel="stylesheet" type="text/css" href="/path/to/ABCD.css">

Your css file should be css only and not contain any markup.

android - save image into gallery

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

The image below is from the article written by Erwin van der Valk:

image explaining MVC, MVP and MVVM - by Erwin Vandervalk

The article explains the differences and gives some code examples in C#

Generate random numbers uniformly over an entire range

[edit] Warning: Do not use rand() for statistics, simulation, cryptography or anything serious.

It's good enough to make numbers look random for a typical human in a hurry, no more.

See @Jefffrey's reply for better options, or this answer for crypto-secure random numbers.


Generally, the high bits show a better distribution than the low bits, so the recommended way to generate random numbers of a range for simple purposes is:

((double) rand() / (RAND_MAX+1)) * (max-min+1) + min

Note: make sure RAND_MAX+1 does not overflow (thanks Demi)!

The division generates a random number in the interval [0, 1); "stretch" this to the required range. Only when max-min+1 gets close to RAND_MAX you need a "BigRand()" function like posted by Mark Ransom.

This also avoids some slicing problems due to the modulo, which can worsen your numbers even more.


The built-in random number generator isn't guaranteed to have a the quality required for statistical simulations. It is OK for numbers to "look random" to a human, but for a serious application, you should take something better - or at least check its properties (uniform distribution is usually good, but values tend to correlate, and the sequence is deterministic). Knuth has an excellent (if hard-to-read) treatise on random number generators, and I recently found LFSR to be excellent and darn simple to implement, given its properties are OK for you.

How can I display an image from a file in Jupyter Notebook?

Courtesy of this page, I found this worked when the suggestions above didn't:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

How to list only the file names that changed between two commits?

git diff --name-only SHA1 SHA2

where you only need to include enough of the SHA to identify the commits. You can also do, for example

git diff --name-only HEAD~10 HEAD~5

to see the differences between the tenth latest commit and the fifth latest (or so).

PHP Multiple Checkbox Array

add [] in the name of the attributes in the input tag

 <form action="" name="frm" method="post">
<input type="checkbox" name="hobby[]" value="coding">  coding &nbsp
<input type="checkbox" name="hobby[]" value="database">  database &nbsp
<input type="checkbox" name="hobby[]" value="software engineer">  soft Engineering <br>
<input type="submit" name="submit" value="submit"> 
</form>

for PHP Code :

<?php
 if(isset($_POST['submit']){
   $hobby = $_POST['hobby'];

   foreach ($hobby as $hobys=>$value) {
             echo "Hobby : ".$value."<br />";
        }
}
?>

How to check for valid email address?

The Python standard library comes with an e-mail parsing function: email.utils.parseaddr().

It returns a two-tuple containing the real name and the actual address parts of the e-mail:

>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')

>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')

>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')

And if the parsing is unsuccessful, it returns a two-tuple of empty strings:

>>> parseaddr('[invalid!email]')
('', '')

An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:

>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')

>>> parseaddr('invalid-email')
('', 'invalid-email')

So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.

However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:

>>> '@' in parseaddr("invalid-email")[1]
False

If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX servers:

>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
dns.resolver.NXDOMAIN

You can catch both NoAnswer and NXDOMAIN by catching dns.exception.DNSException.

And Yes, foo@[email protected] is a syntactically valid address. Only the last @ should be considered for detecting where the domain part starts.

How to implement a ConfigurationSection with a ConfigurationElementCollection

This is generic code for configuration collection :

public class GenericConfigurationElementCollection<T> :   ConfigurationElementCollection, IEnumerable<T> where T : ConfigurationElement, new()
{
    List<T> _elements = new List<T>();

    protected override ConfigurationElement CreateNewElement()
    {
        T newElement = new T();
        _elements.Add(newElement);
        return newElement;
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return _elements.Find(e => e.Equals(element));
    }

    public new IEnumerator<T> GetEnumerator()
    {
        return _elements.GetEnumerator();
    }
}

After you have GenericConfigurationElementCollection, you can simple use it in the config section (this is an example from my Dispatcher):

public class  DispatcherConfigurationSection: ConfigurationSection
{
    [ConfigurationProperty("maxRetry", IsRequired = false, DefaultValue = 5)]
    public int MaxRetry
    {
        get
        {
            return (int)this["maxRetry"];
        }
        set
        {
            this["maxRetry"] = value;
        }
    }

    [ConfigurationProperty("eventsDispatches", IsRequired = true)]
    [ConfigurationCollection(typeof(EventsDispatchConfigurationElement), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
    public GenericConfigurationElementCollection<EventsDispatchConfigurationElement> EventsDispatches
    {
        get { return (GenericConfigurationElementCollection<EventsDispatchConfigurationElement>)this["eventsDispatches"]; }
    }
}

The Config Element is config Here:

public class EventsDispatchConfigurationElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
            return (string) this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }
}

The config file would look like this:

<?xml version="1.0" encoding="utf-8" ?>
  <dispatcherConfigurationSection>
    <eventsDispatches>
      <add name="Log" ></add>
      <add name="Notification" ></add>
      <add name="tester" ></add>
    </eventsDispatches>
  </dispatcherConfigurationSection>

Hope it help !

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You can certainly do something like

SQL> ed
Wrote file afiedt.buf

  1  begin
  2    for d in (select * from dept)
  3    loop
  4      for e in (select * from emp where deptno=d.deptno)
  5      loop
  6        dbms_output.put_line( 'Employee ' || e.ename ||
  7                              ' in department ' || d.dname );
  8      end loop;
  9    end loop;
 10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

Or something equivalent using explicit cursors.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    cursor dept_cur
  3        is select *
  4             from dept;
  5    d dept_cur%rowtype;
  6    cursor emp_cur( p_deptno IN dept.deptno%type )
  7        is select *
  8             from emp
  9            where deptno = p_deptno;
 10    e emp_cur%rowtype;
 11  begin
 12    open dept_cur;
 13    loop
 14      fetch dept_cur into d;
 15      exit when dept_cur%notfound;
 16      open emp_cur( d.deptno );
 17      loop
 18        fetch emp_cur into e;
 19        exit when emp_cur%notfound;
 20        dbms_output.put_line( 'Employee ' || e.ename ||
 21                              ' in department ' || d.dname );
 22      end loop;
 23      close emp_cur;
 24    end loop;
 25    close dept_cur;
 26* end;
 27  /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of

FOR x IN (SELECT *
            FROM all_users,
                 org
           WHERE length(all_users.username) = 3
             AND all_users.username = org.username )
LOOP
  <<do something>>
END LOOP;

XPath: difference between dot and text()

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node. In the image description screenshot, the XPath text() function will only locate Success in DOM Example 2. It will not find success in DOM Example 1 because it's located between the tags.

In addition, the text() function will not find success in DOM Example 3 because success does not have a direct relationship to the element . Here's a video demo explaining the difference between text() and dot (.) https://youtu.be/oi2Q7-0ZIBg

How to generate .json file with PHP?

If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Then in your script set the path to the file my_json.php

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can either pass the parameter in the task constructor or when you call execute:

AsyncTask<Object, Void, MyTaskResult>

The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

public class MyActivity extends AppCompatActivity {

    TextView textView1;
    TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);    
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        String input1 = "test";
        boolean input2 = true;
        int input3 = 100;
        long input4 = 100000000;

        new MyTask(input3, input4).execute(input1, input2);
    }

    private class MyTaskResult {
        String text1;
        String text2;
    }

    private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
        private String val1;
        private boolean val2;
        private int val3;
        private long val4;


        public MyTask(int in3, long in4) {
            this.val3 = in3;
            this.val4 = in4;

            // Do something ...
        }

        protected void onPreExecute() {
            // Do something ...
        }

        @Override
        protected MyTaskResult doInBackground(Object... params) {
            MyTaskResult res = new MyTaskResult();
            val1 = (String) params[0];
            val2 = (boolean) params[1];

            //Do some lengthy operation    
            res.text1 = RunProc1(val1);
            res.text2 = RunProc2(val2);

            return res;
        }

        @Override
        protected void onPostExecute(MyTaskResult res) {
            textView1.setText(res.text1);
            textView2.setText(res.text2);

        }
    }

}

Using Camera in the Android emulator

Does not seem like it, but android recognises a webcam as a device. Every time I run the emulator my webcam's active light comes on.

How to play an android notification sound

I think the concept of "notification sound" is someway wrong for Android UI.

The Android expected behaviour is to use the standard Notification to alert the user. If you play a notification sound without the status bar icon, you get the user confused ("what was that sound? there is no icon here, maybe I have hearing problems?").

How to set sound on a notification is, for example, here: Setting sound for notification

Change One Cell's Data in mysql

My answer is repeating what others have said before, but I thought I'd add an example, using MySQL, only because the previous answers were a little bit cryptic to me.

The general form of the command you need to use to update a single row's column:

UPDATE my_table SET my_column='new value' WHERE something='some value';

And here's an example.

BEFORE

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10104 | 
+------------+-------+
2 rows in set (0.00 sec)

MAKING THE CHANGE

mysql> update ae set port='10105' where aet='CDRECORD';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

AFTER

mysql> select aet,port from ae;
+------------+-------+
| aet        | port  |
+------------+-------+
| DCM4CHEE01 | 11112 | 
| CDRECORD   | 10105 | 
+------------+-------+
2 rows in set (0.00 sec)

Functions are not valid as a React child. This may happen if you return a Component instead of from render

I was getting this from webpack lazy loading like this

import Loader from 'some-loader-component';
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: Loader, // warning
});
render() {
    return <WishlistPageComponent />;
}


// changed to this then it's suddenly fine
const WishlistPageComponent = loadable(() => import(/* webpackChunkName: 'WishlistPage' */'../components/WishlistView/WishlistPage'), {
  fallback: '', // all good
});    

How do I convert a number to a numeric, comma-separated formatted string?

For SQL Server 2012, or later, an easier solution is to use FORMAT ()Documentation.
EG:

SELECT Format(1234567.8, '##,##0') 

Results in: 1,234,568

Getting a browser's name client-side

This code will return "browser" and "browserVersion"
Works on 95% of 80+ browsers

var geckobrowsers;
var browser = "";
var browserVersion = 0;
var agent = navigator.userAgent + " ";
if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("like Gecko") != -1){
    geckobrowsers = agent.substring(agent.indexOf("like Gecko")+10).substring(agent.substring(agent.indexOf("like Gecko")+10).indexOf(") ")+2).replace("LG Browser", "LGBrowser").replace("360SE", "360SE/");
    for(i = 0; i < 1; i++){
        geckobrowsers = geckobrowsers.replace(geckobrowsers.substring(geckobrowsers.indexOf("("), geckobrowsers.indexOf(")")+1), "");
    }
    geckobrowsers = geckobrowsers.split(" ");
    for(i = 0; i < geckobrowsers.length; i++){
        if(geckobrowsers[i].indexOf("/") == -1)geckobrowsers[i] = "Chrome";
        if(geckobrowsers[i].indexOf("/") != -1)geckobrowsers[i] = geckobrowsers[i].substring(0, geckobrowsers[i].indexOf("/"));
    }
    if(geckobrowsers.length < 4){
        browser = geckobrowsers[0];
    } else {
        for(i = 0; i < geckobrowsers.length; i++){
            if(geckobrowsers[i].indexOf("Chrome") == -1 && geckobrowsers[i].indexOf("Safari") == -1 && geckobrowsers[i].indexOf("Mobile") == -1 && geckobrowsers[i].indexOf("Version") == -1)browser = geckobrowsers[i];
        }
    }
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Gecko/") != -1){
    browser = agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).substring(0, agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).indexOf("/"));
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Clecko/") != -1){
    browser = agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).substring(0, agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).indexOf("/"));
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0"){
    browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(";"));
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 == agent.length-1){
    browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ")[agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ").length-1];
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 != agent.length-1){
    if(agent.substring(agent.indexOf(") ")+2).indexOf("/") != -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf("/"));
    if(agent.substring(agent.indexOf(") ")+2).indexOf("/") == -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf(" "));
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(0, 6) == "Opera/"){
    browser = "Opera";
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
    if(agent.substring(agent.indexOf("(")+1).indexOf(";") != -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(";"));
    if(agent.substring(agent.indexOf("(")+1).indexOf(";") == -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(")"));
} else if(agent.substring(0, agent.indexOf("/")) != "Mozilla" && agent.substring(0, agent.indexOf("/")) != "Opera"){
    browser = agent.substring(0, agent.indexOf("/"));
    browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else {
    browser = agent;
}
alert(browser + " v" + browserVersion);

Converting 'ArrayList<String> to 'String[]' in Java

Generics solution to covert any List<Type> to String []:

public static  <T> String[] listToArray(List<T> list) {
    String [] array = new String[list.size()];
    for (int i = 0; i < array.length; i++)
        array[i] = list.get(i).toString();
    return array;
}

Note You must override toString() method.

class Car {
  private String name;
  public Car(String name) {
    this.name = name;
  }
  public String toString() {
    return name;
  }
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);

PHP json_encode json_decode UTF-8

if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json. You can either remove the first character or save if without BOM.

Convert float to string with precision & number of decimal digits specified?

The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstream something like:

std::stringstream ss;
ss << std::fixed << std::setprecision(2) << number;
std::string mystring = ss.str();

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Convert a dataframe to a vector (by rows)

You can try as.vector(t(test)). Please note that, if you want to do it by columns you should use unlist(test).

How to percent-encode URL parameters in Python?

Python 2

From the docs:

urllib.quote(string[, safe])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'

That means passing '' for safe will solve your first issue:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:

>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller

By the way have a look at urlencode

Python 3

The same, except replace urllib.quote with urllib.parse.quote.

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

Check table exist or not before create it in Oracle

I know this topic is a bit old, but I think I did something that may be useful for someone, so I'm posting it.

I compiled suggestions from this thread's answers into a procedure:

CREATE OR REPLACE PROCEDURE create_table_if_doesnt_exist(
  p_table_name VARCHAR2,
  create_table_query VARCHAR2
) AUTHID CURRENT_USER IS
  n NUMBER;
BEGIN
  SELECT COUNT(*) INTO n FROM user_tables WHERE table_name = UPPER(p_table_name);
  IF (n = 0) THEN
    EXECUTE IMMEDIATE create_table_query;
  END IF;
END;

You can then use it in a following way:

call create_table_if_doesnt_exist('my_table', 'CREATE TABLE my_table (
        id NUMBER(19) NOT NULL PRIMARY KEY,
        text VARCHAR2(4000),
        modified_time TIMESTAMP
  )'
);

I know that it's kinda redundant to pass table name twice, but I think that's the easiest here.

Hope somebody finds above useful :-).

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Delete all records in a table of MYSQL in phpMyAdmin

Go to the Sql tab run one of the below query:

delete from tableName;

Delete: will delete all rows from your table. Next insert will take next auto increment id.

or

truncate tableName;

Truncate: will also delete the rows from your table but it will start from new row with 1.

A detailed blog with example: http://sforsuresh.in/phpmyadmin-deleting-rows-mysql-table/

Eclipse: Enable autocomplete / content assist

  1. window->preferences->java->Editor->Contest Assist
  2. Enter in Auto activation triggers for java:
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
  3. Apply and Close

other method:
type initial letter then ctrl+spacebar for auto-complete options.

Compile to stand alone exe for C# app in Visual Studio 2010

Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...

Install Android App Bundle on device

Installing the aab directly from the device, I couldn't find a way for that.

But there is a way to install it through your command line using the following documentation You can install apk to a device through BundleTool

According to "@Albert Vila Calvo" comment he noted that to install bundletools using HomeBrew use brew install bundletool

You can now install extract apks from aab file and install it to a device

Extracting apk files from through the next command

java -jar bundletool-all-0.3.3.jar build-apks --bundle=bundle.aab --output=app.apks --ks=my-release-key.keystore --ks-key-alias=alias --ks-pass=pass:password

Arguments:

  • --bundle -> Android Bundle .aab file
  • --output -> Destination and file name for the generated apk file
  • --ks -> Keystore file used to generate the Android Bundle
  • --ks-key-alias -> Alias for keystore file
  • --ks-pass -> Password for Alias file (Please note the 'pass' prefix before password value)

Then you will have a file with extension .apks So now you need to install it to a device

java -jar bundletool-all-0.6.0.jar install-apks --adb=/android-sdk/platform-tools/adb --apks=app.apks

Arguments:

  • --adb -> Path to adb file
  • --apks -> Apks file need to be installed

How do I get a background location update every n minutes in my iOS application?

It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:

     [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
     [self.locationManager setDistanceFilter:99999];

which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:

- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}

All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

Switch php versions on commandline ubuntu 16.04

please follow the steps :

i.e : your current version is : current_version = 7.3 , and you want to change it to : new_version = 7.2

1) sudo a2dismod php(current_version) 
2) sudo a2enmod php(new_version)
3) sudo update-alternatives --config php (here you need to select php version number) 
4) restart apache through : 
  sudo /etc/init.d/apache2 restart OR
  sudo service apache2 restart

How can I analyze a heap dump in IntelliJ? (memory leak)

The best thing out there is Memory Analyzer (MAT), IntelliJ does not have any bundled heap dump analyzer.

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

Easy way to print Perl array? (with a little formatting)

For inspection/debugging check the Data::Printer module. It is meant to do one thing and one thing only:

display Perl variables and objects on screen, properly formatted (to be inspected by a human)

Example usage:

use Data::Printer;  
p @array;  # no need to pass references

The code above might output something like this (with colors!):

   [
       [0] "a",
       [1] "b",
       [2] undef,
       [3] "c",
   ]

Convert alphabet letters to number in Python

def letter_to_int(letter):
    alphabet = list('abcdefghijklmnopqrstuvwxyz')
    return alphabet.index(letter) + 1

here, the index (x) function returns the position value of x if the list contains x.

Contain form within a bootstrap popover?

<a data-title="A Title" data-placement="top" data-html="true" data-content="<form><input type='text'/></form>" data-trigger="hover" rel="popover" class="btn btn-primary" id="test">Top popover</a>

just state data-html="true"

How to get the list of all database users

SELECT name FROM sys.database_principals WHERE
type_desc = 'SQL_USER' AND default_schema_name = 'dbo'

This selects all the users in the SQL server that the administrator created!

Return the characters after Nth character in a string

Since there is the [vba] tag, split is also easy:

str1 = "001 baseball"
str2 = Split(str1)

Then use str2(1).

Python script to do something at the same time every day

APScheduler might be what you are after.

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])

# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])

https://apscheduler.readthedocs.io/en/latest/

You can just get it to schedule another run by building that into the function you are scheduling.

How do I print colored output to the terminal in Python?

A side note: Windows users should run os.system('color') first, otherwise you would see some ANSI escape sequences rather than a colored output.

How to declare std::unique_ptr and what is the use of it?

There is no difference in working in both the concepts of assignment to unique_ptr.

int* intPtr = new int(3);
unique_ptr<int> uptr (intPtr);

is similar to

unique_ptr<int> uptr (new int(3));

Here unique_ptr automatically deletes the space occupied by uptr.


how pointers, declared in this way will be different from the pointers declared in a "normal" way.

If you create an integer in heap space (using new keyword or malloc), then you will have to clear that memory on your own (using delete or free respectively).

In the below code,

int* heapInt = new int(5);//initialize int in heap memory
.
.//use heapInt
.
delete heapInt;

Here, you will have to delete heapInt, when it is done using. If it is not deleted, then memory leakage occurs.

In order to avoid such memory leaks unique_ptr is used, where unique_ptr automatically deletes the space occupied by heapInt when it goes out of scope. So, you need not do delete or free for unique_ptr.

getting only name of the class Class.getName()

The below both ways works fine.

System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());

Output as below:

The Class Name is: package.Student

The simple Class Name is: Student

Explanation of "ClassCastException" in Java

A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ClassCastExceptionExample {

  public ClassCastExceptionExample() {

    List list = new ArrayList();
    list.add("one");
    list.add("two");
    Iterator it = list.iterator();
    while (it.hasNext()) {
        // intentionally throw a ClassCastException by trying to cast a String to an
        // Integer (technically this is casting an Object to an Integer, where the Object 
        // is really a reference to a String:
        Integer i = (Integer)it.next();
    }
  }
 public static void main(String[] args) {
  new ClassCastExceptionExample();
 }
}

If you try to run this Java program you’ll see that it will throw the following ClassCastException:

Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample  (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main  (ClassCastExceptionExample.java:19)

The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.

How can I make my custom objects Parcelable?

It is very easy, you can use a plugin on android studio to make objects Parcelables.

public class Persona implements Parcelable {
String nombre;
int edad;
Date fechaNacimiento;

public Persona(String nombre, int edad, Date fechaNacimiento) {
    this.nombre = nombre;
    this.edad = edad;
    this.fechaNacimiento = fechaNacimiento;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.nombre);
    dest.writeInt(this.edad);
    dest.writeLong(fechaNacimiento != null ? fechaNacimiento.getTime() : -1);
}

protected Persona(Parcel in) {
    this.nombre = in.readString();
    this.edad = in.readInt();
    long tmpFechaNacimiento = in.readLong();
    this.fechaNacimiento = tmpFechaNacimiento == -1 ? null : new Date(tmpFechaNacimiento);
}

public static final Parcelable.Creator<Persona> CREATOR = new Parcelable.Creator<Persona>() {
    public Persona createFromParcel(Parcel source) {
        return new Persona(source);
    }

    public Persona[] newArray(int size) {
        return new Persona[size];
    }
};}

How to insert the current timestamp into MySQL database using a PHP insert query

Don't like any of those solutions.

this is how i do it:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" 
            . sqlEsc($somename) . "' ;";

then i use my own sqlEsc function:

function sqlEsc($val) 
{
    global $mysqli;
    return mysqli_real_escape_string($mysqli, $val);
}

How to do a scatter plot with empty circles in Python?

Here's another way: this adds a circle to the current axes, plot or image or whatever :

from matplotlib.patches import Circle  # $matplotlib/patches.py

def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
    """ add a circle to ax= or current axes
    """
        # from .../pylab_examples/ellipse_demo.py
    e = Circle( xy=xy, radius=radius )
    if ax is None:
        ax = pl.gca()  # ax = subplot( 1,1,1 )
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_edgecolor( color )
    e.set_facecolor( facecolor )  # "none" not None
    e.set_alpha( alpha )

alt text

(The circles in the picture get squashed to ellipses because imshow aspect="auto" ).

Extracting jar to specified directory

This is what I ended up using inside my .bat file. Windows only of course.

set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%

Add class to an element in Angular 4

Here is a plunker showing how you can use it with the ngClass directive.

I'm demonstrating with divs instead of imgs though.

Template:

<ul>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>

TS:

export class App {
  selectedIndex = -1;

  setSelected(id: number) {
    this.selectedIndex = id;
  }
}

iPhone app could not be installed at this time

in my case app want to use iCloud services, but in distr. provision profile wasn't set iCloud enabled. turn it on and refresh profile.

Linux Command History with date and time

It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history if there is any timestamp there).

To have bash store the timestamp you need to set HISTTIMEFORMAT before executing the commands, e.g. in .bashrc or .bash_profile. This will cause bash to store the timestamps in .bash_history (see the entries starting with #).

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

How to efficiently use try...catch blocks in PHP

There is no any problem to write multiple lines of execution withing a single try catch block like below

try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}

The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}

How do you make a div follow as you scroll?

The post is old but I found a perfect CSS for the purpose and I want to share it.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

    div.sticky {
        position: -webkit-sticky; /* Safari */
        position: sticky;
        top: 0;
        background-color: green;
        border: 2px solid #4CAF50;
    }

Source: https://www.w3schools.com/css/css_positioning.asp

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

How can I change Eclipse theme?

Update December 2012 (19 months later):

The blog post "Jin Mingjian: Eclipse Darker Theme" mentions this GitHub repo "eclipse themes - darker":

enter image description here

The big fun is that, the codes are minimized by using Eclipse4 platform technologies like dependency injection.
It proves that again, the concise codes and advanced features could be achieved by contributing or extending with the external form (like library, framework).
New language is not necessary just for this kind of purpose.


Update July 2012 (14 months later):

With the latest Eclipse4.2 (June 2012, "Juno") release, you can implement what I originally described below: a CSS-based fully dark theme for Eclipse.
See the article by Lars Vogel in "Eclipse 4 is beautiful – Create your own Eclipse 4 theme":

Eclipse fully dark theme

If you want to play with it, you only need to write a plug-in, create a CSS file and use the org.eclipse.e4.ui.css.swt.theme extension point to point to your file.
If you export your plug-in, place it in the “dropins” folder of your Eclipse installation and your styling is available.


Original answer: August 2011

With Eclipse 3.x, theme is only for the editors, as you can see in the site "Eclipse Color Themes".
Anything around that is managed by windows system colors.
That is what you need to change to have any influence on Eclipse global colors around editors.

Eclipse 4 will provide much advance theme options: See "Eclipse 4.0 – So you can theme me Part 1" and "Eclipse 4.0 RCP: Dynamic CSS Theme Switching".

dark theme

Should I use window.navigate or document.location in JavaScript?

I'd go with window.location = "http://...";. I've been coding cross-browser JavaScript for a few years, and I've never experienced problems using this approach.

window.navigate and window.location.href seems a bit odd to me.

Replace multiple characters in one replace call

Please try:

  • replace multi string

    var str = "http://www.abc.xyz.com"; str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"

  • replace multi chars

    var str = "a.b.c.d,e,f,g,h"; str = str.replace(/[.,]/g, ''); //str is "abcdefgh";

Good luck!

Bootstrap 3: pull-right for col-lg only

Try this LESS snippet (It's created from the examples above & the media query mixins in grid.less).

@media (min-width: @screen-sm-min) {
.pull-right-sm {
  float: right;
}
}
@media (min-width: @screen-md-min) {
.pull-right-md {
  float: right;
}
}
@media (min-width: @screen-lg-min) {
.pull-right-lg {
  float: right;
}
}

How to display Oracle schema size with SQL query?

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
    FROM DBA_SEGMENTS DS
    WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES) AND SEGMENT_NAME='YOUR_TABLE_NAME'
    GROUP BY DS.TABLESPACE_NAME, SEGMENT_NAME;

Adding asterisk to required fields in Bootstrap 3

The other two answers are correct. When you include spaces in your CSS selectors you're targeting child elements so:

.form-group .required {
    styles
}

Is targeting an element with the class of "required" that is inside an element with the class of "form-group".

Without the space it's targeting an element that has both classes. 'required' and 'form-group'

What's the difference between using "let" and "var"?

var is global scope (hoist-able) variable.

let and const is block scope.

test.js

_x000D_
_x000D_
{_x000D_
    let l = 'let';_x000D_
    const c = 'const';_x000D_
    var v = 'var';_x000D_
    v2 = 'var 2';_x000D_
}_x000D_
_x000D_
console.log(v, this.v);_x000D_
console.log(v2, this.v2);_x000D_
console.log(l); // ReferenceError: l is not defined_x000D_
console.log(c); // ReferenceError: c is not defined
_x000D_
_x000D_
_x000D_

Node.js - use of module.exports as a constructor

CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new keywords has a simple answer: Yes. I'll illustrate...

Module exports

You can either use the exports variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require() is a reference to the value of module.exports.

A pseudo-code example of how a module is defined:

var theModule = {
  exports: {}
};

(function(module, exports, require) {

  // Your module code goes here

})(theModule, theModule.exports, theRequireFunction);

In the example above module.exports and exports are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.

Require with constructors

Since you can attach a function directly to module.exports you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)

So the following is perfectly good code and I personally encourage it:

// My module
function MyObject(bar) {
  this.bar = bar;
}

MyObject.prototype.foo = function foo() {
  console.log(this.bar);
};

module.exports = MyObject;

// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"

Require for non-constructors

Same thing goes for non-constructor like functions:

// My Module
exports.someFunction = function someFunction(msg) {
  console.log(msg);
}

// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"

Difference between _self, _top, and _parent in the anchor tag target attribute

While these answers are good, IMHO I don't think they fully address the question.

The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.

While target="_self" is default by browser and the most common target is target="_blank" which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent", "_top" and framename tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.

target="_self" This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame and frameset tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.

target="_parent" Will open the in the next level up of a frame if they were nested to inside one another

target="_top" This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.

target="framename This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name was the proper method that method has been replaced with using the id identifying tag.

<!--Example:-->

<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>

<a href="url4" target="B"></a>
</body>
</html>

Random integer in VB.NET

Just for reference, VB NET Fuction definition for RND and RANDOMIZE (which should give the same results of BASIC (1980 years) and all versions after is:

Public NotInheritable Class VBMath
    ' Methods
    Private Shared Function GetTimer() As Single
        Dim now As DateTime = DateTime.Now
        Return CSng((((((60 * now.Hour) + now.Minute) * 60) + now.Second) + (CDbl(now.Millisecond) / 1000)))
    End Function

    Public Shared Sub Randomize()
        Dim timer As Single = VBMath.GetTimer
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        Dim num3 As Integer = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0)
        num3 = (((num3 And &HFFFF) Xor (num3 >> &H10)) << 8)
        rndSeed = ((rndSeed And -16776961) Or num3)
        projectData.m_rndSeed = rndSeed
    End Sub

    Public Shared Sub Randomize(ByVal Number As Double)
        Dim num2 As Integer
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        If BitConverter.IsLittleEndian Then
            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 4)
        Else
            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 0)
        End If
        num2 = (((num2 And &HFFFF) Xor (num2 >> &H10)) << 8)
        rndSeed = ((rndSeed And -16776961) Or num2)
        projectData.m_rndSeed = rndSeed
    End Sub

    Public Shared Function Rnd() As Single
        Return VBMath.Rnd(1!)
    End Function

    Public Shared Function Rnd(ByVal Number As Single) As Single
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        If (Number <> 0) Then
            If (Number < 0) Then
                Dim num1 As UInt64 = (BitConverter.ToInt32(BitConverter.GetBytes(Number), 0) And &HFFFFFFFF)
                rndSeed = CInt(((num1 + (num1 >> &H18)) And CULng(&HFFFFFF)))
            End If
            rndSeed = CInt((((rndSeed * &H43FD43FD) + &HC39EC3) And &HFFFFFF))
        End If
        projectData.m_rndSeed = rndSeed
        Return (CSng(rndSeed) / 1.677722E+07!)
    End Function

End Class

While the Random CLASS is:

Public Class Random
    ' Methods
    <__DynamicallyInvokable> _
    Public Sub New()
        Me.New(Environment.TickCount)
    End Sub

    <__DynamicallyInvokable> _
    Public Sub New(ByVal Seed As Integer)
        Me.SeedArray = New Integer(&H38  - 1) {}
        Dim num4 As Integer = If((Seed = -2147483648), &H7FFFFFFF, Math.Abs(Seed))
        Dim num2 As Integer = (&H9A4EC86 - num4)
        Me.SeedArray(&H37) = num2
        Dim num3 As Integer = 1
        Dim i As Integer
        For i = 1 To &H37 - 1
            Dim index As Integer = ((&H15 * i) Mod &H37)
            Me.SeedArray(index) = num3
            num3 = (num2 - num3)
            If (num3 < 0) Then
                num3 = (num3 + &H7FFFFFFF)
            End If
            num2 = Me.SeedArray(index)
        Next i
        Dim j As Integer
        For j = 1 To 5 - 1
            Dim k As Integer
            For k = 1 To &H38 - 1
                Me.SeedArray(k) = (Me.SeedArray(k) - Me.SeedArray((1 + ((k + 30) Mod &H37))))
                If (Me.SeedArray(k) < 0) Then
                    Me.SeedArray(k) = (Me.SeedArray(k) + &H7FFFFFFF)
                End If
            Next k
        Next j
        Me.inext = 0
        Me.inextp = &H15
        Seed = 1
    End Sub

    Private Function GetSampleForLargeRange() As Double
        Dim num As Integer = Me.InternalSample
        If ((Me.InternalSample Mod 2) = 0) Then
            num = -num
        End If
        Dim num2 As Double = num
        num2 = (num2 + 2147483646)
        Return (num2 / 4294967293)
    End Function

    Private Function InternalSample() As Integer
        Dim inext As Integer = Me.inext
        Dim inextp As Integer = Me.inextp
        If (++inext >= &H38) Then
            inext = 1
        End If
        If (++inextp >= &H38) Then
            inextp = 1
        End If
        Dim num As Integer = (Me.SeedArray(inext) - Me.SeedArray(inextp))
        If (num = &H7FFFFFFF) Then
            num -= 1
        End If
        If (num < 0) Then
            num = (num + &H7FFFFFFF)
        End If
        Me.SeedArray(inext) = num
        Me.inext = inext
        Me.inextp = inextp
        Return num
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next]() As Integer
        Return Me.InternalSample
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next](ByVal maxValue As Integer) As Integer
        If (maxValue < 0) Then
            Dim values As Object() = New Object() { "maxValue" }
            Throw New ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", values))
        End If
        Return CInt((Me.Sample * maxValue))
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next](ByVal minValue As Integer, ByVal maxValue As Integer) As Integer
        If (minValue > maxValue) Then
            Dim values As Object() = New Object() { "minValue", "maxValue" }
            Throw New ArgumentOutOfRangeException("minValue", Environment.GetResourceString("Argument_MinMaxValue", values))
        End If
        Dim num As Long = (maxValue - minValue)
        If (num <= &H7FFFFFFF) Then
            Return (CInt((Me.Sample * num)) + minValue)
        End If
        Return (CInt(CLng((Me.GetSampleForLargeRange * num))) + minValue)
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Sub NextBytes(ByVal buffer As Byte())
        If (buffer Is Nothing) Then
            Throw New ArgumentNullException("buffer")
        End If
        Dim i As Integer
        For i = 0 To buffer.Length - 1
            buffer(i) = CByte((Me.InternalSample Mod &H100))
        Next i
    End Sub

    <__DynamicallyInvokable> _
    Public Overridable Function NextDouble() As Double
        Return Me.Sample
    End Function

    <__DynamicallyInvokable> _
    Protected Overridable Function Sample() As Double
        Return (Me.InternalSample * 4.6566128752457969E-10)
    End Function


    ' Fields
    Private inext As Integer
    Private inextp As Integer
    Private Const MBIG As Integer = &H7FFFFFFF
    Private Const MSEED As Integer = &H9A4EC86
    Private Const MZ As Integer = 0
    Private SeedArray As Integer()
End Class

Sorting a List<int>

There's no need for LINQ here, just call Sort:

list.Sort();

Example code:

List<int> list = new List<int> { 5, 7, 3 };
list.Sort();
foreach (int x in list)
{
    Console.WriteLine(x);
}

Result:

3
5
7

How to compare two strings are equal in value, what is the best method?

== checks to see if they are actually the same object in memory (which confusingly sometimes is true, since they may both be from the pool), where as equals() is overridden by java.lang.String to check each character to ensure true equality. So therefore, equals() is what you want.

Remove leading zeros from a number in Javascript

We can use four methods for this conversion

  1. parseInt with radix 10
  2. Number Constructor
  3. Unary Plus Operator
  4. Using mathematical functions (subtraction)

_x000D_
_x000D_
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
_x000D_
_x000D_


Update(based on comments): Why doesn't this work on "large numbers"?

For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER).

_x000D_
_x000D_
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
_x000D_
_x000D_

Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods

_x000D_
_x000D_
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
_x000D_
_x000D_

All results will be incorrect.

That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means all operation performed with the assumption that the stringcan be converted to number type fails.

For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere.

The conversion code will be like this.

const numString = '099999999999999999999';
const number = BigInt(numString);

P.S: Why radix is important for parseInt?

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal)
  • If the input string begins with any other value, the radix is 10 (decimal)

Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.

For this reason, always specify a radix when using parseInt

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

void operator could be used here.
Instead of:

React.useEffect(() => {
    async function fetchData() {
    }
    fetchData();
}, []);

or

React.useEffect(() => {
    (async function fetchData() {
    })()
}, []);

you could write:

React.useEffect(() => {
    void async function fetchData() {
    }();
}, []);

It is a little bit cleaner and prettier.


Async effects could cause memory leaks so it is important to perform cleanup on component unmount. In case of fetch this could look like this:

function App() {
    const [ data, setData ] = React.useState([]);

    React.useEffect(() => {
        const abortController = new AbortController();
        void async function fetchData() {
            try {
                const url = 'https://jsonplaceholder.typicode.com/todos/1';
                const response = await fetch(url, { signal: abortController.signal });
                setData(await response.json());
            } catch (error) {
                console.log('error', error);
            }
        }();
        return () => {
            abortController.abort(); // cancel pending fetch request on component unmount
        };
    }, []);

    return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

The entity cannot be constructed in a LINQ to Entities query

In response to the other question which was marked as duplicate (see here) I figured out a quick and easy solution based on the answer of Soren:

data.Tasks.AddRange(
    data.Task.AsEnumerable().Select(t => new Task{
        creator_id   = t.ID,
        start_date   = t.Incident.DateOpened,
        end_date     = t.Incident.DateCLosed,
        product_code = t.Incident.ProductCode
        // so on...
    })
);
data.SaveChanges();

Note: This solution only works if you have a navigation property (foreign key) on the Task class (here called 'Incident'). If you don't have that, you can just use one of the other posted solutions with "AsQueryable()".

How to get POSTed JSON in Flask?

You may note that request.json or request.get_json() works only when the "Content-type: application/json" has been added in the header of the request. If you are unable to change the client request configuration, so you can get the body as json like this:

data = json.loads(request.data)

How to calculate mean, median, mode and range from a set of numbers

As already pointed out by Nico Huysamen, finding multiple mode in Java 1.8 can be done alternatively as below.

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

public static void mode(List<Integer> numArr) {
    Map<Integer, Integer> freq = new HashMap<Integer, Integer>();;
    Map<Integer, List<Integer>> mode = new HashMap<Integer, List<Integer>>();

    int modeFreq = 1; //record the highest frequence
    for(int x=0; x<numArr.size(); x++) { //1st for loop to record mode
        Integer curr = numArr.get(x); //O(1)
        freq.merge(curr, 1, (a, b) -> a + b); //increment the frequency for existing element, O(1)
        int currFreq = freq.get(curr); //get frequency for current element, O(1)

        //lazy instantiate a list if no existing list, then
        //record mapping of frequency to element (frequency, element), overall O(1)
        mode.computeIfAbsent(currFreq, k -> new ArrayList<>()).add(curr);

        if(modeFreq < currFreq) modeFreq = currFreq; //update highest frequency
    }
    mode.get(modeFreq).forEach(x -> System.out.println("Mode = " + x)); //pretty print the result //another for loop to return result
}

Happy coding!

Select a random sample of results from a query result

Sample function is used for sample data in ORACLE. So you can try like this:-

SELECT * FROM TABLE_NAME SAMPLE(50);

Here 50 is the percentage of data contained by the table. So if you want 1000 rows from 100000. You can execute a query like:

SELECT * FROM TABLE_NAME SAMPLE(1);

Hope this can help you.

Adding a new line/break tag in XML

just simply press enter it make a break

<![CDATA[this is
my text.]]>

Check if Internet Connection Exists with jQuery?

i have a solution who work here to check if internet connection exist :

$.ajax({
    url: "http://www.google.com",
    context: document.body,
    error: function(jqXHR, exception) {
        alert('Offline')
    },
    success: function() {
        alert('Online')
    }
})

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

Creating C formatted strings (not printing them)

Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf

final keyword in method parameters

Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.

Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.

How do you pass a function as a parameter in C?

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

Bootstrap modal link

A Simple Approach will be to use a normal link and add Bootstrap modal effect to it. Just make use of my Code, hopefully you will get it run.

 <div class="container">
        <div class="row">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="addContact" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><b style="color:#fb3600; font-weight:700;">X</b></button><!--&times;-->
                            <h4 class="modal-title text-center" id="addContact">Add Contact</h4>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <ul class="nav nav-tabs">
                                    <li class="active">
                                        <a data-toggle="tab" style="background-color:#f5dfbe" href="#contactTab">Contact</a>
                                    </li>
                                    <li>
                                        <a data-toggle="tab" style="background-color:#a6d2f6" href="#speechTab">Speech</a>
                                    </li>
                                </ul>
                                <div class="tab-content">
                                    <div id="contactTab" class="tab-pane in active"><partial name="CreateContactTag"></div>
                                    <div id="speechTab" class="tab-pane fade in"><partial name="CreateSpeechTag"></div>
                                </div>

                            </div>
                        </div>
                        <div class="modal-footer">
                            <a class="btn btn-info" data-dismiss="modal">Close</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Is optimisation level -O3 dangerous in g++?

In the early days of gcc (2.8 etc.) and in the times of egcs, and redhat 2.96 -O3 was quite buggy sometimes. But this is over a decade ago, and -O3 is not much different than other levels of optimizations (in buggyness).

It does however tend to reveal cases where people rely on undefined behavior, due to relying more strictly on the rules, and especially corner cases, of the language(s).

As a personal note, I am running production software in the financial sector for many years now with -O3 and have not yet encountered a bug that would not have been there if I would have used -O2.

By popular demand, here an addition:

-O3 and especially additional flags like -funroll-loops (not enabled by -O3) can sometimes lead to more machine code being generated. Under certain circumstances (e.g. on a cpu with exceptionally small L1 instruction cache) this can cause a slowdown due to all the code of e.g. some inner loop now not fitting anymore into L1I. Generally gcc tries quite hard to not to generate so much code, but since it usually optimizes the generic case, this can happen. Options especially prone to this (like loop unrolling) are normally not included in -O3 and are marked accordingly in the manpage. As such it is generally a good idea to use -O3 for generating fast code, and only fall back to -O2 or -Os (which tries to optimize for code size) when appropriate (e.g. when a profiler indicates L1I misses).

If you want to take optimization into the extreme, you can tweak in gcc via --param the costs associated with certain optimizations. Additionally note that gcc now has the ability to put attributes at functions that control optimization settings just for these functions, so when you find you have a problem with -O3 in one function (or want to try out special flags for just that function), you don't need to compile the whole file or even whole project with O2.

otoh it seems that care must be taken when using -Ofast, which states:

-Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard compliant programs.

which makes me conclude that -O3 is intended to be fully standards compliant.

How to implement LIMIT with SQL Server?

Clunky, but it'll work.

SELECT TOP 10 * FROM table WHERE id NOT IN (SELECT TOP 10 id FROM table ORDER BY id) FROM table ORDER BY id

MSSQL's omission of a LIMIT clause is criminal, IMO. You shouldn't have to do this kind of kludgy workaround.

SQL string value spanning multiple lines in query

SQL Server allows the following (be careful to use single quotes instead of double)

UPDATE User
SET UserId = 12345
   , Name = 'J Doe'
   , Location = 'USA'
   , Bio='my bio
spans 
multiple
lines!'
WHERE UserId = 12345

xcode library not found

You can also try to lint with the --use-library option, as cocoapods lint libraries as framework by default since v0.36

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

phpmailer - The following SMTP Error: Data not accepted

Try to set the port on 26, this has fixed my problem with the message "data not accepted".

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

See this answer for more info on How to access the dom element in React

Running Node.Js on Android

You can use Node.js for Mobile Apps.

It works on Android devices and simulators, with pre-built binaries for armeabi-v7a, x86, arm64-v8a, x86_64. It also works on iOS, though that's outside the scope of this question.

Like JXcore, it is used to host a Node.js engine in the same process as the app, in a dedicated thread. Unlike JXcore, it is basically pure Node.js, built as a library, with a few portability fixes to run on Android. This means that it's much easier to keep the project up to date with mainline Node.js.

Plugins for Cordova and React Native are also available. The plugins provide a communication layer between the JavaScript side of those frameworks and the Node.js side. They also simplify development by taking care of a few things automatically, like packaging modules and cross-compiling native modules at build time.

Full disclosure: I work for the company that develops Node.js for Mobile Apps.

How to set TextView textStyle such as bold, italic

Try this:

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);

Spring RestTemplate GET with parameters

OK, so I'm being an idiot and I'm confusing query parameters with url parameters. I was kinda hoping there would be a nicer way to populate my query parameters rather than an ugly concatenated String but there we are. It's simply a case of build the URL with the correct parameters. If you pass it as a String Spring will also take care of the encoding for you.

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

Add property to an array of objects

You can use the forEach method to execute a provided function once for each element in the array. In this provided function you can add the Active property to the element.

Results.forEach(function (element) {
  element.Active = "false";
});

How to extract a string using JavaScript Regex?

This code works:

  let str = "governance[string_i_want]"; 
  let res = str.match(/[^governance\[](.*)[^\]]/g);

res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.

By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!

You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp

Good luck.

Refresh (reload) a page once using jQuery?

You don't have a jQuery refresh function, because this is JavaScript basics.

Try this:

<body onload="if (location.href.indexOf('reload')==-1) location.replace(location.href+'?reload');">

Run function in script from command line (Node JS)

simple way:

let's say you have db.js file in a helpers directory in project structure.

now go inside helpers directory and go to node console

 helpers $ node

2) require db.js file

> var db = require("./db")

3) call your function (in your case its init())

> db.init()

hope this helps

How to install a specific JDK on Mac OS X?

For people using any LION OS X 10.7.X

They uploaded Java SE 6 version 1.6.0_26 available here

http://support.apple.com/kb/dl1421

MongoDB via Mongoose JS - What is findByID?

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

How to fire an event on class change using jQuery?

you can use something like this:

$(this).addClass('someClass');

$(Selector).trigger('ClassChanged')

$(otherSelector).bind('ClassChanged', data, function(){//stuff });

but otherwise, no, there's no predefined function to fire an event when a class changes.

Read more about triggers here

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

How to substring in jquery

Standard javascript will do that using the following syntax:

string.substring(from, to)

var name = "nameGorge";
var output = name.substring(4);

Read more here: http://www.w3schools.com/jsref/jsref_substring.asp

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

This latest announcement list snippet might be of interest if you'll be upgrading to 8.4:

Until 8.4 comes out with a super-effient native one, you can add the array_accum() function in the PostgreSQL documentation for rolling up any column into an array, which can then be used by application code, or combined with array_to_string() to format it as a list:

http://www.postgresql.org/docs/current/static/xaggr.html

I'd link to the 8.4 development docs but they don't seem to list this feature yet.

Deadly CORS when http://localhost is the origin

None of the extensions worked for me, so I installed a simple local proxy. In my case https://www.npmjs.com/package/local-cors-proxy It is a 2-minute setup:

(from their site)

npm install -g local-cors-proxy

API endpoint that we want to request that has CORS issues: https://www.yourdomain.ie/movies/list

Start Proxy: lcp --proxyUrl https://www.yourdomain.ie

Then in your client code, new API endpoint: http://localhost:8010/proxy/movies/list

Worked like a charm for me: your app calls the proxy, who calls the server. Zero CORS problems.

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

Deleting queues in RabbitMQ

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
               'localhost'))
channel = connection.channel()

channel.queue_delete(queue='queue-name')

connection.close()

Install pika package as follows

$ sudo pip install pika==0.9.8

The installation depends on pip and git-core packages, you may need to install them first.

On Ubuntu:

$ sudo apt-get install python-pip git-core

On Debian:

$ sudo apt-get install python-setuptools git-core
$ sudo easy_install pip

On Windows: To install easy_install, run the MS Windows Installer for setuptools

> easy_install pip
> pip install pika==0.9.8

PHP CSV string to array

If you have carriage return/line feeds within columns, str_getcsv will not work.

Try https://github.com/synappnz/php-csv

Use:

include "csv.php";
$csv = new csv(file_get_contents("filename.csv"));
$rows = $csv->rows();
foreach ($rows as $row)
{
  // do something with $row
}

How are parameters sent in an HTTP POST request?

You cannot type it directly on the browser URL bar.

You can see how POST data is sent on the Internet with Live HTTP Headers for example. Result will be something like that

http://127.0.0.1/pass.php
POST /pass.php HTTP/1.1

Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1/pass.php
Cookie: passx=87e8af376bc9d9bfec2c7c0193e6af70; PHPSESSID=l9hk7mfh0ppqecg8gialak6gt5
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
username=zurfyx&pass=password

Where it says

Content-Length: 30
    username=zurfyx&pass=password

will be the post values.

How to sort an object array by date property?

@Phrogz answers are both great, but here is a great, more concise answer:

array.sort(function(a,b){return a.getTime() - b.getTime()});

Using the arrow function way

array.sort((a,b)=>a.getTime()-b.getTime());

found here: Sort date in Javascript

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

man date on OSX has this example

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

Which I think does what you want.

You can use this for a specific date

date -j -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

Or use whatever format you want.

how to add button click event in android studio

package com.mani.smsdetect;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

    //Declaration Button
    Button btnClickMe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Intialization Button

        btnClickMe = (Button) findViewById(R.id.btnClickMe);

        btnClickMe.setOnClickListener(MainActivity.this);
        //Here MainActivity.this is a Current Class Reference (context)
    }

    @Override
    public void onClick(View v) {

        //Your Logic
    }
}

Error 0x80005000 and DirectoryServices

I had to change my code from this:

 DirectoryEntry entry = new DirectoryEntry(path, ldapUser, ldapPassword);
 DirectorySearcher searcher = new DirectorySearcher();
 searcher.SearchRoot = entry;
 searcher.SearchScope = SearchScope.Subtree;

To this:

DirectoryEntry entry = new DirectoryEntry(path, ldapUser, ldapPassword);
DirectorySearcher searcher = new DirectorySearcher();
searcher.SearchScope = SearchScope.OneLevel;
SearchResult searchResult = searcher.FindOne();

PHP salt and hash SHA256 for login password

According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler

Example for store the password:

$hashPassword = password_hash("password", PASSWORD_BCRYPT);

Example to verify the password:

$passwordCorrect = password_verify("password", $hashPassword);

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

add your default theme this line;

   <item name="colorControlNormal">@color/my_color</item>

How to suspend/resume a process in Windows?

#pragma comment(lib,"ntdll.lib")
EXTERN_C NTSTATUS NTAPI NtSuspendProcess(IN HANDLE ProcessHandle);

void SuspendSelf(){
    NtSuspendProcess(GetCurrentProcess());
}

ntdll contains the exported function NtSuspendProcess, pass the handle to a process to do the trick.

MySQL Insert into multiple tables? (Database normalization?)

What would happen, if you want to create many such records ones (to register 10 users, not just one)? I find the following solution (just 5 queryes):

Step I: Create temporary table to store new data.

CREATE TEMPORARY TABLE tmp (id bigint(20) NOT NULL, ...)...;

Next, fill this table with values.

INSERT INTO tmp (username, password, bio, homepage) VALUES $ALL_VAL

Here, instead of $ALL_VAL you place list of values: ('test1','test1','bio1','home1'),...,('testn','testn','bion','homen')

Step II: Send data to 'user' table.

INSERT IGNORE INTO users (username, password)
SELECT username, password FROM tmp;

Here, "IGNORE" can be used, if you allow some users already to be inside. Optionaly you can use UPDATE similar to step III, before this step, to find whom users are already inside (and mark them in tmp table). Here we suppouse, that username is declared as PRIMARY in users table.

Step III: Apply update to read all users id from users to tmp table. THIS IS ESSENTIAL STEP.

UPDATE tmp JOIN users ON tmp.username=users.username SET tmp.id=users.id

Step IV: Create another table, useing read id for users

INSERT INTO profiles (userid, bio, homepage) 
SELECT id, bio, homepage FROM tmp

Send Email to multiple Recipients with MailMessage?

According to the Documentation :

MailMessage.To property - Returns MailAddressCollection that contains the list of recipients of this email message

Here MailAddressCollection has a in built method called

   public void Add(string addresses)

   1. Summary:
          Add a list of email addresses to the collection.

   2. Parameters:
          addresses: 
                *The email addresses to add to the System.Net.Mail.MailAddressCollection. Multiple
                *email addresses must be separated with a comma character (",").     

Therefore requirement in case of multiple recipients : Pass a string that contains email addresses separated by comma

In your case :

simply replace all the ; with ,

Msg.To.Add(toEmail.replace(";", ","));

For reference :

  1. https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=netframework-4.8
  2. https://www.geeksforgeeks.org/c-sharp-replace-method/

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

You can just serialize the base object to JSON and then deserialize it to the derived object.

Adding a guideline to the editor in Visual Studio

If you are a user of the free Visual Studio Express edition the right key is in

HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor

{note the VCExpress instead of VisualStudio) but it works! :)

How to get all of the immediate subdirectories in Python

I did some speed testing on various functions to return the full path to all current subdirectories.

tl;dr: Always use scandir:

list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]

Bonus: With scandir you can also simply only get folder names by using f.name instead of f.path.

This (as well as all other functions below) will not use natural sorting. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at https://stackoverflow.com/a/48030307/2441026




Results: scandir is: 3x faster than walk, 32x faster than listdir (with filter), 35x faster than Pathlib and 36x faster than listdir and 37x (!) faster than glob.

Scandir:           0.977
Walk:              3.011
Listdir (filter): 31.288
Pathlib:          34.075
Listdir:          35.501
Glob:             36.277

Tested with W7x64, Python 3.8.1. Folder with 440 subfolders.
In case you wonder if listdir could be speed up by not doing os.path.join() twice, yes, but the difference is basically nonexistent.

Code:

import os
import pathlib
import timeit
import glob

path = r"<example_path>"



def a():
    list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]
    # print(len(list_subfolders_with_paths))


def b():
    list_subfolders_with_paths = [os.path.join(path, f) for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
    # print(len(list_subfolders_with_paths))


def c():
    list_subfolders_with_paths = []
    for root, dirs, files in os.walk(path):
        for dir in dirs:
            list_subfolders_with_paths.append( os.path.join(root, dir) )
        break
    # print(len(list_subfolders_with_paths))


def d():
    list_subfolders_with_paths = glob.glob(path + '/*/')
    # print(len(list_subfolders_with_paths))


def e():
    list_subfolders_with_paths = list(filter(os.path.isdir, [os.path.join(path, f) for f in os.listdir(path)]))
    # print(len(list(list_subfolders_with_paths)))


def f():
    p = pathlib.Path(path)
    list_subfolders_with_paths = [x for x in p.iterdir() if x.is_dir()]
    # print(len(list_subfolders_with_paths))



print(f"Scandir:          {timeit.timeit(a, number=1000):.3f}")
print(f"Listdir:          {timeit.timeit(b, number=1000):.3f}")
print(f"Walk:             {timeit.timeit(c, number=1000):.3f}")
print(f"Glob:             {timeit.timeit(d, number=1000):.3f}")
print(f"Listdir (filter): {timeit.timeit(e, number=1000):.3f}")
print(f"Pathlib:          {timeit.timeit(f, number=1000):.3f}")

Programmatically add custom event in the iPhone Calendar

The Google idea is a nice one, but has problems.

I can successfully open a Google calendar event screen - but only on the main desktop version, and it doesn't display properly on iPhone Safari. The Google mobile calendar, which does display properly on Safari, doesn't seem to work with the API to add events.

For the moment, I can't see a good way out of this one.

Link a photo with the cell in excel

Select both the column you are sorting, and the column that the picture is in (I am assuming the picture is small compared to the cell, i.e. it is "in" the cell). Make sure that the object positioning property is set as "move but don't size with cells". Now if you do a sort, the pictures will move with the list being sorted.

Note - you must include the column with the picture in your range when you sort, and the picture must fit inside the cell.

The following VBA snippet will make sure all pictures in your spreadsheet have their "move and size" property set:

Sub moveAndSize()
Dim s As Shape
For Each s In ActiveSheet.Shapes
  If s.Type = msoPicture Or s.Type = msoLinkedPicture Or s.Type = msoPlaceholder Then
    s.Placement = xlMove
  End If
Next
End Sub

If you want to make sure the picture continues to fit after you move it, you can use xlMoveAndSize instead of xlMove.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

This is a great solution! With a few additional CSS rules you can format it just like an MS Word outline list with a hanging first line indent:

OL { 
  counter-reset: item; 
}
LI { 
  display: block; 
}
LI:before { 
  content: counters(item, ".") "."; 
  counter-increment: item; 
  padding-right:10px; 
  margin-left:-20px;
}

Using Git, show all commits that are in one branch, but not the other(s)

For those still looking for a simple answer, check out git cherry. It compares actual diffs instead of commit hashes. That means it accommodates commits that have been cherry picked or rebased.

First checkout the branch you want to delete:

git checkout [branch-to-delete]

then use git cherry to compare it to your main development branch:

git cherry -v master

Example output:

+ 8a14709d08c99c36e907e47f9c4dacebeff46ecb Commit message
+ b30ccc3fb38d3d64c5fef079a761c7e0a5c7da81 Another commit message
- 85867e38712de930864c5edb7856342e1358b2a0 Yet another message

Note: The -v flag is to include the commit message along with the SHA hash.

Lines with the '+' in front are in the branch-to-delete, but not the master branch. Those with a '-' in front have an equivalent commit in master.

For JUST the commits that aren't in master, combine cherry pick with grep:

git cherry -v master | grep "^\+"

Example output:

+ 8a14709d08c99c36e907e47f9c4dacebeff46ecb Commit message
+ b30ccc3fb38d3d64c5fef079a761c7e0a5c7da81 Another commit message

python for increment inner loop

I read all the above answers and those are actually good.

look at this code:

for i in range(1, 4):
    print("Before change:", i)
    i = 20 # changing i variable
    print("After change:", i) # this line will always print 20

When we execute above code the output is like below,

Before Change: 1
After change: 20
Before Change: 2
After change: 20
Before Change: 3
After change: 20

in python for loop is not trying to increase i value. for loop is just assign values to i which we gave. Using range(4) what we are doing is we give the values to for loop which need assign to the i.

You can use while loop instead of for loop to do same thing what you want,

i = 0
while i < 6:
    print(i)
    j = 0
    while j < 5:
        i += 2 # to increase `i` by 2

This will give,

0
2
4

Thank you !

What is the role of the bias in neural networks?

In neural networks:

  1. Each Neuron has a bias
  2. You can view bias as threshold ( generally opposite values of threshold)
  3. Weighted sum from input layers + bias decides activation of neuron
  4. Bias increases the flexibility of the model.

In absence of bias, the neuron may not be activated by considering only the weighted sum from input layer. If the neuron is not activated, the information from this neuron is not passed through rest of neural network.

The value of bias is learn-able.

enter image description here

Effectively, bias = — threshold. You can think of bias as how easy it is to get the neuron to output a 1 — with a really big bias, it’s very easy for the neuron to output a 1, but if the bias is very negative, then it’s difficult.

in summary : bias helps in controlling the value at which activation function will trigger.

Follow this video for more details

Few more useful links:

geeksforgeeks

towardsdatascience

Bootstrap Collapse not Collapsing

jQuery is required ;-)

DEMO

<html>
<head>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <!-- THIS LINE -->
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                    Collapsible Group Item #1
                </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit
            </div>
        </div>
    </div>
</div>

</body>
</html>

Count number of rows within each group

An old question without a data.table solution. So here goes...

Using .N

library(data.table)
DT <- data.table(df)
DT[, .N, by = list(year, month)]

how I can show the sum of in a datagridview column?

Use LINQ if you can.

  label1.Text =  dataGridView1.Rows.Cast<DataGridViewRow>()
                                   .AsEnumerable()
                                   .Sum(x => int.Parse(x.Cells[1].Value.ToString()))
                                   .ToString();

What svn command would list all the files modified on a branch?

This will do it I think:

svn diff -r 22334:HEAD --summarize <url of the branch>

How can I force users to access my page over HTTPS instead of HTTP?

Use $_SERVER['HTTPS'] to tell if it is SSL, and redirect to the right place if not.

And remember, the page that displays the form does not need to be fed via HTTPS, it's the post back URL that needs it most.

Edit: yes, as is pointed out below, it's best to have the entire process in HTTPS. It's much more reassuring - I was pointing out that the post is the most critical part. Also, you need to take care that any cookies are set to be secure, so they will only be sent via SSL. The mod_rewrite solution is also very nifty, I've used it to secure a lot of applications on my own website.

How to set border's thickness in percentages?

You can make a custom border using a span. Make a span with a class (Specifying the direction in which the border is going) and an id:

<html>
    <body>
        <div class="mdiv">
            <span class="VerticalBorder" id="Span1"></span>
            <header class="mheader">
                <span class="HorizontalBorder" id="Span2"></span>
            </header>
        </div>
    </body>
</html>

Then, go to you CSS and set the class to position:absolute, height:100% (For Vertical Borders), width:100% (For Horizontal Borders), margin:0% and background-color:#000000;. Add everthing else that is necessary:

body{
    margin:0%;
}

div.mdiv{
    position:absolute;
    width:100%;
    height:100%;
    top:0%;
    left:0%;
    margin:0%;
}

header.mheader{
    position:absolute;
    width:100%;
    height:20%; /* You can set this to whatever. I will use 20 for easier calculations. You don't need a header. I'm using it to show you the difference. */
    top:0%;
    left:0%;
    margin:0%;
}

span.HorizontalBorder{
    position:absolute;
    width:100%;
    margin:0%;
    background-color:#000000;
}

span.VerticalBorder{
    position:absolute;
    height:100%;
    margin:0%;
    background-color:#000000;
}

Then set the id that corresponds to class="VerticalBorder" to top:0%;, left:0%;, width:1%; (Since the width of the mdiv is equal to the width of the mheader at 100%, the width will be 100% of what you set it. If you set the width to 1% the border will be 1% of the window's width). Set the id that corresponds to the class="HorizontalBorder" to top:99% (Since it's in a header container the top refers to the position it is in according to the header. This + the height should add up to 100% if you want it to reach the bottom), left:0%; and height:1%(Since the height of the mdiv is 5 times greater than the mheader height [100% = 100, 20% = 20, 100/20 = 5], the height will be 20% of what you set it. If you set the height to 1% the border will be .2% of the window's height). Here is how it will look:

span#Span1{
    top:0%;
    left:0%;
    width:.4%;
}
span#Span2{
    top:99%;
    left:0%;
    width:1%;
}

DISCLAIMER: If you resize the window to a small enough size, the borders will disappear. A solution would be to cap of the size of the border if the window is resized to a certain point. Here is what I did:

window.addEventListener("load", Loaded);

function Loaded() {
  window.addEventListener("resize", Resized);

  function Resized() {
    var WindowWidth = window.innerWidth;
    var WindowHeight = window.innerHeight;
    var Span1 = document.getElementById("Span1");
    var Span2 = document.getElementById("Span2");
    if (WindowWidth <= 800) {
      Span1.style.width = .4;
    }
    if (WindowHeight <= 600) {
      Span2.style.height = 1;
    }
  }
}

If you did everything right, it should look like how it is in this link: https://jsfiddle.net/umhgkvq8/12/ For some odd reason, the the border will disappear in jsfiddle but not if you launch it to a browser.

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

As some suggested here, replacing utf8mb4 with utf8 will help you resolve the issue. IMHO, I used sed to find and replace them to avoid losing data. In addition, opening a large file into any graphical editor is potential pain. My MySQL data grows up 2 GB. The ultimate command is

sed 's/utf8mb4_unicode_520_ci/utf8_unicode_ci/g' original-mysql-data.sql > updated-mysql-data.sql
sed 's/utf8mb4/utf8/g' original-mysql-data.sql > updated-mysql-data.sql

Done!

How can I find the location of origin/master in git, and how do I change it?

I thought my laptop was the origin…

That’s kind of nonsensical: origin refers to the default remote repository – the one you usually fetch/pull other people’s changes from.

How can I:

  1. git remote -v will show you what origin is; origin/master is your “bookmark” for the last known state of the master branch of the origin repository, and your own master is a tracking branch for origin/master. This is all as it should be.

  2. You don’t. At least it makes no sense for a repository to be the default remote repository for itself.

  3. It isn’t. It’s merely telling you that you have made so-and-so many commits locally which aren’t in the remote repository (according to the last known state of that repository).

Using Tkinter in python to edit the title bar

Here it is nice and simple.

root = tkinter.Tk()
root.title('My Title')

root is the window you create and root.title() sets the title of that window.

How to get the list of files in a directory in a shell script?

The accepted answer will not return files prefix with a . To do that use

for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
  echo "$entry"
done

What is the difference between re.search and re.match?

The difference is, re.match() misleads anyone accustomed to Perl, grep, or sed regular expression matching, and re.search() does not. :-)

More soberly, As John D. Cook remarks, re.match() "behaves as if every pattern has ^ prepended." In other words, re.match('pattern') equals re.search('^pattern'). So it anchors a pattern's left side. But it also doesn't anchor a pattern's right side: that still requires a terminating $.

Frankly given the above, I think re.match() should be deprecated. I would be interested to know reasons it should be retained.

Get Last Part of URL PHP

One line working answer:

$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));

Output: drink

How to check if String is null

To sure, you should use function to check is null and empty as below:

string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}

How to generate a random alpha-numeric string

Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes.

public class RandomString {

    /**
     * Generate a random string.
     */
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];
    }

    /**
     * Create an alphanumeric string generator.
     */
    public RandomString(int length, Random random) {
        this(length, random, alphanum);
    }

    /**
     * Create an alphanumeric strings from a secure generator.
     */
    public RandomString(int length) {
        this(length, new SecureRandom());
    }

    /**
     * Create session identifiers.
     */
    public RandomString() {
        this(21);
    }

}

Usage examples

Create an insecure generator for 8-character identifiers:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2‑50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

Meaning of 'const' last in a function declaration of a class?

The const keyword used with the function declaration specifies that it is a const member function and it will not be able to change the data members of the object.

Execute a command line binary with Node.js

Use this lightweight npm package: system-commands

Look at it here.

Import it like this:

const system = require('system-commands')

Run commands like this:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})

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

In this case the CORS problem has been caused by using the wrong source constructor in OpenLayers. ol.source.OSM is intended for accessing the default OpenStreetMap tiles from the web and for that reason defaults to crossOrigin:'anonymous'. If you are using a local source URL you should use the generic ol.source.XYZ constructor which doesn't default the crossOrigin setting (which is why setting crossOrigin:null above happened to work). And it is perfectly legitimate want to use file protocol for maps, for example on an SD card of a mobile device.

Is java.sql.Timestamp timezone specific?

You can use the below method to store the timestamp in database specific to your desired zone/zone Id.

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Calcutta")) ;
Timestamp timestamp = Timestamp.valueOf(zdt.toLocalDateTime());

A common mistake people do is use LocaleDateTime to get the timestamp of that instant which discards any information specif to your zone even if you try to convert it later. It does not understand the Zone.

Please note Timestamp is of the class java.sql.Timestamp.

How to see if an object is an array without using reflection?

You can create a utility class to check if the class represents any Collection, Map or Array

  public static boolean isCollection(Class<?> rawPropertyType) {
        return Collection.class.isAssignableFrom(rawPropertyType) || 
               Map.class.isAssignableFrom(rawPropertyType) || 
               rawPropertyType.isArray();
 }

How to display image from database using php

Displaying an image from MySql Db.

$db = mysqli_connect("localhost","root","","DbName"); 
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

"unmappable character for encoding" warning in Java

This worked for me -

    <?xml version="1.0" encoding="utf-8" ?>
<project name="test" default="compile">
    <target name="compile">
        <javac srcdir="src" destdir="classes" 
                           encoding="iso-8859-1" debug="true" />
    </target>
</project>

Characters allowed in GET parameter

There are reserved characters, that have a reserved meanings, those are delimiters — :/?#[]@ — and subdelimiters — !$&'()*+,;=

There is also a set of characters called unreserved characters — alphanumerics and -._~ — which are not to be encoded.

That means, that anything that doesn't belong to unreserved characters set is supposed to be %-encoded, when they do not have special meaning (e.g. when passed as a part of GET parameter).

See also RFC3986: Uniform Resource Identifier (URI): Generic Syntax

querying WHERE condition to character length?

I think you want this:

select *
from dbo.table
where DATALENGTH(column_name) = 3

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Ignore mapping one property with Automapper

From Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

It's in one of the comments at his blog.

Declaring a python function with an array parameters and passing an array argument to the function call?

Maybe you want unpack elements of array, I don't know if I got it, but below a example:

def my_func(*args):
    for a in args:
        print a

my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)

automating telnet session using bash scripts

Here is how to use telnet in bash shell/expect

#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed

set ip [lindex $argv 0]
set port [lindex $argv 1]

set timeout 5
spawn telnet $ip $port
expect "'^]'."

Git Pull is Not Possible, Unmerged Files

Say the remote is origin and the branch is master, and say you already have master checked out, might try the following:

git fetch origin
git reset --hard origin/master

This basically just takes the current branch and points it to the HEAD of the remote branch.

WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.

Or you can use the plumbing commands to do essentially the same:

git fetch <remote>
git update-ref refs/heads/<branch> $(git rev-parse <remote>/<branch>)
git reset --hard

EDIT: I'd like to briefly explain why this works.

The .git folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.

A branch is just a named pointer to a given hash. Here's an example set:

$ find .git/refs -type f
.git/refs/tags/v3.8
.git/refs/heads/master
.git/refs/remotes/origin/HEAD
.git/refs/remotes/origin/master

Each of these files contains a hash pointing to a commit:

$ cat .git/refs/remotes/origin/master
d895cb1af15c04c522a25c79cc429076987c089b

These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:

git reset --hard origin/master

git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.

To see this at work go ahead and try out the following:

git checkout -b test-branch
# see current commit and diff by the following
git show HEAD
# now point to another location
git reset --hard <remote>/<branch>
# see the changes again
git show HEAD

web-api POST body object always null

If the any of values of the request's JSON object are not the same type as expected by the service then the [FromBody] argument will be null.

For example, if the age property in the json had a float value:

"age":18.0

but the API service expects it to be an int

"age":18

then student will be null. (No error messages will be sent in the response unless no null reference check).

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.

CORS Access-Control-Allow-Headers wildcard being ignored?

Support for wildcards in the Access-Control-Allow-Headers header was added to the living standard only in May 2016, so it may not be supported by all browsers. On browser which don't implement this yet, it must be an exact match: https://www.w3.org/TR/2014/REC-cors-20140116/#access-control-allow-headers-response-header

If you expect a large number of headers, you can read in the value of the Access-Control-Request-Headers header and echo that value back in the Access-Control-Allow-Headers header.

JQuery show/hide when hover

jquery:

$('div.animalcontent').hide();
$('div').hide();
$('p.animal').bind('mouseover', function() {
    $('div.animalcontent').fadeOut();
    $('#'+$(this).attr('id')+'content').fadeIn();
});  

html:

<p class='animal' id='dog'>dog url</p><div id='dogcontent' class='animalcontent'>Doggiecontent!</div>
<p class='animal' id='cat'>cat url</p><div id='catcontent' class='animalcontent'>Pussiecontent!</div>
<p class='animal' id='snake'>snake url</p><div id='snakecontent'class='animalcontent'>Snakecontent!</div>

-edit-

yeah sure, here you go -- JSFiddle

Delimiters in MySQL

The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.

Why do we have to change the delimiter?

Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.

Current time formatting with Javascript

To work with the base Date class you can look at MDN for its methods (instead of W3Schools due to this reason). There you can find a good description about every method useful to access each single date/time component and informations relative to whether a method is deprecated or not.

Otherwise you can look at Moment.js that is a good library to use for date and time processing. You can use it to manipulate date and time (such as parsing, formatting, i18n, etc.).

Output in a table format in Java's System.out

Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/

An example of the TableBuilder and sample output

Java Regex to Validate Full Name allow only Spaces and Letters

My personal choice is: ^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$, Where:

^\p{L}+ - It should start with 1 or more letters.

[\p{Pd}\p{Zs}'\p{L}]* - It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.

\p{L}+$ - It should finish with 1 or more letters.

|^\p{L}+$ - Or it just should contain 1 or more letters (It is done to support single letter names).

Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.

Is there a vr (vertical rule) in html?

Try it and you will know yourself:

<body>
rokon<br />
rkn <hr style="width: 1px; height: 10px; display: inline; margin-left: 2px; margin-right: 2px;" />rockon<br />
rocks
</body>
</html>

In Spring MVC, how can I set the mime type header when using @ResponseBody

I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization (via the MappingJacksonHttpMessageConverter as you write). As of Spring 3.1, the implementation looks quite neat:

@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, 
    method = RequestMethod.GET
    value = "/foo/bar")
@ResponseBody
public Bar fooBar(){
    return myService.getBar();
}

Comments:

First, the <mvc:annotation-driven /> or the @EnableWebMvc must be added to your application config.

Next, the produces attribute of the @RequestMapping annotation is used to specify the content type of the response. Consequently, it should be set to MediaType.APPLICATION_JSON_VALUE (or "application/json").

Lastly, Jackson must be added so that any serialization and de-serialization between Java and JSON will be handled automatically by Spring (the Jackson dependency is detected by Spring and the MappingJacksonHttpMessageConverter will be under the hood).

Writing/outputting HTML strings unescaped

Complete example for using template functions in RazorEngine (for email generation, for example):

@model SomeModel
@{
    Func<PropertyChangeInfo, object> PropInfo =
        @<tr class="property">
            <td>
                @item.PropertyName                
            </td>
            <td class="value">
                <small class="old">@item.OldValue</small>
                <small class="new">@item.CurrentValue</small>                
            </td>
        </tr>;
}

<body>

@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }

</body>

Synchronous Requests in Node.js

The short answer is: don't. If you want code that reads linearly, use a library like seq. But just don't expect synchronous. You really can't. And that's a good thing.

There's little or nothing that can't be put in a callback. If they depend on common variables, create a closure to contain them. What's the actual task at hand?

You'd want to have a counter, and only call the callback when the data is there:

var waiting = 2;
request( {url: base + u_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    ucomp = split2[1];
    if(--waiting == 0) callback();
});

request( {url: base + v_ext}, function( err, res, body ) {
    var split1 = body.split("\n");
    var split2 = split1[1].split(", ");
    vcomp = split2[1];
    if(--waiting == 0) callback();
});

function callback() {
    // do math here.
}

Update 2018: node.js supports async/await keywords in recent editions, and with libraries that represent asynchronous processes as promises, you can await them. You get linear, sequential flow through your program, and other work can progress while you await. It's pretty well built and worth a try.