Programs & Examples On #Coverstory

What's is the difference between train, validation and test set, in neural networks?

Training set: A set of examples used for learning, that is to fit the parameters [i.e., weights] of the classifier.

Validation set: A set of examples used to tune the parameters [i.e., architecture, not weights] of a classifier, for example to choose the number of hidden units in a neural network.

Test set: A set of examples used only to assess the performance [generalization] of a fully specified classifier.

From ftp://ftp.sas.com/pub/neural/FAQ1.txt section "What are the population, sample, training set, design set, validation"

The error surface will be different for different sets of data from your data set (batch learning). Therefore if you find a very good local minima for your test set data, that may not be a very good point, and may be a very bad point in the surface generated by some other set of data for the same problem. Therefore you need to compute such a model which not only finds a good weight configuration for the training set but also should be able to predict new data (which is not in the training set) with good error. In other words the network should be able to generalize the examples so that it learns the data and does not simply remembers or loads the training set by overfitting the training data.

The validation data set is a set of data for the function you want to learn, which you are not directly using to train the network. You are training the network with a set of data which you call the training data set. If you are using gradient based algorithm to train the network then the error surface and the gradient at some point will completely depend on the training data set thus the training data set is being directly used to adjust the weights. To make sure you don't overfit the network you need to input the validation dataset to the network and check if the error is within some range. Because the validation set is not being using directly to adjust the weights of the netowork, therefore a good error for the validation and also the test set indicates that the network predicts well for the train set examples, also it is expected to perform well when new example are presented to the network which was not used in the training process.

Early stopping is a way to stop training. There are different variations available, the main outline is, both the train and the validation set errors are monitored, the train error decreases at each iteration (backprop and brothers) and at first the validation error decreases. The training is stopped at the moment the validation error starts to rise. The weight configuration at this point indicates a model, which predicts the training data well, as well as the data which is not seen by the network . But because the validation data actually affects the weight configuration indirectly to select the weight configuration. This is where the Test set comes in. This set of data is never used in the training process. Once a model is selected based on the validation set, the test set data is applied on the network model and the error for this set is found. This error is a representative of the error which we can expect from absolutely new data for the same problem.

EDIT:

Also, in the case you do not have enough data for a validation set, you can use crossvalidation to tune the parameters as well as estimate the test error.

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

This is how I solved the problem. In Device Manager you will find the Arduino COM port.

Enter image description here

Go to the Advanced properties of the port

Enter image description here

Set the COM port number to COM1.

Enter image description here

Then replug the USB.

How to gettext() of an element in Selenium Webdriver

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();
System.out.println(Txt);

Concatenate two JSON objects

Just try this, using underscore

var json1 = [{ value1: '1', value2: '2' },{ value1: '3', value2: '4' }];
var json2 = [{ value3: 'a', value4: 'b' },{ value3: 'c', value4: 'd' }];
var resultArray = [];
json1.forEach(function(obj, index){
  resultArray.push(_.extend(obj,  json2[index]));
});

console.log("Result Array", resultArray);

Result

What exactly is a Maven Snapshot and why do we need it?

A "release" is the final build for a version which does not change.

A "snapshot" is a build which can be replaced by another build which has the same name. It implies that the build could change at any time and is still under active development.

You have different artifacts for different builds based on the same code. E.g. you might have one with debugging and one without. One for Java 5.0 and one for Java 6. Generally its simpler to have one build which does everything you need. ;)

Change the bullet color of list

You have to use image

.listStyle {
    list-style: none;
    background: url(bullet.jpg) no-repeat left center;
    padding-left: 40px;
}

php.ini: which one?

Although Pascal's answer was detailed and informative it failed to mention some key information in the assumption that everyone knows how to use phpinfo()

For those that don't:

Navigate to your webservers root folder such as /var/www/

Within this folder create a text file called info.php

Edit the file and type phpinfo()

Navigate to the file such as: http://www.example.com/info.php

Here you will see the php.ini path under Loaded Configuration File:

phpinfo

Make sure you delete info.php when you are done.

Python integer incrementing with ++

The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++ is the next method of iterators.

If input field is empty, disable submit button

An easy way to do:

function toggleButton(ref,bttnID){
    document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}


<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >

How to generate unique ID with node.js

More easy and without addition modules

Math.random().toString(26).slice(2)

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

try adding the permission outside the application tag of the manifest in addition to the above mentioned answers of changing localhost to 10.0.2.2:8080

How can I issue a single command from the command line through sql plus?

I'm able to run an SQL query by piping it to SQL*Plus:

@echo select count(*) from table; | sqlplus username/password@database

Give

@echo execute some_procedure | sqlplus username/password@databasename

a try.

Make the image go behind the text and keep it in center using CSS

You can position both the image and the text with position:absolute or position:relative. Then the z-index property will work. E.g.

#sometext {
    position:absolute;
    z-index:1;

}
image.center {
    position:absolute;
    z-index:0;
}

Use whatever method you like to center it.

Another option/hack is to make the image the background, either on the whole page or just within the text box.

How to get JSON object from Razor Model object in javascript

You could use the following:

var json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

This would output the following (without seeing your model I've only included one field):

<script>
    var json = [{"State":"a state"}];   
</script>

Working Fiddle

AspNetCore

AspNetCore uses Json.Serialize intead of Json.Encode

var json = @Html.Raw(Json.Serialize(@Model.CollegeInformationlist));

MVC 5/6

You can use Newtonsoft for this:

    @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, 
Newtonsoft.Json.Formatting.Indented))

This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.

How do you parse and process HTML/XML in PHP?

Just use DOMDocument->loadHTML() and be done with it. libxml's HTML parsing algorithm is quite good and fast, and contrary to popular belief, does not choke on malformed HTML.

Open fancybox from function

What you need is:

$.fancybox.open({ .... });

See the "API methods" section at the bottom of here:

http://fancyapps.com/fancybox/

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think that more accurate is this syntax:

SELECT CONVERT(CHAR(10), GETDATE(), 103)

I add SELECT and GETDATE() for instant testing purposes :)

MySQL JOIN with LIMIT 1 on joined table

Assuming you want product with MIN()imial value in sort column, it would look something like this.

SELECT 
  c.id, c.title, p.id AS product_id, p.title
FROM 
  categories AS c
INNER JOIN (
  SELECT
    p.id, p.category_id, p.title
  FROM
    products AS p
  CROSS JOIN (
    SELECT p.category_id, MIN(sort) AS sort
    FROM products
    GROUP BY category_id
  ) AS sq USING (category_id)
) AS p ON c.id = p.category_id

findViewById in Fragment

Try this it works for me

public class TestClass extends Fragment {
    private ImageView imageView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.testclassfragment, container, false);
        findViews(view);
        return view;
    }

    private void findViews(View view) {
        imageView = (ImageView) view.findViewById(R.id.my_image);
    }
}

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

I encountered another problem that returns the same error.

Single quote issue

I used a json string with single quotes :

{
    'property': 1
}

But json.loads accepts only double quotes for json properties :

{
    "property": 1
}

Final comma issue

json.loads doesn't accept a final comma:

{
  "property": "text", 
  "property2": "text2",
}

Solution: ast to solve single quote and final comma issues

You can use ast (part of standard library for both Python 2 and 3) for this processing. Here is an example :

import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json

# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}

# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}

Using ast will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It's a pretty good and safely alternative of eval() function for literal structures.

Python documentation warned us of using large/complex string :

Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

json.dumps with single quotes

To use json.dumps with single quotes easily you can use this code:

import ast
import json

data = json.dumps(ast.literal_eval(json_data_single_quote))

ast documentation

ast Python 3 doc

ast Python 2 doc

Tool

If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.

I hope it helps.

SQL keys, MUL vs PRI vs UNI

For Mul, this was also helpful documentation to me - http://grokbase.com/t/mysql/mysql/9987k2ew41/key-field-mul-newbie-question

"MUL means that the key allows multiple rows to have the same value. That is, it's not a UNIque key."

For example, let's say you have two models, Post and Comment. Post has a has_many relationship with Comment. It would make sense then for the Comment table to have a MUL key(Post id) because many comments can be attributed to the same Post.

Correct way of using log4net (logger naming)

My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

Shortcut to comment out a block of code with sublime text

Just an important note. If you have HTML comment and your uncomment doesn't work
(Maybe it's a PHP file), so don't mark all the comment but just put your cursor at the end or at the beginning of the comment (before ) and try again (Ctrl+/).

Removing whitespace from strings in Java

mysz = mysz.replace(" ","");

First with space, second without space.

Then it is done.

Detect if user is scrolling

Use an interval to check

You can setup an interval to keep checking if the user has scrolled then do something accordingly.

Borrowing from the great John Resig in his article.

Example:

    let didScroll = false;

    window.onscroll = () => didScroll = true;

    setInterval(() => {
        if ( didScroll ) {
            didScroll = false;
            console.log('Someone scrolled me!')
        }
    }, 250);

See live example

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

T-SQL CASE Clause: How to specify WHEN NULL

You can use IsNull function

select 
    isnull(rtrim(ltrim([FirstName]))+' ','') +
    isnull(rtrim(ltrim([SecondName]))+' ','') +
    isnull(rtrim(ltrim([Surname]))+' ','') +
    isnull(rtrim(ltrim([SecondSurname])),'')
from TableDat

if one column is null you would get an empty char

Compatible with Microsoft SQL Server 2008+

How to check whether a given string is valid JSON in Java

I have found a very simple solution for it.

Please first install this library net.sf.json-lib for it.

    import net.sf.json.JSONException;

    import net.sf.json.JSONSerializer;

    private static boolean isValidJson(String jsonStr) {
        boolean isValid = false;
        try {
            JSONSerializer.toJSON(jsonStr);
            isValid = true;
        } catch (JSONException je) {
            isValid = false;
        }
        return isValid;
    }

    public static void testJson() {
        String vjson = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        String ivjson = "{\"employees\": [{ \"firstName\":\"John\" ,, \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        System.out.println(""+isValidJson(vjson)); // true
        System.out.println(""+isValidJson(ivjson)); // false
    }

Done. Enjoy

How to set timeout for a line of c# code

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

Anaconda vs. miniconda

Anaconda or Miniconda?

Choose Anaconda if you:

  1. Are new to conda or Python.

  2. Like the convenience of having Python and over 1,500 scientific packages automatically installed at once.

  3. Have the time and disk space---a few minutes and 3 GB.

  4. Do not want to individually install each of the packages you want to use.

Choose Miniconda if you:

  1. Do not mind installing each of the packages you want to use individually.

  2. Do not have time or disk space to install over 1,500 packages at once.

  3. Want fast access to Python and the conda commands and you wish to sort out the other programs later.

Source

CSS force new line

Use <br /> OR <br> -

<li>Post by<br /><a>Author</a></li>

OR

<li>Post by<br><a>Author</a></li>

or

make the a element display:block;

<li>Post by <a style="display:block;">Author</a></li>

Try

Can you do a partial checkout with Subversion?

Not in any especially useful way, no. You can check out subtrees (as in Bobby Jack's suggestion), but then you lose the ability to update/commit them atomically; to do that, they need to be placed under their common parent, and as soon as you check out the common parent, you'll download everything under that parent. Non-recursive isn't a good option, because you want updates and commits to be recursive.

Get unique values from a list in python

def setlist(lst=[]):
   return list(set(lst))

How do I center text vertically and horizontally in Flutter?

Text element inside Center of SizedBox work much better way, below Sample code

Widget build(BuildContext context) {
    return RawMaterialButton(
      fillColor: Colors.green,
      splashColor: Colors.greenAccent,
      shape: new CircleBorder(),
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            SizedBox(
              width: 100.0,
              height: 100.0,
              child: Center(
                child: Text(
                widget.buttonText,
                maxLines: 1,
                style: TextStyle(color: Colors.white)
              ),
              )
          )]
        ),
    ),
  onPressed: widget.onPressed
);
}

Enjoy coding ?

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Where is Ubuntu storing installed programs?

They are usually stored in the following folders:

/bin/
/usr/bin/
/sbin/
/usr/sbin/

If you're not sure, use the which command:

~$ which firefox
/usr/bin/firefox

Execute external program

import java.io.*;

public class Code {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
    Process process = builder.start();

    StringBuilder out = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line = null;
      while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append("\n");
      }
      System.out.println(out);
    }
  }
}

Try online

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Run PHP Task Asynchronously

If you don't want the full blown ActiveMQ, I recommend to consider RabbitMQ. RabbitMQ is lightweight messaging that uses the AMQP standard.

I recommend to also look into php-amqplib - a popular AMQP client library to access AMQP based message brokers.

How to subtract a day from a date?

If your Python datetime object is timezone-aware than you should be careful to avoid errors around DST transitions (or changes in UTC offset for other reasons):

from datetime import datetime, timedelta
from tzlocal import get_localzone # pip install tzlocal

DAY = timedelta(1)
local_tz = get_localzone()   # get local timezone
now = datetime.now(local_tz) # get timezone-aware datetime object
day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ
naive = now.replace(tzinfo=None) - DAY # same time
yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ

In general, day_ago and yesterday may differ if UTC offset for the local timezone has changed in the last day.

For example, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 A.M. in America/Los_Angeles timezone therefore if:

import pytz # pip install pytz

local_tz = pytz.timezone('America/Los_Angeles')
now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None)
# 2014-11-02 10:00:00 PST-0800

then day_ago and yesterday differ:

  • day_ago is exactly 24 hours ago (relative to now) but at 11 am, not at 10 am as now
  • yesterday is yesterday at 10 am but it is 25 hours ago (relative to now), not 24 hours.

pendulum module handles it automatically:

>>> import pendulum  # $ pip install pendulum

>>> now = pendulum.create(2014, 11, 2, 10, tz='America/Los_Angeles')
>>> day_ago = now.subtract(hours=24)  # exactly 24 hours ago
>>> yesterday = now.subtract(days=1)  # yesterday at 10 am but it is 25 hours ago

>>> (now - day_ago).in_hours()
24
>>> (now - yesterday).in_hours()
25

>>> now
<Pendulum [2014-11-02T10:00:00-08:00]>
>>> day_ago
<Pendulum [2014-11-01T11:00:00-07:00]>
>>> yesterday
<Pendulum [2014-11-01T10:00:00-07:00]>

Table Height 100% inside Div element

Not possible without assigning height value to div.

Add this

body, html{height:100%}
div{height:100%}
table{background:green; width:450px}    ?

DEMO

Using continue in a switch statement

It's syntactically correct and stylistically okay.

Good style requires every case: statement should end with one of the following:

 break;
 continue;
 return (x);
 exit (x);
 throw (x);
 //fallthrough

Additionally, following case (x): immediately with

 case (y):
 default:

is permissible - bundling several cases that have exactly the same effect.

Anything else is suspected to be a mistake, just like if(a=4){...} Of course you need enclosing loop (while, for, do...while) for continue to work. It won't loop back to case() alone. But a construct like:

while(record = getNewRecord())
{
    switch(record.type)
    {
        case RECORD_TYPE_...;
            ...
        break;
        default: //unknown type
            continue; //skip processing this record altogether.
    }
    //...more processing...
}

...is okay.

Split comma-separated input box values into array in jquery, and loop through it

var array = $('#searchKeywords').val().split(",");

then

$.each(array,function(i){
   alert(array[i]);
});

OR

for (i=0;i<array.length;i++){
     alert(array[i]);
}

Converting File to MultiPartFile

MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;

Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
    content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
                     originalFileName, contentType, content);

Remove Identity from a column in a table

I had the same requirement, and you could try this way, which I personally recommend you, please manually design your table and generate the script, and what I did below was renaming the old table and also its constraint for backup.

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION

SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.SI_Provider_Profile
    DROP CONSTRAINT DF_SI_Provider_Profile_SIdtDateTimeStamp
GO
ALTER TABLE dbo.SI_Provider_Profile
    DROP CONSTRAINT DF_SI_Provider_Profile_SIbHotelPreLoaded
GO
CREATE TABLE dbo.Tmp_SI_Provider_Profile
    (
    SI_lProvider_Profile_ID int NOT NULL,
    SI_lSerko_Integrator_Token_ID int NOT NULL,
    SI_sSerko_Integrator_Provider varchar(50) NOT NULL,
    SI_sSerko_Integrator_Profile varchar(50) NOT NULL,
    SI_dtDate_Time_Stamp datetime NOT NULL,
    SI_lProvider_ID int NULL,
    SI_sDisplay_Name varchar(10) NULL,
    SI_lPurchased_From int NULL,
    SI_sProvider_UniqueID varchar(255) NULL,
    SI_bHotel_Pre_Loaded bit NOT NULL,
    SI_sSiteName varchar(255) NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile ADD CONSTRAINT
    DF_SI_Provider_Profile_SIdtDateTimeStamp DEFAULT (getdate()) FOR SI_dtDate_Time_Stamp
GO
ALTER TABLE dbo.Tmp_SI_Provider_Profile ADD CONSTRAINT
    DF_SI_Provider_Profile_SIbHotelPreLoaded DEFAULT ((0)) FOR SI_bHotel_Pre_Loaded
GO
IF EXISTS(SELECT * FROM dbo.SI_Provider_Profile)
        EXEC('INSERT INTO dbo.Tmp_SI_Provider_Profile (SI_lProvider_Profile_ID, SI_lSerko_Integrator_Token_ID, SI_sSerko_Integrator_Provider, SI_sSerko_Integrator_Profile, SI_dtDate_Time_Stamp, SI_lProvider_ID, SI_sDisplay_Name, SI_lPurchased_From, SI_sProvider_UniqueID, SI_bHotel_Pre_Loaded, SI_sSiteName)
        SELECT SI_lProvider_Profile_ID, SI_lSerko_Integrator_Token_ID, SI_sSerko_Integrator_Provider, SI_sSerko_Integrator_Profile, SI_dtDate_Time_Stamp, SI_lProvider_ID, SI_sDisplay_Name, SI_lPurchased_From, SI_sProvider_UniqueID, SI_bHotel_Pre_Loaded, SI_sSiteName FROM dbo.SI_Provider_Profile WITH (HOLDLOCK TABLOCKX)')
GO

-- Rename the primary key constraint or unique key In SQL Server constraints such as primary keys or foreign keys are objects in their own right, even though they are dependent upon the "containing" table.
EXEC sp_rename 'dbo.SI_Provider_Profile.PK_SI_Provider_Profile', 'PK_SI_Provider_Profile_Old';
GO
-- backup old table in case of 
EXECUTE sp_rename N'dbo.SI_Provider_Profile', N'SI_Provider_Profile_Old', 'OBJECT'
GO

EXECUTE sp_rename N'dbo.Tmp_SI_Provider_Profile', N'SI_Provider_Profile', 'OBJECT'
GO

ALTER TABLE dbo.SI_Provider_Profile ADD CONSTRAINT
    PK_SI_Provider_Profile PRIMARY KEY NONCLUSTERED 
    (
    SI_lProvider_Profile_ID
    ) WITH( PAD_INDEX = OFF, FILLFACTOR = 90, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
COMMIT TRANSACTION

How do I replace a character at a particular index in JavaScript?

The methods on here are complicated. I would do it this way:

var myString = "this is my string";
myString = myString.replace(myString.charAt(number goes here), "insert replacement here");

This is as simple as it gets.

Select the top N values by group

I prefer @Ista solution, cause needs no extra package and is simple.
A modification of the data.table solution also solve my problem, and is more general.
My data.frame is

> str(df)
'data.frame':   579 obs. of  11 variables:
 $ trees     : num  2000 5000 1000 2000 1000 1000 2000 5000 5000 1000 ...
 $ interDepth: num  2 3 5 2 3 4 4 2 3 5 ...
 $ minObs    : num  6 4 1 4 10 6 10 10 6 6 ...
 $ shrinkage : num  0.01 0.001 0.01 0.005 0.01 0.01 0.001 0.005 0.005 0.001     ...
 $ G1        : num  0 2 2 2 2 2 8 8 8 8 ...
 $ G2        : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ qx        : num  0.44 0.43 0.419 0.439 0.43 ...
 $ efet      : num  43.1 40.6 39.9 39.2 38.6 ...
 $ prec      : num  0.606 0.593 0.587 0.582 0.574 0.578 0.576 0.579 0.588 0.585 ...
 $ sens      : num  0.575 0.57 0.573 0.575 0.587 0.574 0.576 0.566 0.542 0.545 ...
 $ acu       : num  0.631 0.645 0.647 0.648 0.655 0.647 0.619 0.611 0.591 0.594 ...

The data.table solution needs order on i to do the job:

> require(data.table)
> dt1 <- data.table(df)
> dt2 = dt1[order(-efet, G1, G2), head(.SD, 3), by = .(G1, G2)]
> dt2
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 5:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 6:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 7:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
 8:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
 9:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
10:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
11:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
12:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
13:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635
14:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621  

By some reason, it does not order the way pointed (probably because ordering by the groups). So, another ordering is done.

> dt2[order(G1, G2)]
    G1    G2 trees interDepth minObs shrinkage        qx   efet  prec  sens   acu
 1:  0 FALSE  2000          2      6     0.010 0.4395953 43.066 0.606 0.575 0.631
 2:  0 FALSE  2000          5      1     0.005 0.4294718 37.554 0.583 0.548 0.607
 3:  0 FALSE  5000          2      6     0.005 0.4395753 36.981 0.575 0.559 0.616
 4:  0  TRUE  2000          6      4     0.010 0.3192862  9.779 0.460 0.433 0.621
 5:  2 FALSE  5000          3      4     0.001 0.4296346 40.624 0.593 0.570 0.645
 6:  2 FALSE  1000          5      1     0.010 0.4186802 39.915 0.587 0.573 0.647
 7:  2 FALSE  2000          2      4     0.005 0.4390503 39.164 0.582 0.575 0.648
 8:  2  TRUE  5000          3      4     0.001 0.3812878 21.057 0.510 0.479 0.615
 9:  2  TRUE  2000          3     10     0.005 0.3790536 20.127 0.507 0.470 0.608
10:  2  TRUE  1000          5      4     0.001 0.3690911 18.981 0.500 0.475 0.611
11:  8 FALSE  2000          4     10     0.001 0.4511349 38.240 0.576 0.576 0.619
12:  8 FALSE  5000          2     10     0.005 0.4469665 38.064 0.579 0.566 0.611
13:  8 FALSE  5000          3      6     0.005 0.4426952 37.888 0.588 0.542 0.591
14:  8  TRUE  5000          6     10     0.010 0.2865042 16.870 0.497 0.435 0.635

Complete list of reasons why a css file might not be working

I had a problem like this! I was able to fix it following

Step 1>>from Abraar Arique post, I went into the console>> Went under Style Editor and found Firefox wasn't loading the updated copy of my css file.

I cleared all history and reload the page then my problem was fixed.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Let’s assume, your old app.module.ts may look similar to this :

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }

Now import FormsModule in your app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})

export class AppModule { }

http://jsconfig.com/solution-cant-bind-ngmodel-since-isnt-known-property-input/

What's the difference between echo, print, and print_r in PHP?

print_r() is used for printing the array in human readable format.

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

How can I convert a date to GMT?

Based on the accepted answer and the second highest scoring answer both are not perfect according to the comment so I mixed both to get something perfect:

_x000D_
_x000D_
var date = new Date(); //Current timestamp_x000D_
date = date.toGMTString(); _x000D_
//Based on the time zone where the date was created_x000D_
console.log(date);_x000D_
_x000D_
/*based on the comment getTimezoneOffset returns an offset based _x000D_
on the date it is called on, and the time zone of the computer the code is_x000D_
 running on. It does not supply the offset passed in when constructing a _x000D_
date from a string. */_x000D_
_x000D_
date = new Date(date); //will convert to present timestamp offset_x000D_
date = new Date(date.getTime() + (date.getTimezoneOffset() * 60 * 1000)); _x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

Fragment MyFragment not attached to Activity

An old post, but I was surprised about the most up-voted answer.

The proper solution for this should be to cancel the asynctask in onStop (or wherever appropriate in your fragment). This way you don't introduce a memory leak (an asynctask keeping a reference to your destroyed fragment) and you have better control of what is going on in your fragment.

@Override
public void onStop() {
    super.onStop();
    mYourAsyncTask.cancel(true);
}

The type is defined in an assembly that is not referenced, how to find the cause?

It just happened to me that different projects were referencing different copies of the same dll. I made sure all referenced the same file on disk, and the error disappeared as I expected.

phpmyadmin "Not Found" after install on Apache, Ubuntu

This issue was resolved thanks to this guide: https://help.ubuntu.com/community/ApacheMySQLPHP#Troubleshooting_Phpmyadmin_.26_mysql-workbench by adding

Include /etc/phpmyadmin/apache.conf

...to the /etc/apache2/apache2.conf file and restarting the service.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Have been trying every variation on João's solution to get an IN List query to work with Tornado's mysql wrapper, and was still getting the accursed "TypeError: not enough arguments for format string" error. Turns out adding "*" to the list var "*args" did the trick.

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
db.query(sql, *args)

Asp.net Validation of viewstate MAC failed

On multi-server environment, this error likely occurs when session expires and another instance of an application is resorted with same session id and machine key but on a different server. At first, each server produce its own machine key which later is associated with a single instance of an application. When session expires and current server is busy, the application is redirected like, via load balancer to a more operational server. In my case I run same app from multiple servers, the error message:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm

Defining the machine code under in web.config have solve the problem. But instead of using 3rd party sites for code generation which might be corrupted, please run this from your command shell: Based on microsoft solution 1a, https://support.microsoft.com/en-us/kb/2915218#AppendixA

# Generates a <machineKey> element that can be copied + pasted into a Web.config file.
function Generate-MachineKey {
  [CmdletBinding()]
  param (
    [ValidateSet("AES", "DES", "3DES")]
    [string]$decryptionAlgorithm = 'AES',
    [ValidateSet("MD5", "SHA1", "HMACSHA256", "HMACSHA384", "HMACSHA512")]
    [string]$validationAlgorithm = 'HMACSHA256'
  )
  process {
    function BinaryToHex {
        [CmdLetBinding()]
        param($bytes)
        process {
            $builder = new-object System.Text.StringBuilder
            foreach ($b in $bytes) {
              $builder = $builder.AppendFormat([System.Globalization.CultureInfo]::InvariantCulture, "{0:X2}", $b)
            }
            $builder
        }
    }
    switch ($decryptionAlgorithm) {
      "AES" { $decryptionObject = new-object System.Security.Cryptography.AesCryptoServiceProvider }
      "DES" { $decryptionObject = new-object System.Security.Cryptography.DESCryptoServiceProvider }
      "3DES" { $decryptionObject = new-object System.Security.Cryptography.TripleDESCryptoServiceProvider }
    }
    $decryptionObject.GenerateKey()
    $decryptionKey = BinaryToHex($decryptionObject.Key)
    $decryptionObject.Dispose()
    switch ($validationAlgorithm) {
      "MD5" { $validationObject = new-object System.Security.Cryptography.HMACMD5 }
      "SHA1" { $validationObject = new-object System.Security.Cryptography.HMACSHA1 }
      "HMACSHA256" { $validationObject = new-object System.Security.Cryptography.HMACSHA256 }
      "HMACSHA385" { $validationObject = new-object System.Security.Cryptography.HMACSHA384 }
      "HMACSHA512" { $validationObject = new-object System.Security.Cryptography.HMACSHA512 }
    }
    $validationKey = BinaryToHex($validationObject.Key)
    $validationObject.Dispose()
    [string]::Format([System.Globalization.CultureInfo]::InvariantCulture,
      "<machineKey decryption=`"{0}`" decryptionKey=`"{1}`" validation=`"{2}`" validationKey=`"{3}`" />",
      $decryptionAlgorithm.ToUpperInvariant(), $decryptionKey,
      $validationAlgorithm.ToUpperInvariant(), $validationKey)
  }
}

Then:

For ASP.NET 4.0

Generate-MachineKey

Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="HMACSHA256" validationKey="..." />

For ASP.NET 2.0 and 3.5

Generate-MachineKey -validation sha1

Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="SHA1" validationKey="..." />

After installing with pip, "jupyter: command not found"

I'm on Mojave with Python 2.7 and after pip install --user jupyter the binary went here:

/Users/me/Library/Python//2.7/bin/jupyter

Difference between npx and npm?

Introducing npx: an npm package runner

NPM - Manages packages but doesn't make life easy executing any.
NPX - A tool for executing Node packages.

NPX comes bundled with NPM version 5.2+

NPM by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json file.

When executables are installed via NPM packages, NPM links to them:

  1. local installs have "links" created at ./node_modules/.bin/ directory.
  2. global installs have "links" created from the global bin/ directory (e.g. /usr/local/bin) on Linux or at %AppData%/npm on Windows.

Documentation you should read


NPM:

One might install a package locally on a certain project:

npm install some-package

Now let's say you want NodeJS to execute that package from the command line:

$ some-package

The above will fail. Only globally installed packages can be executed by typing their name only.

To fix this, and have it run, you must type the local path:

$ ./node_modules/.bin/some-package

You can technically run a locally installed package by editing your packages.json file and adding that package in the scripts section:

{
  "name": "whatever",
  "version": "1.0.0",
  "scripts": {
    "some-package": "some-package"
  }
}

Then run the script using npm run-script (or npm run):

npm run some-package

NPX:

npx will check whether <command> exists in $PATH, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package all you need to do is type:

npx some-package

Another major advantage of npx is the ability to execute a package which wasn't previously installed:

$ npx create-react-app my-app

The above example will generate a react app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.


Use-Case Example:

npx command may be helpful in the script section of a package.json file, when it is unwanted to define a dependency which might not be commonly used or any other reason:

"scripts": {
    "start": "npx [email protected]",
    "serve": "npx http-server"
}

Call with: npm run serve


Related questions:

  1. How to use package installed locally in node_modules?
  2. NPM: how to source ./node_modules/.bin folder?
  3. How do you run a js file using npm scripts?

How to sum a list of integers with java streams?

class Pojo{
    int num;

    public Pojo(int num) {
        super();
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}

List<Pojo> list = new ArrayList<Pojo>();
            list.add(new Pojo(1));
            list.add(new Pojo(5));
            list.add(new Pojo(3));
            list.add(new Pojo(4));
            list.add(new Pojo(5));

            int totalSum = list.stream().mapToInt(pojo -> pojo.getNum()).sum();
            System.out.println(totalSum);

PUT vs. POST in REST

Summary:

Create:

Can be performed with both PUT or POST in the following way:

PUT

Creates THE new resource with newResourceId as the identifier, under the /resources URI, or collection.

PUT /resources/<newResourceId> HTTP/1.1 

POST

Creates A new resource under the /resources URI, or collection. Usually the identifier is returned by the server.

POST /resources HTTP/1.1

Update:

Can only be performed with PUT in the following way:

PUT

Updates the resource with existingResourceId as the identifier, under the /resources URI, or collection.

PUT /resources/<existingResourceId> HTTP/1.1

Explanation:

When dealing with REST and URI as general, you have generic on the left and specific on the right. The generics are usually called collections and the more specific items can be called resource. Note that a resource can contain a collection.

Examples:

<-- generic -- specific -->

URI: website.com/users/john
website.com  - whole site
users        - collection of users
john         - item of the collection, or a resource

URI:website.com/users/john/posts/23
website.com  - whole site
users        - collection of users
john         - item of the collection, or a resource
posts        - collection of posts from john
23           - post from john with identifier 23, also a resource

When you use POST you are always refering to a collection, so whenever you say:

POST /users HTTP/1.1

you are posting a new user to the users collection.

If you go on and try something like this:

POST /users/john HTTP/1.1

it will work, but semantically you are saying that you want to add a resource to the john collection under the users collection.

Once you are using PUT you are refering to a resource or single item, possibly inside a collection. So when you say:

PUT /users/john HTTP/1.1

you are telling to the server update, or create if it doesn't exist, the john resource under the users collection.

Spec:

Let me highlight some important parts of the spec:

POST

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line

Hence, creates a new resource on a collection.

PUT

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI."

Hence, create or update based on existence of the resource.

Reference:

What is %2C in a URL?

In Firefox there is Ctrl+Shift+K for the Web console, then you type

;decodeURIComponent("%2c")
  • mind the semicolon in the beginning
  • if you Copy&Paste, you should first enable it (the console will warn you)

and you get the answer:

","

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

In my case - I had to perform below operations:

  1. Move context.xml file from src/java/package to the resource directory (IntelliJ IDE)
  2. Clean target directory.

How can I calculate the number of years between two dates?

No for-each loop, no extra jQuery plugin needed... Just call the below function.. Got from Difference between two dates in years

        function dateDiffInYears(dateold, datenew) {
            var ynew = datenew.getFullYear();
            var mnew = datenew.getMonth();
            var dnew = datenew.getDate();
            var yold = dateold.getFullYear();
            var mold = dateold.getMonth();
            var dold = dateold.getDate();
            var diff = ynew - yold;
            if (mold > mnew) diff--;
            else {
                if (mold == mnew) {
                    if (dold > dnew) diff--;
                }
            }
            return diff;
        }

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.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
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

You can use auto in data placement like data-placement="auto left". It will automatic adjust according to your screen size and default placement will be left.

How to change identity column values programmatically?

Very nice question, first we need to on the IDENTITY_INSERT for the specific table, after that run the insert query (Must specify the column name).

Note: After edit the the identity column, don't forget to off the IDENTITY_INSERT. If you not done, you cannot able to Edit the identity column for any other table.

SET IDENTITY_INSERT Emp_tb_gb_Menu ON
     INSERT Emp_tb_gb_Menu(MenuID) VALUES (68)
SET IDENTITY_INSERT Emp_tb_gb_Menu OFF

http://allinworld99.blogspot.com/2016/07/how-to-edit-identity-field-in-sql.html

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Decoding base64 to UTF8 String

Below is current most voted answer by @brandonscript

function b64DecodeUnicode(str) {
    // Going backwards: from bytestream, to percent-encoding, to original string.
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

Above code can work, but it's very slow. If your input is a very large base64 string, for example 30,000 chars for a base64 html document. It will need lots of computation.

Here is my answer, use built-in TextDecoder, nearly 10x faster than above code for large input.

function decodeBase64(base64) {
    const text = atob(base64);
    const length = text.length;
    const bytes = new Uint8Array(length);
    for (let i = 0; i < length; i++) {
        bytes[i] = text.charCodeAt(i);
    }
    const decoder = new TextDecoder(); // default is utf-8
    return decoder.decode(bytes);
}

The total number of locks exceeds the lock table size

From the MySQL documentation (that you already have read as I see):

1206 (ER_LOCK_TABLE_FULL)

The total number of locks exceeds the lock table size. To avoid this error, increase the value of innodb_buffer_pool_size. Within an individual application, a workaround may be to break a large operation into smaller pieces. For example, if the error occurs for a large INSERT, perform several smaller INSERT operations.

If increasing innodb_buffer_pool_size doesnt help, then just follow the indication on the bolded part and split up your INSERT into 3. Skip the UNIONs and make 3 INSERTs, each with a JOIN to the topThreetransit table.

Get index of selected option with jQuery

selectedIndex is a JavaScript Select Property. For jQuery you can use this code:

jQuery(document).ready(function($) {
  $("#dropDownMenuKategorie").change(function() {
    // I personally prefer using console.log(), but if you want you can still go with the alert().
    console.log($(this).children('option:selected').index());
  });
});

startsWith() and endsWith() functions in PHP

function startsWith($haystack, $needle, $case = true) {
    if ($case) {
        return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
    }
    return (strcasecmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
}

function endsWith($haystack, $needle, $case = true) {
    if ($case) {
        return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
    }
    return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
}

Credit To:

Check if a string ends with another string

Check if a string begins with another string

Apache Cordova - uninstall globally

Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How can I make a thumbnail <img> show a full size image when clicked?

That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).

Send HTTP GET request with header

You do it exactly as you showed with this line:

get.setHeader("Content-Type", "application/x-zip");

So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

I'm running SQL Developer 17.2.0.188 build 188.1159 which does indeed contain data modeling capability. I just created a relational model diagram via the menu: File->Data Modeler->Import->Data Dictionary....

I also have the stand-alone Data Modeler, which does the same thing.

As the Data Modeler tutorial states:

Figure 4: Relational model and diagram for HR

The diagram you’ve generated is not an ERD. Logical models are higher abstractions. An ERD represents entities and their attributes and relations, whereas a relational or physical model represents tables, columns, and foreign keys."

How to get MAC address of client using PHP?

First you check your user agent OS Linux or windows or another. Then Your OS Windows Then this code use:

public function win_os(){ 
    ob_start();
    system('ipconfig-a');
    $mycom=ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    $pmac = strpos($mycom, $findme); // Find the position of Physical text
    $mac=substr($mycom,($pmac+36),17); // Get Physical Address

    return $mac;
   }

And your OS Linux Ubuntu or Linux then this code use:

public function unix_os(){
    ob_start();
    system('ifconfig -a');
    $mycom = ob_get_contents(); // Capture the output into a variable
    ob_clean(); // Clean (erase) the output buffer
    $findme = "Physical";
    //Find the position of Physical text 
    $pmac = strpos($mycom, $findme); 
    $mac = substr($mycom, ($pmac + 37), 18);

    return $mac;
    }

This code may be work OS X.

pandas read_csv and filter columns with usecols

import csv first and use csv.DictReader its easy to process...

Create array of regex matches

In Java 9, you can now use Matcher#results() to get a Stream<MatchResult> which you can use to get a list/array of matches.

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.

OK then. These two are the ones I used:

Komodo Edit

Aptana Studio 3

and then there is always Eclipse.

*UPDATE 20 March 2013 *

Well, Sublime Text 2 is the one to heavily consider. Heavily.

How do I pass a URL with multiple parameters into a URL?

Rather than html encoding your URL parameter, you need to URL encode it:

http://www.facebook.com/sharer.php?&t=FOOBAR&u=http%3A%2F%2Fwww.foobar.com%2F%3Ffirst%3D12%26sec%3D25%26position%3D

You can do this easily in most languages - in javascript:

var encodedParam = encodeURIComponent('www.foobar.com/?first=1&second=12&third=5');
// encodedParam = 'http%3A%2F%2Fwww.foobar.com%2F%3Ffirst%3D12%26sec%3D25%26position%3D'

(there are equivalent methods in other languages too)

How do I get a reference to the app delegate in Swift?

Here's an extension for UIApplicationDelegate that avoids hardcoding the AppDelegate class name:

extension UIApplicationDelegate {

    static var shared: Self {    
        return UIApplication.shared.delegate! as! Self
    }
}

// use like this:
let appDelegate = MyAppDelegate.shared // will be of type MyAppDelegate

C++11 reverse range-based for-loop

This should work in C++11 without boost:

namespace std {
template<class T>
T begin(std::pair<T, T> p)
{
    return p.first;
}
template<class T>
T end(std::pair<T, T> p)
{
    return p.second;
}
}

template<class Iterator>
std::reverse_iterator<Iterator> make_reverse_iterator(Iterator it)
{
    return std::reverse_iterator<Iterator>(it);
}

template<class Range>
std::pair<std::reverse_iterator<decltype(begin(std::declval<Range>()))>, std::reverse_iterator<decltype(begin(std::declval<Range>()))>> make_reverse_range(Range&& r)
{
    return std::make_pair(make_reverse_iterator(begin(r)), make_reverse_iterator(end(r)));
}

for(auto x: make_reverse_range(r))
{
    ...
}

How to clear Tkinter Canvas?

Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.

Using NSLog for debugging

Why do you have the brackets around digit? It should be

NSLog("%@", digit);

You're also missing an = in the first line...

NSString *digit = [[sender titlelabel] text];

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

invalid new-expression of abstract class type

If you use C++11, you can use the specifier "override", and it will give you a compiler error if your aren't correctly overriding an abstract method. You probably have a method that doesn't match exactly with an abstract method in the base class, so your aren't actually overriding it.

http://en.cppreference.com/w/cpp/language/override

How to make vim paste from (and copy to) system's clipboard?

I used the answer of NM Pennypacker and installed vim via homebrew for an early 2011 MacBook Pro:

brew install vim

Now I can also use the "* register to copy and paste text within vim. I even didn't have to change something within my ~/.vimrc file or the $PATH. Homebrew added symlinks in /usr/local/bin, e.g. vim -> ../Cellar/vim/8.1.2350/bin/vim.

The alternative, which worked before, is to copy some lines of text within vim by marking it with the mouse and using copy and paste (cmd + c, cmd + v) on a mac. This option only works if the text you want to copy and paste is less in size than the window size of vim. If you want to copy all text within vim by marking the whole window or using cmd + a, this will copy other parts of the console, written before starting vim, which is very annoying.

So, I am happy having found the new method using the clippboard register.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

overlay a smaller image on a larger image python OpenCv

Based on fireant's excellent answer above, here is the alpha blending but a bit more human legible. You may need to swap 1.0-alpha and alpha depending on which direction you're merging (mine is swapped from fireant's answer).

o* == s_img.* b* == b_img.*

for c in range(0,3):
    alpha = s_img[oy:oy+height, ox:ox+width, 3] / 255.0
    color = s_img[oy:oy+height, ox:ox+width, c] * (1.0-alpha)
    beta  = l_img[by:by+height, bx:bx+width, c] * (alpha)

    l_img[by:by+height, bx:bx+width, c] = color + beta

How to set column widths to a jQuery datatable?

by using css we can easily add width to the column.

here im adding first column width to 300px on header (thead)

_x000D_
_x000D_
::ng-deep  table thead tr:last-child th:nth-child(1) {_x000D_
    width: 300px!important;_x000D_
}
_x000D_
_x000D_
_x000D_

now add same width to tbody first column by,

_x000D_
_x000D_
  <table datatable class="display table ">_x000D_
            <thead>_x000D_
            <tr>_x000D_
                <th class="text-left" style="width: 300px!important;">name</th>_x000D_
            </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
           _x000D_
            <tr>_x000D_
                <td class="text-left" style="width: 300px!important;">jhon mathew</td>_x000D_
                _x000D_
            </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
       
_x000D_
_x000D_
_x000D_

by this way you can easily change width by changing the order of nth child. if you want 3 column then ,add nth-child(3)

How to create streams from string in Node.Js?

I got tired of having to re-learn this every six months, so I just published an npm module to abstract away the implementation details:

https://www.npmjs.com/package/streamify-string

This is the core of the module:

const Readable = require('stream').Readable;
const util     = require('util');

function Streamify(str, options) {

  if (! (this instanceof Streamify)) {
    return new Streamify(str, options);
  }

  Readable.call(this, options);
  this.str = str;
}

util.inherits(Streamify, Readable);

Streamify.prototype._read = function (size) {

  var chunk = this.str.slice(0, size);

  if (chunk) {
    this.str = this.str.slice(size);
    this.push(chunk);
  }

  else {
    this.push(null);
  }

};

module.exports = Streamify;

str is the string that must be passed to the constructor upon invokation, and will be outputted by the stream as data. options are the typical options that may be passed to a stream, per the documentation.

According to Travis CI, it should be compatible with most versions of node.

How to get the Google Map based on Latitude on Longitude?

<script>
    function initMap() {
        //echo hiii;

        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(8.5241, 76.9366),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

        // Change this depending on the name of your PHP or XML file
        downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('package');
            Array.prototype.forEach.call(markers, function(markerElem) {
                var id = markerElem.getAttribute('id');
                // var name = markerElem.getAttribute('name');
                // var address = markerElem.getAttribute('address');
                // var type = markerElem.getAttribute('type');
                // var latitude = results[0].geometry.location.lat();
                // var longitude = results[0].geometry.location.lng();
                var point = new google.maps.LatLng(
                    parseFloat(markerElem.getAttribute('latitude')),
                    parseFloat(markerElem.getAttribute('longitude'))
                );

                var infowincontent = document.createElement('div');
                var strong = document.createElement('strong');
                strong.textContent = name
                infowincontent.appendChild(strong);
                infowincontent.appendChild(document.createElement('br'));

                var text = document.createElement('text');
                text.textContent = address
                infowincontent.appendChild(text);
                var icon = customLabel[type] || {};
                var package = new google.maps.Marker({
                    map: map,
                    position: point,
                    label: icon.label
                });

                package.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, package);
                });
            });
        });
    }


    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

Turning multiple lines into one comma separated line

sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'

Remove all special characters except space from a string using JavaScript

You can do it specifying the characters you want to remove:

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g, '');

Set cookies for cross origin requests

Note for Chrome Browser released in 2020.

A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.

More info https://www.chromium.org/updates/same-site.

Firefox and Edge developers also want to release this feature in the future.

Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8

Switching a DIV background image with jQuery

One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:

$(document).ready(function(){
    $(".button").click(function () {
        $(this).children(".arrow").toggle();
            return false;
    });
});

<a href="#" class="button">
    <span class="arrow">
        <img src="/images/icons/left.png" alt="+" />
    </span>
    <span class="arrow" style="display: none;">
        <img src="/images/down.png" alt="-" />
    </span>
</a>

Pandas DataFrame to List of Lists

I wanted to preserve the index, so I adapted the original answer to this solution:

list_df = df.reset_index().values.tolist()

Now you can paste it somewhere else (e.g. to paste into a Stack Overflow question) and latter recreate it:

pd.Dataframe(list_df, columns=['name1', ...])
pd.set_index(['name1'], inplace=True)

Editing the date formatting of x-axis tick labels in matplotlib

In short:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

Create excel ranges using column numbers in vba?

These answers seem strangely convoluted. Unless I'm missing something...if you want to convert numbers to letters, you can just stock them all in an array using a for loop then call on the number associated with that column letter. Like so

For intloop = 1 To 26
    colcheck(intloop) = Chr$(64 + intloop)
    For lenloop = 1 To 26
        colcheck((intloop * 26) + lenloop) = Chr$(64 + intloop) & Chr$(64 + lenloop)
        For terloop = 1 To 26
            colcheck((intloop * 676) + (lenloop * 26) + terloop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop)
            For qualoop = 1 To 26
                colcheck((intloop * 17576) + (lenloop * 676) + (terloop * 26) + qualoop) = Chr$(64 + intloop) & Chr$(64 + lenloop) & Chr$(64 + terloop) & Chr$(64 + qualoop)
            Next qualoop
        Next terloop
    Next lenloop
Next intloop

Then just use colcheck(yourcolumnnumberhere) and you will get the column heading associated with that letter (i.e. colcheck(703) = AAA

Determine what attributes were changed in Rails after_save callback?

You just add an accessor who define what you change

class Post < AR::Base
  attr_reader :what_changed

  before_filter :what_changed?

  def what_changed?
    @what_changed = changes || []
  end

  after_filter :action_on_changes

  def action_on_changes
    @what_changed.each do |change|
      p change
    end
  end
end

How can I convert a string to boolean in JavaScript?

Do:

var isTrueSet = (myValue == 'true');

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==).

var isTrueSet = (myValue === 'true');

Don't:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

how to remove css property using javascript?

This should do the trick - setting the inline style to normal for zoom:

$('div').attr("style", "zoom:normal;");

Running code in main thread from another thread

One method I can think of is this:

1) Let the UI bind to the service.
2) Expose a method like the one below by the Binder that registers your Handler:

public void registerHandler(Handler handler) {
    mHandler = handler;
}

3) In the UI thread, call the above method after binding to the service:

mBinder.registerHandler(new Handler());

4) Use the handler in the Service's thread to post your task:

mHandler.post(runnable);

how get yesterday and tomorrow datetime in c#

The trick is to use "DateTime" to manipulate dates; only use integers and strings when you need a "final result" from the date.

For example (pseudo code):

  1. Get "DateTime tomorrow = Now + 1"

  2. Determine date, day of week, day of month - whatever you want - of the resulting date.

Can you overload controller methods in ASP.NET MVC?

If this is an attempt to use one GET action for several views that POST to several actions with different models, then try add a GET action for each POST action that redirects to the first GET to prevent 404 on refresh.

Long shot but common scenario.

All com.android.support libraries must use the exact same version specification

I had this:

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:27.1.1'
   implementation 'com.android.support:design:27.1.1'
   implementation 'com.android.support:support-v4:27.1.1'
   implementation 'com.google.firebase:firebase-auth:12.0.1'
   implementation 'com.google.firebase:firebase-firestore:12.0.1'
   implementation 'com.google.firebase:firebase-messaging:12.0.1'
   implementation 'com.google.android.gms:play-services-auth:12.0.1'
   implementation'com.facebook.android:facebook-login:[4,5)'
   implementation 'com.twitter.sdk.android:twitter:3.1.1'
   implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
   implementation 'org.jetbrains:annotations-java5:15.0'
   implementation project(':vehiclesapi')
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.1'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

and got this error: enter image description here

The solutions was easy - the primary dependencies were all correct so the leaves however - any third party dependencies. Removed one by one until found the culprit, and turns out to be facebook! its using version 27.0.2 of the android support libraries. I tried to add the cardview version 27.1.1 but that didn't work eithern the solution was still simple enough.

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:27.1.1'
   implementation 'com.android.support:design:27.1.1'
   implementation 'com.android.support:support-v4:27.1.1'
   implementation 'com.google.firebase:firebase-auth:12.0.1'
   implementation 'com.google.firebase:firebase-firestore:12.0.1'
   implementation 'com.google.firebase:firebase-messaging:12.0.1'
   implementation 'com.google.android.gms:play-services-auth:12.0.1'
   implementation('com.facebook.android:facebook-login:[4,5)'){
       // contains com.android.support:v7:27.0.2, included required com.android.support.*:27.1.1 modules
    exclude group: 'com.android.support'
   }
   implementation 'com.android.support:cardview-v7:27.1.1' // to replace facebook sdk's cardview-v7:27.0.2.
   implementation 'com.twitter.sdk.android:twitter:3.1.1'
   implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
   implementation 'org.jetbrains:annotations-java5:15.0'
   implementation project(':vehiclesapi')
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.1'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I had this error for some time and found a fix. This fix is for Asp.net application, Strange it failed only in IE non compatibility mode, but works in Firefox and Crome. Giving access to the webservice service folder for all/specific users solved the issue.

Add the following code in web.config file:

 <location path="YourWebserviceFolder">
  <system.web>
   <authorization>
    <allow users="*"/>
   </authorization>
  </system.web>
 </location>

How to delete all instances of a character in a string in python?

I suggest split (not saying that the other answers are invalid, this is just another way to do it):

def findreplace(char, string):
   return ''.join(string.split(char))

Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below

In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'

And the speed...

In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204

Not as fast as replace or translate, but ok.

Resolve Git merge conflicts in favor of their changes during a pull

To resolve all conflicts with the version in a particular branch:

git diff --name-only --diff-filter=U | xargs git checkout ${branchName}

So, if you are already in the merging state, and you want to keep the master version of the conflicting files:

git diff --name-only --diff-filter=U | xargs git checkout master

Override valueof() and toString() in Java enum

You can use a static Map in your enum that maps Strings to enum constants. Use it in a 'getEnum' static method. This skips the need to iterate through the enums each time you want to get one from its String value.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private final String strVal;
    private RandomEnum(String strVal) {
        this.strVal = strVal;
    }

    public static RandomEnum getEnum(String strVal) {
        if(!strValMap.containsKey(strVal)) {
            throw new IllegalArgumentException("Unknown String Value: " + strVal);
        }
        return strValMap.get(strVal);
    }

    private static final Map<String, RandomEnum> strValMap;
    static {
        final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
        for(final RandomEnum en : RandomEnum.values()) {
            tmpMap.put(en.strVal, en);
        }
        strValMap = ImmutableMap.copyOf(tmpMap);
    }

    @Override
    public String toString() {
        return strVal;
    }
}

Just make sure the static initialization of the map occurs below the declaration of the enum constants.

BTW - that 'ImmutableMap' type is from the Google guava API, and I definitely recommend it in cases like this.


EDIT - Per the comments:

  1. This solution assumes that each assigned string value is unique and non-null. Given that the creator of the enum can control this, and that the string corresponds to the unique & non-null enum value, this seems like a safe restriction.
  2. I added the 'toSTring()' method as asked for in the question

Length of the String without using length() method

Very nice solutions. Here are some more.

int length ( String s )
{
     int length = 0 ;
     // iterate through all possible code points
     for ( int i = INTEGER . MIN_VALUE ; i <= INTEGER . MAX_VALUE ; i ++ ) 
     {
           // count the number of i's in the string
          for ( int next = s . indexOf ( i , next ) + 1 ; next != -1 ; next = s . indexOf ( i , next ) + 1 )
          {
               length ++ ;
          }
     }
     return ( length ) ;
}

Here is a recursive version:

int length ( String s )
{
     int length = 0 ;
     search :
     for ( int i = Integer . MIN_VALUE ; i <= Integer . MAX_VALUE ; i ++ )
     {
          final int k = s . indexOf ( i ) ;
          if ( k != -1 )
          {
               length = length ( s . substring ( 0 , k ) ) + length ( s . substring ( k ) ) ;
               break search ;
          }
     }
     return ( length ) ;
}

And still more

int length ( String s )
{
     int length ;
     search ;
     for ( length = 0 ; true ; length ++ )
     {
          int [ ] codePoints = new int [ length ] ;
          for ( each possible value of codePoints from {MIN_VALUE,MIN_VALUE,...} to {MAX_VALUE,MAX_VALUE,...} )
          {
               if ( new String ( codePoints ) . equals ( s ) ) { break search ; }
          }
     }
}

How could I forget one that actually works in a reasonable time? (String#length is still preferred.)

int length ( String s )
{
     String t = s . replaceAll ( "." , "A" ) ;
     int length ;
     String r = "" ;
     search :
     for ( r = "" , length = 0 ; true ; r += "A" , length ++ )
          {
               if ( r . equals ( t ) )
               {
                    break search ;
               }
          }
     return ( length ) ;
}

Use a JSON array with objects with javascript

_x000D_
_x000D_
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
_x000D_
_x000D_

Copy files from one directory into an existing directory

What you want is:

cp -R t1/. t2/

The dot at the end tells it to copy the contents of the current directory, not the directory itself. This method also includes hidden files and folders.

How can I get input radio elements to horizontally align?

To get your radio button to list horizontally , just add

RepeatDirection="Horizontal"

to your .aspx file where the asp:radiobuttonlist is being declared.

How to grant remote access to MySQL for a whole subnet?

EDIT: Consider looking at and upvoting Malvineous's answer on this page. Netmasks are a much more elegant solution.


Simply use a percent sign as a wildcard in the IP address.

From http://dev.mysql.com/doc/refman/5.1/en/grant.html

You can specify wildcards in the host name. For example, user_name@'%.example.com' applies to user_name for any host in the example.com domain, and user_name@'192.168.1.%' applies to user_name for any host in the 192.168.1 class C subnet.

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

Wait until boolean value changes it state

Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.

Integer any = new Integer(0);

public synchronized boolean waitTillChange() {
    any.wait();
    return true;
}

public synchronized void change() {
    any.notify();
}

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

An easy approach is to leverage this code:

<a href="javascript:void(0);">Link Title</a>

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.

Can comments be used in JSON?

If your text file, which is a JSON string, is going to be read by some program, how difficult would it be to strip out either C or C++ style comments before using it?

Answer: It would be a one liner. If you do that then JSON files could be used as configuration files.

Should functions return null or an empty object?

It will vary based on context, but I will generally return null if I'm looking for one particular object (as in your example) and return an empty collection if I'm looking for a set of objects but there are none.

If you've made a mistake in your code and returning null leads to null pointer exceptions, then the sooner you catch that the better. If you return an empty object, initial use of it may work, but you may get errors later.

String replacement in Objective-C

It also posible string replacement with stringByReplacingCharactersInRange:withString:

for (int i = 0; i < card.length - 4; i++) {

    if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {

        NSRange range = NSMakeRange(i, 1);
        card = [card stringByReplacingCharactersInRange:range withString:@"*"];

    }

} //out: **** **** **** 1234

Invoking a static method using reflection

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

I know this has been answered but none of these solutions worked for me. I needed to take a different approach. I am using PhoneGap and am compiling my code natively so I had to move the background to the body. I hope this helps someone else. Or if there a cleaner way to do this please feel free to comment...

$(document).on('shown.bs.modal', '.modal', function (e) {

    $("#" + e.target.id).find(".modal-backdrop").css("z-index", $("#" + e.target.id).css("z-index")).insertBefore("#" + e.target.id);

});

How can I mock an ES6 module import using Jest?

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

How do I run Visual Studio as an administrator by default?

Right-click the icon, then click Properties. In the properties window, go to the Compatibility tab. There should be a checkbox labeled "Run this program as an administrator." Check that, then click OK. The next time you run the application from that shortcut, it will automatically run as the admin.

php: loop through json array

Decode the JSON string using json_decode() and then loop through it using a regular loop:

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}

how to overlap two div in css?

add to second div bottomDiv

and add this to css.

 .bottomDiv{
       position:relative;
       bottom:150px;
       left:150px;
    }

http://jsfiddle.net/aw8RD/1/

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Eclipse CDT project built but "Launch Failed. Binary Not Found"

I think I found solution - proper binary parser must be selected so Eclipse can recognize the executable:

Select the project, then right-click. Project->Properties->C/C++ Build->Settings->Binary Parsers, PE Windows Parser.

I.e. if Cygwin compiler is used then Cygwin parser should be used.

That worked for me at least for Cross-compiler (both on Windows 7 and Ubuntu 12.04). On Linux, I use Elf parser.

If anyone has the better solution, please advise.

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

How to load up CSS files using Javascript?

Element.insertAdjacentHTML has very good browser support, and can add a stylesheet in one line.

document.getElementsByTagName("head")[0].insertAdjacentHTML(
    "beforeend",
    "<link rel=\"stylesheet\" href=\"path/to/style.css\" />");

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

Button text toggle in jquery

You can also use math function to do this

var i = 0;
$('#button').on('click', function() {
    if (i++ % 2 == 0) {
        $(this).val("Push me!");
    } else {
        $(this).val("Don't push me!");
    }
});

DEMO

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

Check if a Bash array contains a value

I came up with this one, which turns out to work only in zsh, but I think the general approach is nice.

arr=( "hello world" "find me" "what?" )
if [[ "${arr[@]/#%find me/}" != "${arr[@]}" ]]; then
    echo "found!"
else
    echo "not found!"
fi

You take out your pattern from each element only if it starts ${arr[@]/#pattern/} or ends ${arr[@]/%pattern/} with it. These two substitutions work in bash, but both at the same time ${arr[@]/#%pattern/} only works in zsh.

If the modified array is equal to the original, then it doesn't contain the element.

Edit:

This one works in bash:

 function contains () {
        local arr=(${@:2})
        local el=$1
        local marr=(${arr[@]/#$el/})
        [[ "${#arr[@]}" != "${#marr[@]}" ]]
    }

After the substitution it compares the length of both arrays. Obly if the array contains the element the substitution will completely delete it, and the count will differ.

Injecting Mockito mocks into a Spring bean

@InjectMocks
private MyTestObject testObject;

@Mock
private MyDependentObject mockedObject;

@Before
public void setup() {
        MockitoAnnotations.initMocks(this);
}

This will inject any mocked objects into the test class. In this case it will inject mockedObject into the testObject. This was mentioned above but here is the code.

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

A potentially dangerous Request.Path value was detected from the client (*)

You should encode the route value and then (if required) decode the value before searching.

Ways to iterate over a list in Java

I don't know what you consider pathological, but let me provide some alternatives you could have not seen before:

List<E> sl= list ;
while( ! sl.empty() ) {
    E element= sl.get(0) ;
    .....
    sl= sl.subList(1,sl.size());
}

Or its recursive version:

void visit(List<E> list) {
    if( list.isEmpty() ) return;
    E element= list.get(0) ;
    ....
    visit(list.subList(1,list.size()));
}

Also, a recursive version of the classical for(int i=0... :

void visit(List<E> list,int pos) {
    if( pos >= list.size() ) return;
    E element= list.get(pos) ;
    ....
    visit(list,pos+1);
}

I mention them because you are "somewhat new to Java" and this could be interesting.

WCF ServiceHost access rights

If you are running via the IDE, running as administrator should help. To do this locate the Visual Studio 2008/10 application icon, right click it and select "Run as administrator"

jQuery Ajax POST example with PHP

Please check this. It is the complete Ajax request code.

$('#foo').submit(function(event) {
    // Get the form data
    // There are many ways to get this data using jQuery (you
    // can use the class or id also)
    var formData = $('#foo').serialize();
    var url = 'URL of the request';

    // Process the form.
    $.ajax({
        type        : 'POST',   // Define the type of HTTP verb we want to use
        url         : 'url/',   // The URL where we want to POST
        data        : formData, // Our data object
        dataType    : 'json',   // What type of data do we expect back.
        beforeSend : function() {

            // This will run before sending an Ajax request.
            // Do whatever activity you want, like show loaded.
        },
        success:function(response){
            var obj = eval(response);
            if(obj)
            {
                if(obj.error==0){
                    alert('success');
                }
                else{
                    alert('error');
                }
            }
        },
        complete : function() {
            // This will run after sending an Ajax complete
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert('error occured');
            // If any error occurs in request
        }
    });

    // Stop the form from submitting the normal way
    // and refreshing the page
    event.preventDefault();
});

Quick way to retrieve user information Active Directory

Well, if you know where your user lives in the AD hierarchy (e.g. quite possibly in the "Users" container, if it's a small network), you could also bind to the user account directly, instead of searching for it.

DirectoryEntry deUser = new DirectoryEntry("LDAP://cn=John Doe,cn=Users,dc=yourdomain,dc=com");

if (deUser != null)
{
  ... do something with your user
}

And if you're on .NET 3.5 already, you could even use the vastly expanded System.DirectorySrevices.AccountManagement namespace with strongly typed classes for each of the most common AD objects:

// bind to your domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain, "LDAP://dc=yourdomain,dc=com");

// find the user by identity (or many other ways)
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "cn=John Doe");

There's loads of information out there on System.DirectoryServices.AccountManagement - check out this excellent article on MSDN by Joe Kaplan and Ethan Wilansky on the topic.

How to create border in UIButton?

Swift 5

button.layer.borderWidth = 2

To change the colour of the border use

button.layer.borderColor = CGColor(srgbRed: 255/255, green: 126/255, blue: 121/255, alpha: 1)

Angularjs simple file download causes router to redirect

https://docs.angularjs.org/guide/$location#html-link-rewriting

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element Example:
    <a href="/ext/link?a=b" target="_self">link</a>

  • Absolute links that go to a different domain Example:
    <a href="http://angularjs.org/">link</a>

  • Links starting with '/' that lead to a different base path when base is defined Example:
    <a href="/not-my-base/link">link</a>

So in your case, you should add a target attribute like so...

<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">

How to get request URI without context path?

request.getRequestURI().substring(request.getContextPath().length())

sqlplus statement from command line

I assume this is *nix?

Use "here document":

sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF

EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):

$ echo 'select 1 from dual;'|sqlplus -s user/pw

         1
----------
         1


$

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Select SQL results grouped by weeks

This should do it for you:

Declare @DatePeriod datetime

Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'

From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
        Sale as 'Sale'

From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod variable is used to fetch only rows relative to the month (in this example only for the month of May)

Output using my sample data:

enter image description here

How to recursively download a folder via FTP on Linux

If you can use scp instead of ftp, the -r option will do this for you. I would check to see whether you can use a more modern file transfer mechanism than FTP.

DisplayName attribute from Resources?

I got Gunders answer working with my App_GlobalResources by choosing the resources properties and switch "Custom Tool" to "PublicResXFileCodeGenerator" and build action to "Embedded Resource". Please observe Gunders comment below.

enter image description here

Works like a charm :)

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

UILabel - auto-size label to fit text?

I created some methods based Daniel's reply above.

-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
    CGSize maximumLabelSize     = CGSizeMake(290, FLT_MAX);

    CGSize expectedLabelSize    = [text sizeWithFont:label.font
                                constrainedToSize:maximumLabelSize
                                    lineBreakMode:label.lineBreakMode];

    return expectedLabelSize.height;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label
{
    CGRect newFrame         = label.frame;
    newFrame.size.height    = [self heightForLabel:label withText:label.text];
    label.frame             = newFrame;
}

-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
    label.text              = text;
    [self resizeHeightToFitForLabel:label];
}

Refreshing all the pivot tables in my excel workbook with a macro

The code

Private Sub Worksheet_Activate()
    Dim PvtTbl As PivotTable
        Cells.EntireColumn.AutoFit
        For Each PvtTbl In Worksheets("Sales Details").PivotTables
        PvtTbl.RefreshTable
        Next
End Sub 

works fine.

The code is used in the activate sheet module, thus it displays a flicker/glitch when the sheet is activated.

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

How can I convert a .jar to an .exe?

JSmooth .exe wrapper

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your Java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a website.

JSmooth provides a variety of wrappers for your java application, each of them having their own behavior: Choose your flavor!

Download: http://jsmooth.sourceforge.net/

JarToExe 1.8 Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe on their website:

Can generate “Console”, “Windows GUI”, “Windows Service” three types of .exe files.

Generated .exe files can add program icons and version information. Generated .exe files can encrypt and protect java programs, no temporary files will be generated when the program runs.

Generated .exe files provide system tray icon support. Generated .exe files provide record system event log support. Generated windows service .exe files are able to install/uninstall itself, and support service pause/continue.

Executor

Package your Java application as a jar, and Executor will turn the jar into a Windows .exe file, indistinguishable from a native application. Simply double-clicking the .exe file will invoke the Java Runtime Environment and launch your application.

Redis command to get all available keys?

If your redis is a cluster,you can use this script

#!/usr/bin/env bash
redis_list=("172.23.3.19:7001,172.23.3.19:7002,172.23.3.19:7003,172.23.3.19:7004,172.23.3.19:7005,172.23.3.19:7006")

arr=($(echo "$redis_list" | tr ',' '\n'))

for info in ${arr[@]}; do
  echo "start :${info}"
  redis_info=($(echo "$info" | tr ':' '\n'))
  ip=${redis_info[0]}
  port=${redis_info[1]}
  echo "ip="${ip}",port="${port}
  redis-cli -c -h $ip -p $port set laker$port '?????'
  redis-cli -c -h $ip -p $port keys \*

done

echo "end"

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

As stated on Installing MySQL-python on mac :

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

Then test it :

python -c "import MySQLdb"

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

Change the image source on rollover using jQuery

I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:

#element {
    width: 100px; /* width of image */
    height: 200px; /* height of image */
    background-image: url(/path/to/image.jpg);
}

#element:hover {
    background-image: url(/path/to/other_image.jpg);
}

There's a longer description here

Even better, however, is to use sprites: simple-css-image-rollover

mongodb group values by multiple fields

Below query will provide exactly the same result as given in the desired response:

db.books.aggregate([
    {
        $group: {
            _id: { addresses: "$addr", books: "$book" },
            num: { $sum :1 }
        }
    },
    {
        $group: {
            _id: "$_id.addresses",
            bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
        }
    },
    {
        $project: {
            _id: 1,
            bookCounts:1,
            "totalBookAtAddress": {
                "$sum": "$bookCounts.count"
            }
        }
    }

]) 

The response will be looking like below:

/* 1 */
{
    "_id" : "address4",
    "bookCounts" : [
        {
            "bookName" : "book3",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 2 */
{
    "_id" : "address90",
    "bookCounts" : [
        {
            "bookName" : "book33",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 3 */
{
    "_id" : "address15",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 4 */
{
    "_id" : "address3",
    "bookCounts" : [
        {
            "bookName" : "book9",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 5 */
{
    "_id" : "address5",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 6 */
{
    "_id" : "address1",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 3
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 4
},

/* 7 */
{
    "_id" : "address2",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 2
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 3
},

/* 8 */
{
    "_id" : "address77",
    "bookCounts" : [
        {
            "bookName" : "book11",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 9 */
{
    "_id" : "address9",
    "bookCounts" : [
        {
            "bookName" : "book99",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
}

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can find the answer here: Is there a minlength validation attribute in HTML5?

Therefore this should do the job:

<input pattern=".{6,6}">

How to access Session variables and set them in javascript?

Here is what worked for me. Javascript has this.

<script type="text/javascript">
var deptname = '';
</script>

C# Code behind has this - it could be put on the master page so it reset var on ever page change.

        String csname1 = "LoadScript";
        Type cstype = p.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = p.ClientScript;

        // Check to see if the startup script is already registered.
        if (!cs.IsStartupScriptRegistered(cstype, csname1))
        {
            String cstext1 = funct;
            cs.RegisterStartupScript(cstype, csname1, "deptname = 'accounting'", true);
        }
        else
        {
            String cstext = funct;
            cs.RegisterClientScriptBlock(cstype, csname1, "deptname ='accounting'",true);
        }

Add this code to a button click to confirm deptname changed.

alert(deptname);

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

Is there a replacement for unistd.h for Windows (Visual C)?

I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h header you are looking for.

The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.

Create Test Class in IntelliJ

Alternatively you could also position the cursor onto the class name and press alt+enter (Show intention actions and quick fixes). It will suggest to Create Test.

At least works in IDEA version 12.

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

bash: mkvirtualenv: command not found

Since I just went though a drag, I'll try to write the answer I'd have wished for two hours ago. This is for people who don't just want the copy&paste solution

First: Do you wonder why copying and pasting paths works for some people while it doesn't work for others?** The main reason, solutions differ are different python versions, 2.x or 3.x. There are actually distinct versions of virtualenv and virtualenvwrapper that work with either python 2 or 3. If you are on python 2 install like so:

sudo pip install virutalenv
sudo pip install virtualenvwrapper

If you are planning to use python 3 install the related python 3 versions

sudo pip3 install virtualenv
sudo pip3 install virtualenvwrapper

You've successfully installed the packages for your python version and are all set, right? Well, try it. Type workon into your terminal. Your terminal will not be able to find the command (workon is a command of virtualenvwrapper). Of course it won't. Workon is an executable that will only be available to you once you load/source the file virtualenvwrapper.sh. But the official installation guide has you covered on this one, right?. Just open your .bash_profile and insert the following, it says in the documentation:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

Especially the command source /usr/local/bin/virtualenvwrapper.sh seems helpful since the command seems to load/source the desired file virtualenvwrapper.sh that contains all the commands you want to work with like workon and mkvirtualenv. But yeah, no. When following the official installation guide, you are very likely to receive the error from the initial post: mkvirtualenv: command not found. Still no command is being found and you are still frustrated. So whats the problem here? The problem is that virtualenvwrapper.sh is not were you are looking for it right now. Short reminder ... you are looking here:

source /usr/local/bin/virtualenvwrapper.sh

But there is a pretty straight forward way to finding the desired file. Just type

which virtualenvwrapper

to your terminal. This will search your PATH for the file, since it is very likely to be in some folder that is included in the PATH of your system.

If your system is very exotic, the desired file will hide outside of a PATH folder. In that case you can find the path to virtalenvwrapper.sh with the shell command find / -name virtualenvwrapper.sh

Your result may look something like this: /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh Congratulations. You have found your missing file!. Now all you have to do is changing one command in your .bash_profile. Just change:

source "/usr/local/bin/virtualenvwrapper.sh"

to:

"/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh"

Congratulations. Virtualenvwrapper does now work on your system. But you can do one more thing to enhance your solution. If you've found the file virtualenvwrapper.sh with the command which virtualenvwrapper.sh you know that it is inside of a folder of the PATH. So if you just write the filename, your file system will assume the file is inside of a PATH folder. So you you don't have to write out the full path. Just type:

source "virtualenvwrapper.sh"

Thats it. You are no longer frustrated. You have solved your problem. Hopefully.

Extract / Identify Tables from PDF python

I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py

This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.

Binding Combobox Using Dictionary as the Datasource

If this doesn't work why not simply do a foreach loop over the dictionary adding all the items to the combobox?

foreach(var item in userCache)
{
    userListComboBox.Items.Add(new ListItem(item.Key, item.Value));
}

Valid characters in a Java class name

Further to previous answers its worth noting that:

  1. Java allows any Unicode currency symbol in symbol names, so the following will all work:

$var1 £var2 €var3

I believe the usage of currency symbols originates in C/C++, where variables added to your code by the compiler conventionally started with '$'. An obvious example in Java is the names of '.class' files for inner classes, which by convention have the format 'Outer$Inner.class'

  1. Many C# and C++ programmers adopt the convention of placing 'I' in front of interfaces (aka pure virtual classes in C++). This is not required, and hence not done, in Java because the implements keyword makes it very clear when something is an interface.

Compare:

class Employee : public IPayable //C++

with

class Employee : IPayable //C#

and

class Employee implements Payable //Java

  1. Many projects use the convention of placing an underscore in front of field names, so that they can readily be distinguished from local variables and parameters e.g.

private double _salary;

A tiny minority place the underscore after the field name e.g.

private double salary_;

CURL alternative in Python

import requests

url = 'https://example.tld/'
auth = ('username', 'password')

r = requests.get(url, auth=auth)
print r.content

This is the simplest I've been able to get it.

Getting the IP address of the current machine using Java

EDIT 1: Updated code, since the previous link, exists no more

import java.io.*;
import java.net.*;

public class GetMyIP {
    public static void main(String[] args) {
        URL url = null;
        BufferedReader in = null;
        String ipAddress = "";
        try {
            url = new URL("http://bot.whatismyipaddress.com");
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            ipAddress = in.readLine().trim();
            /* IF not connected to internet, then
             * the above code will return one empty
             * String, we can check it's length and
             * if length is not greater than zero, 
             * then we can go for LAN IP or Local IP
             * or PRIVATE IP
             */
            if (!(ipAddress.length() > 0)) {
                try {
                    InetAddress ip = InetAddress.getLocalHost();
                    System.out.println((ip.getHostAddress()).trim());
                    ipAddress = (ip.getHostAddress()).trim();
                } catch(Exception exp) {
                    ipAddress = "ERROR";
                }
            }
        } catch (Exception ex) {
            // This try will give the Private IP of the Host.
            try {
                InetAddress ip = InetAddress.getLocalHost();
                System.out.println((ip.getHostAddress()).trim());
                ipAddress = (ip.getHostAddress()).trim();
            } catch(Exception exp) {
                ipAddress = "ERROR";
            }
            //ex.printStackTrace();
        }
        System.out.println("IP Address: " + ipAddress);
    }
}

ACTUAL VERSION: This stopped working

Hopefully this snippet might help you to achieve this :

// Method to get the IP Address of the Host.
private String getIP()
{
    // This try will give the Public IP Address of the Host.
    try
    {
        URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String ipAddress = new String();
        ipAddress = (in.readLine()).trim();
        /* IF not connected to internet, then
         * the above code will return one empty
         * String, we can check it's length and
         * if length is not greater than zero, 
         * then we can go for LAN IP or Local IP
         * or PRIVATE IP
         */
        if (!(ipAddress.length() > 0))
        {
            try
            {
                InetAddress ip = InetAddress.getLocalHost();
                System.out.println((ip.getHostAddress()).trim());
                return ((ip.getHostAddress()).trim());
            }
            catch(Exception ex)
            {
                return "ERROR";
            }
        }
        System.out.println("IP Address is : " + ipAddress);

        return (ipAddress);
    }
    catch(Exception e)
    {
        // This try will give the Private IP of the Host.
        try
        {
            InetAddress ip = InetAddress.getLocalHost();
            System.out.println((ip.getHostAddress()).trim());
            return ((ip.getHostAddress()).trim());
        }
        catch(Exception ex)
        {
            return "ERROR";
        }
    }
}

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

:: (double colon) operator in Java 8

return reduce(Math::max); is NOT EQUAL to return reduce(max());

But it means, something like this:

IntBinaryOperator myLambda = (a, b)->{(a >= b) ? a : b};//56 keystrokes I had to type -_-
return reduce(myLambda);

You can just save 47 keystrokes if you write like this

return reduce(Math::max);//Only 9 keystrokes ^_^

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

is there something like isset of php in javascript/jQuery?

JavaScript isset() on PHP JS

function isset () {
    // discuss at: http://phpjs.org/functions/isset
    // +   original by: Kevin van     Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // +   improved by: Rafal Kukawski
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    var a = arguments,
        l = a.length,
        i = 0,
        undef;

    if (l === 0) {
        throw new Error('Empty isset');
    }

    while (i !== l) {
        if (a[i] === undef || a[i] === null) {
            return false;
        }
        i++;
    }
    return true;
}

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

Need to ZIP an entire directory using Node.js

Since archiver is not compatible with the new version of webpack for a long time, I recommend using zip-lib.

var zl = require("zip-lib");

zl.archiveFolder("path/to/folder", "path/to/target.zip").then(function () {
    console.log("done");
}, function (err) {
    console.log(err);
});

Adding Only Untracked Files

If you have thousands of untracked files (ugh, don't ask) then git add -i will not work when adding *. You will get an error stating Argument list too long.

If you then also are on Windows (don't ask #2 :-) and need to use PowerShell for adding all untracked files, you can use this command:

git ls-files -o --exclude-standard | select | foreach { git add $_ }

Convert objective-c typedef to its string equivalent

I would use the compiler's # string token (along with macros to make it all more compact):

#define ENUM_START              \
            NSString* ret;      \
            switch(value) {

#define ENUM_CASE(evalue)       \
            case evalue:        \
                ret = @#evalue; \
                break;

#define ENUM_END                \
            }                   \
            return ret;

NSString*
_CvtCBCentralManagerStateToString(CBCentralManagerState value)
{
    ENUM_START
        ENUM_CASE(CBCentralManagerStateUnknown)
        ENUM_CASE(CBCentralManagerStateResetting)
        ENUM_CASE(CBCentralManagerStateUnsupported)
        ENUM_CASE(CBCentralManagerStateUnauthorized)
        ENUM_CASE(CBCentralManagerStatePoweredOff)
        ENUM_CASE(CBCentralManagerStatePoweredOn)
    ENUM_END
}

Android - Using Custom Font

Yes, downloadable fonts are so easy, as Dipali s said.

This is how you do it...

  1. Place a TextView.
  2. In the properties pane, select the fontFamily dropdown. If it isn't there, find the caret thingy (the > and click on it to expand textAppearance) under the.
  3. Expand the font-family drop down.
  4. In the little list, scroll all the way down till you see more fonts
  5. This will open up a dialog box where you can search from Google Fonts
  6. Search for the font you like with the search bar at the top
  7. Select your font.
  8. Select the style of the font you like (i.e. bold, normal, italic, etc)
  9. In the right pane, choose the radio button that says Add font to project
  10. Click okay. Now your TextView has the font you like!

BONUS: If you would like to style EVERYTHING with text in your application with chosen font, just add <item name="android:fontfamily">@font/fontnamehere</item> into your styles.xml

How do I vertical center text next to an image in html/css?

Since most of the answers to this question are between 2009 and 2014 (except for a comment in 2018), there should be an update to this.

I found a solution to the wrap-text problem brought up by Spongman on Jun 11 '14 at 23:20. He has an example here: jsfiddle.net/vPpD4

If you add the following in the CSS under the div tag in the jsfiddle.net/vPpD4 example, you get the desired wrap-text effect that I think Spongman was asking about. I don't know how far back this is applicable, but this works in all of the current (as of Dec 2020/Jan 2021) browsers available for Windows computers. Note: I have not tested this on the Apple Safari browser. I have also not tested this on any mobile devices.

    div img { 
        float: left;
    }
    .clearfix::after {
        content: ""; 
        clear: both;
        display: table;
    }

I also added a border around the image, just so that the reader will understand where the edge of the image is and why the text wraps as it does. The resulting example looks is here: http://jsfiddle.net/tqg7hLzk/

How to make circular background using css?

It can be done using the border-radius property. basically, you need to set the border-radius to exactly half of the height and width to get a circle.

JSFiddle

HTML

<div id="container">
    <div id="inner">
    </div>
</div>

CSS

#container
{
    height:400px;
    width:400px;
    border:1px black solid;
}

#inner
{
    height:200px;
    width:200px;
    background:black;
    -moz-border-radius: 100px;
    -webkit-border-radius: 100px;
    border-radius: 100px;
    margin-left:25%;
    margin-top:25%;
}