Programs & Examples On #Tamil

This tag can be used in questions that relate to encoding standards, fonts, and the readability of the Tamil language.

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

Adding Google Translate to a web site

to allow google translate to be mobile friendly get rid of the layout section, layout: google.translate.TranslateElement.InlineLayout.SIMPLE

<div id="google_translate_element">
</div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

It works on my site and it is mobile friendly. https://livinghisword.org/articles/pages/whoiscernandisourworld.php

How to populate a dropdownlist with json data in jquery?

//javascript
//teams.Table does not exist

function OnSuccessJSON(data, status) {
    var teams = eval('(' + data.d + ')');
    var listItems = "";
    for (var i = 0; i < teams.length; i++) {
      listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
    }
    $("#<%=ddlTeams.ClientID%>").html(listItems);
} 

What is a lambda expression in C++11?

Answers

Q: What is a lambda expression in C++11?

A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.

Q: When would I use one?

A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.

Q: What class of problem do they solve that wasn't possible prior to their introduction?

A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)

Example of usage

auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);

Extras about lambdas, not covered by question. Ignore this section if you're not interest

1. Captured values. What you can to capture

1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.

1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).

[captureVar1,captureVar2](int arg1){}

1.3. You can capture be reference. & -- in this context mean reference, not pointers.

   [&captureVar1,&captureVar2](int arg1){}

1.4. It exists notation to capture all non-static vars by value, or by reference

  [=](int arg1){} // capture all not-static vars by value

  [&](int arg1){} // capture all not-static vars by reference

1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2

[=,&Param2](int arg1){} 

Capture all not-static vars by reference, but by value capture Param2

[&,Param2](int arg1){} 

2. Return type deduction

2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.

[=](int arg1)->trailing_return_type{return trailing_return_type();}

If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions

3. Captured values. What you can not capture

3.1. You can capture only local vars, not member variable of the object.

4. ?onversions

4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.

p.s.

  1. More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88

  2. In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:

    auto toFloat = [](int value) { return float(value);};
    auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
    

Find max and second max salary for a employee table MySQL

try this

select max(salary) as first, 
       (select salary from employee order by salary desc limit 1, 1) as second 
from employee limit 1

How to get the first and last date of the current year?

---Lalmuni Demos---

create table Users
(
userid int,date_of_birth date
)

---insert values---

insert into Users values(4,'9/10/1991')

select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, 
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, 
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

For a very specific reason Type Nullable<int> put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):

public struct Nullable<T> where T : struct
{
...
}

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Could not autowire field in spring. why?

In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)

What is aria-label and how should I use it?

In the example you give, you're perfectly right, you have to set the title attribute.

If the aria-label is one tool used by assistive technologies (like screen readers), it is not natively supported on browsers and has no effect on them. It won't be of any help to most of the people targetted by the WCAG (except screen reader users), for instance a person with intellectal disabilities.

The "X" is not sufficient enough to give information to the action led by the button (think about someone with no computer knowledge). It might mean "close", "delete", "cancel", "reduce", a strange cross, a doodle, nothing.

Despite the fact that the W3C seems to promote the aria-label rather that the title attribute here: http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140916/ARIA14 in a similar example, you can see that the technology support does not include standard browsers : http://www.w3.org/WAI/WCAG20/Techniques/ua-notes/aria#ARIA14

In fact aria-label, in this exact situation might be used to give more context to an action:

For instance, blind people do not perceive popups like those of us with good vision, it's like a change of context. "Back to the page" will be a more convenient alternative for a screen reader, when "Close" is more significant for someone with no screen reader.

  <button
      aria-label="Back to the page"
      title="Close" onclick="myDialog.close()">X</button>

Read the package name of an Android APK

You can use Analyze APK... from the Build menu in Android Studio, it will display the package name at the top of new window.

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

How to overlay image with color in CSS?

You may use negative superthick semi-transparent border...

_x000D_
_x000D_
.red {_x000D_
    outline: 100px solid rgba(255, 0, 0, 0.5) !important;_x000D_
    outline-offset: -100px;_x000D_
    overflow: hidden;_x000D_
    position: relative;_x000D_
    height: 200px;_x000D_
    width: 200px;_x000D_
}
_x000D_
<div class="red">Anything can be red.</div>_x000D_
<h1>Or even image...</h1>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" class="red"/>
_x000D_
_x000D_
_x000D_

This solution requires you to know exact sizes of covered object.

Passing enum or object through an intent (the best solution)

Most of the answers that are using Parcelable concept here are in Java code. It is easier to do it in Kotlin.

Just annotate your enum class with @Parcelize and implement Parcelable interface.

@Parcelize
enum class ViewTypes : Parcelable {
TITLE, PRICES, COLORS, SIZES
}

How can I use a DLL file from Python?

Maybe with Dispatch:

from win32com.client import Dispatch

zk = Dispatch("zkemkeeper.ZKEM") 

Where zkemkeeper is a registered DLL file on the system... After that, you can access functions just by calling them:

zk.Connect_Net(IP_address, port)

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

MySQL LIMIT on DELETE statement

Use row_count - your_desired_offset

So if we had 10 rows and want to offset 3

 10 - 3 = 7

Now the query delete from table where this = that order asc limit 7 keeps the last 3, and order desc to keep the first 3:

$row_count - $offset = $limit

Delete from table where entry = criteria order by ts asc limit $limit

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Can't import all at once but can use following combination:

ALT + Enter --> Show intention actions and quick-fixes.

F2 --> Next highlighted error.

Failed to Connect to MySQL at localhost:3306 with user root

Go to system preferences, then "MySQL"

Click on "Start MySQL Server"

Go to system preferences, then "MySQL". Click on "Start MySQL Server".

how to use sqltransaction in c#

The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection 
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction. 
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred 
                // on the server that would cause the rollback to fail, such as 
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

See SqlTransaction Class

Check if the number is integer

you can use simple if condition like:

if(round(var) != var)­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Find multiple files and rename them in Linux

If you just want to rename and don't mind using an external tool, then you can use rnm. The command would be:

#on current folder
rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' *

-dp -1 will make it recursive to all subdirectories.

-fo implies file only mode.

-ssf '_dbg' searches for files with _dbg in the filename.

-rs '/_dbg//' replaces _dbg with empty string.

You can run the above command with the path of the CURRENT_FOLDER too:

rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory

Is there a way to programmatically scroll a scroll view to a specific edit text?

private final void focusOnView(){
        your_scrollview.post(new Runnable() {
            @Override
            public void run() {
                your_scrollview.scrollTo(0, your_EditBox.getBottom());
            }
        });
    }

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Custom Cell Row Height setting in storyboard is not responding

For dynamic cells, rowHeight set on the UITableView always overrides the individual cells' rowHeight.

This behavior is, IMO, a bug. Anytime you have to manage your UI in two places it is prone to error. For example, if you change your cell size in the storyboard, you have to remember to change them in the heightForRowAtIndexPath: as well. Until Apple fixes the bug, the current best workaround is to override heightForRowAtIndexPath:, but use the actual prototype cells from the storyboard to determine the height rather than using magic numbers. Here's an example:

- (CGFloat)tableView:(UITableView *)tableView 
           heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /* In this example, there is a different cell for
       the top, middle and bottom rows of the tableView.
       Each type of cell has a different height.
       self.model contains the data for the tableview 
    */
    static NSString *CellIdentifier;
    if (indexPath.row == 0) 
        CellIdentifier = @"CellTop";
    else if (indexPath.row + 1 == [self.model count] )
        CellIdentifier = @"CellBottom";
    else
        CellIdentifier = @"CellMiddle";

    UITableViewCell *cell = 
              [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    return cell.bounds.size.height;
}

This will ensure any changes to your prototype cell heights will automatically be picked up at runtime and you only need to manage your UI in one place: the storyboard.

Reset ID autoincrement ? phpmyadmin

I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.

Using the slash character in Git branch name

I forgot that I had already an unused labs branch. Deleting it solved my problem:

git branch -d labs
git checkout -b labs/feature

Explanation:

Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs and labs/feature can't exists both at the same time.

The reason: Branches are stored in the file system and there you also can't have a file labs and a directory labs at the same level.

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Since Spark 1.5 you can use a number of date processing functions:

import datetime
from pyspark.sql.functions import year, month, dayofmonth

elevDF = sc.parallelize([
    (datetime.datetime(1984, 1, 1, 0, 0), 1, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 2, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 3, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 4, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 5, 638.55)
]).toDF(["date", "hour", "value"])

elevDF.select(
    year("date").alias('year'), 
    month("date").alias('month'), 
    dayofmonth("date").alias('day')
).show()
# +----+-----+---+
# |year|month|day|
# +----+-----+---+
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# +----+-----+---+

You can use simple map as with any other RDD:

elevDF = sqlContext.createDataFrame(sc.parallelize([
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=1, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=2, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=3, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=4, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=5, value=638.55)]))

(elevDF
 .map(lambda (date, hour, value): (date.year, date.month, date.day))
 .collect())

and the result is:

[(1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1)]

Btw: datetime.datetime stores an hour anyway so keeping it separately seems to be a waste of memory.

Invalid Host Header when ngrok tries to connect to React dev server

I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:

module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
},   }

Require the file in the server.

const configstrp      = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;

and connect as such

if (ngrok) {
console.log('If nGronk')
ngrok.connect(
    {
    addr: configstrp.ngrok.port,
    subdomain: configstrp.ngrok.subdomain,
    authtoken: configstrp.ngrok.authtoken,
    host_header:3000
  },
  (err, url) => {
    if (err) {

    } else {

    }
   }
  );
 }

Do not pass a subdomain if you do not have a custom domain

How to find NSDocumentDirectory in Swift?

More convenient Swift 3 method:

let documentsUrl = FileManager.default.urls(for: .documentDirectory, 
                                             in: .userDomainMask).first!

Plot multiple lines (data series) each with unique color in R

I know, its old a post to answer but like I came across searching for the same post, someone else might turn here as well

By adding : colour in ggplot function , I could achieve the lines with different colors related to the group present in the plot.

ggplot(data=Set6, aes(x=Semana, y=Net_Sales_in_pesos, group = Agencia_ID, colour = as.factor(Agencia_ID)))    

and

geom_line() 

Line Graph with Multiple colors

Why does ++[[]][+[]]+[+[]] return the string "10"?

If we split it up, the mess is equal to:

++[[]][+[]]
+
[+[]]

In JavaScript, it is true that +[] === 0. + converts something into a number, and in this case it will come down to +"" or 0 (see specification details below).

Therefore, we can simplify it (++ has precendence over +):

++[[]][0]
+
[0]

Because [[]][0] means: get the first element from [[]], it is true that:

[[]][0] returns the inner array ([]). Due to references it's wrong to say [[]][0] === [], but let's call the inner array A to avoid the wrong notation.

++ before its operand means “increment by one and return the incremented result”. So ++[[]][0] is equivalent to Number(A) + 1 (or +A + 1).

Again, we can simplify the mess into something more legible. Let's substitute [] back for A:

(+[] + 1)
+
[0]

Before +[] can coerce the array into the number 0, it needs to be coerced into a string first, which is "", again. Finally, 1 is added, which results in 1.

  • (+[] + 1) === (+"" + 1)
  • (+"" + 1) === (0 + 1)
  • (0 + 1) === 1

Let's simplify it even more:

1
+
[0]

Also, this is true in JavaScript: [0] == "0", because it's joining an array with one element. Joining will concatenate the elements separated by ,. With one element, you can deduce that this logic will result in the first element itself.

In this case, + sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0", next, the number is coerced into a string ("1"). Number + String === String.

"1" + "0" === "10" // Yay!

Specification details for +[]:

This is quite a maze, but to do +[], first it is being converted to a string because that's what + says:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber() says:

Object

Apply the following steps:

  1. Let primValue be ToPrimitive(input argument, hint String).

  2. Return ToString(primValue).

ToPrimitive() says:

Object

Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.

[[DefaultValue]] says:

8.12.8 [[DefaultValue]] (hint)

When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:

  1. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".

  2. If IsCallable(toString) is true then,

a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.

b. If str is a primitive value, return str.

The .toString of an array says:

15.4.4.2 Array.prototype.toString ( )

When the toString method is called, the following steps are taken:

  1. Let array be the result of calling ToObject on the this value.

  2. Let func be the result of calling the [[Get]] internal method of array with argument "join".

  3. If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).

  4. Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.

So +[] comes down to +"", because [].join() === "".

Again, the + is defined as:

11.4.6 Unary + Operator

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.

  2. Return ToNumber(GetValue(expr)).

ToNumber is defined for "" as:

The MV of StringNumericLiteral ::: [empty] is 0.

So +"" === 0, and thus +[] === 0.

Is it wrong to place the <script> tag after the </body> tag?

Google actually recommends this in regards to 'CSS Optimization'. They recommend in-lining critical above-fold styles and deferring the rest(css file).

Example:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

See: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

Is it possible to set ENV variables for rails development environment in my code?

As an aside to the solutions here, there are cleaner alternatives if you're using certain development servers.

With Heroku's Foreman, you can create per-project environment variables in a .env file:

ADMIN_PASSOWRD="secret"

With Pow, you can use a .powenv file:

export ADMIN_PASSOWRD="secret"

CSS background image URL failing to load

You are using a local path. Is that really what you want? If it is, you need to use the file:/// prefix:

file:///H:/media/css/static/img/sprites/buttons-v3-10.png

obviously, this will work only on your local computer.

Also, in many modern browsers, this works only if the page itself is also on a local file path. Addressing local files from remote (http://, https://) pages has been widely disabled due to security reasons.

How to set a selected option of a dropdown list control using angular JS

I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.

You can use track by attribute in your ng-options.

Assume that you have:

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]

You can mention your ng-options as:

ng-options="v.name for v in variants track by v.id"

Hope this helps someone in future.

PHP: Inserting Values from the Form into MySQL

<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");

?>



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
 //$("form").submit(function(e){

     $("#btn1").click(function(e){
     e.preventDefault();
    // alert('here');
        $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');

    });
    //}
});
</script>

</head>

<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file"  name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>

<tr><td>Address:</td><td><textarea  cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input  type="number"  maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio"  name="r1" value="Male" checked="checked"/>Male<input type="radio"  name="r1" value="feale"/>Female</td></tr>
<tr><td><input  id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){


move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);

                     $fname = $_FILES['e5']['name'][$key];
                     $imgarryimp[]=$fname;
                     //echo $fname;

                     if(strlen($fname)>0)
                      {
                         $img = $fname;
                      }
                      $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
}
exit;





                      // echo $values;exit;
                      //foreach($_POST['e1'] as $row) 
    //{ 

    $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
    //}
    //exit;


}
?>

</form>

<table>
<?php 
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>

</body>
</html>

pandas get rows which are NOT in other dataframe

One method would be to store the result of an inner merge form both dfs, then we can simply select the rows when one column's values are not in this common:

In [119]:

common = df1.merge(df2,on=['col1','col2'])
print(common)
df1[(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))]
   col1  col2
0     1    10
1     2    11
2     3    12
Out[119]:
   col1  col2
3     4    13
4     5    14

EDIT

Another method as you've found is to use isin which will produce NaN rows which you can drop:

In [138]:

df1[~df1.isin(df2)].dropna()
Out[138]:
   col1  col2
3     4    13
4     5    14

However if df2 does not start rows in the same manner then this won't work:

df2 = pd.DataFrame(data = {'col1' : [2, 3,4], 'col2' : [11, 12,13]})

will produce the entire df:

In [140]:

df1[~df1.isin(df2)].dropna()
Out[140]:
   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14

Good way to encapsulate Integer.parseInt()

They way I handle this problem is recursively. For example when reading data from the console:

Java.util.Scanner keyboard = new Java.util.Scanner(System.in);

public int GetMyInt(){
    int ret;
    System.out.print("Give me an Int: ");
    try{
        ret = Integer.parseInt(keyboard.NextLine());

    }
    catch(Exception e){
        System.out.println("\nThere was an error try again.\n");
        ret = GetMyInt();
    }
    return ret;
}

Check to see if python script is running

Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.

#/usr/bin/env python

import os
import sys

pid = str(os.getpid())
pidfile = "/tmp/mydaemon.pid"

if os.path.isfile(pidfile):
    print "%s already exists, exiting" % pidfile
    sys.exit()
file(pidfile, 'w').write(pid)
try:
    # Do some actual work here
finally:
    os.unlink(pidfile)

Then you can check to see if the process is running by checking to see if the contents of /tmp/mydaemon.pid are an existing process. Monit (mentioned above) can do this for you, or you can write a simple shell script to check it for you using the return code from ps.

ps up `cat /tmp/mydaemon.pid ` >/dev/null && echo "Running" || echo "Not running"

For extra credit, you can use the atexit module to ensure that your program cleans up its pidfile under any circumstances (when killed, exceptions raised, etc.).

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You want to use URI templates. Look carefully at the README of this project: URLEncoder.encode() does NOT work for URIs.

Let us take your original URL:

http://site-test.test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

and convert it to a URI template with two variables (on multiple lines for clarity):

http://site-test.test.com/Meetings/IC/DownloadDocument
    ?meetingId={meetingID}&itemId={itemID}&file={file}

Now let us build a variable map with these three variables using the library mentioned in the link:

final VariableMap = VariableMap.newBuilder()
    .addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
    .addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
    .addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
        + "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
        + "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
    .build();

final URITemplate template
    = new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
        + "meetingId={meetingID}&itemId={itemID}&file={file}");

// Generate URL as a String
final String theURL = template.expand(vars);

This is GUARANTEED to return a fully functional URL!

python replace single backslash with double backslash

No need to use str.replace or string.replace here, just convert that string to a raw string:

>>> strs = r"C:\Users\Josh\Desktop\20130216"
           ^
           |
       notice the 'r'

Below is the repr version of the above string, that's why you're seeing \\ here. But, in fact the actual string contains just '\' not \\.

>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'

>>> s = r"f\o"
>>> s            #repr representation
'f\\o'
>>> len(s)   #length is 3, as there's only one `'\'`
3

But when you're going to print this string you'll not get '\\' in the output.

>>> print strs
C:\Users\Josh\Desktop\20130216

If you want the string to show '\\' during print then use str.replace:

>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216

repr version will now show \\\\:

>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'

Program to find prime numbers

You only need to check odd divisors up to the square root of the number. In other words your inner loop needs to start:

for (int j = 3; j <= Math.Sqrt(i); j+=2) { ... }

You can also break out of the function as soon as you find the number is not prime, you don't need to check any more divisors (I see you're already doing that!).

This will only work if num is bigger than two.

No Sqrt

You can avoid the Sqrt altogether by keeping a running sum. For example:

int square_sum=1;
for (int j=3; square_sum<i; square_sum+=4*(j++-1)) {...}

This is because the sum of numbers 1+(3+5)+(7+9) will give you a sequence of odd squares (1,9,25 etc). And hence j represents the square root of square_sum. As long as square_sum is less than i then j is less than the square root.

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Here is a simple mail sending code with attachment

try  
{  
    SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);  
    mailServer.EnableSsl = true;  

    mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");  

    string from = "[email protected]";  
    string to = "[email protected]";  
    MailMessage msg = new MailMessage(from, to);  
    msg.Subject = "Enter the subject here";  
    msg.Body = "The message goes here.";
    msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
    mailServer.Send(msg);  
}  
catch (Exception ex)  
{  
    Console.WriteLine("Unable to send email. Error : " + ex);  
}

Read more Sending emails with attachment in C#

Fastest way to implode an associative array with keys

My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 

Why use Optional.of over Optional.ofNullable?

Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

How to make in CSS an overlay over an image?

You could use a pseudo element for this, and have your image on a hover:

_x000D_
_x000D_
.image {_x000D_
  position: relative;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  transition: all 0.8s;_x000D_
  opacity: 0;_x000D_
  background: url(http://lorempixel.com/300/200);_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
  opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
_x000D_
_x000D_

How to use jQuery in AngularJS

Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/

  angular.module('App', [])
    .controller('AppCtrl', function ($scope) {

      $scope.model = 0;

      $scope.initSlider = function () {
          $(function () {
            // wait till load event fires so all resources are available
              $scope.$slider = $('#slider').slider({
                  slide: $scope.onSlide
              });
          });

          $scope.onSlide = function (e, ui) {
             $scope.model = ui.value;
             $scope.$digest();
          };
      };

      $scope.initSlider();
  });

The directive approach:

HTML

<div slider></div>

JS

  angular.module('App', [])
    .directive('slider', function (DataModel) {
      return {
         restrict: 'A',
         scope: true,
         controller: function ($scope, $element, $attrs) {
            $scope.onSlide = function (e, ui) {
              $scope.model = ui.value;
              // or set it on the model
              // DataModel.model = ui.value;
              // add to angular digest cycle
              $scope.$digest();
            };
         },
         link: function (scope, el, attrs) {

            var options = {
              slide: scope.onSlide  
            };

            // set up slider on load
            angular.element(document).ready(function () {
              scope.$slider = $(el).slider(options);
            });
         }
      }
  });

I would also recommend checking out Angular Bootstrap's source code: https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js

You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.

How to get css background color on <tr> tag to span entire row

Have you tried setting the spacing to zero?

/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

TLDR? Try: file = open(filename, encoding='cp437)

Why? When one use:

file = open(filename)
text = file.read()

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

file = open(filename, errors='replace')

Another workaround is to use:

file = open(filename, errors='ignore')

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

file = open(filename, encoding='cp437')

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

PG::ConnectionBad - could not connect to server: Connection refused

I stopped the rails server, ran rake db:migrate and started my rails s.

What's the right way to create a date in Java?

You can use SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");

But I don't know whether it should be considered more right than to use Calendar ...

Position a div container on the right side

  • Use float: right to.. float the second column to the.. right.
  • Use overflow: hidden to clear the floats so that the background color I just put in will be visible.

Live Demo

#wrapper{
    background:#000;
    overflow: hidden
}
#c1 {
   float:left;
   background:red;
}
#c2 {
    background:green;
    float: right
}

HTTP Status 404 - The requested resource (/) is not available

Following steps helped me solve the issue.

  1. In the eclipse right click on server and click on properties.
  2. If Location is set workspace/metadata click on switch location and so that it refers to /servers/tomcatv7server at localhost.server
  3. Save and close
  4. Next double click on server
  5. Under server locations mostly it would be selected as use workspace metadata Instead, select use tomcat installation
  6. Save changes
  7. Restart server and verify localhost:8080 works.

Create two blank lines in Markdown

In GitHub Wiki markdown I used hash marks (#) followed by two spaces to make the line break larger. It doesn't actually give you multiple line breaks but it made one large line break and served me well for my needs.

Instead of:

text
(space)(space)
more text

I did:

text
(hash mark)(space)(space)
more text

C: How to free nodes in the linked list?

You could always do it recursively like so:

void freeList(struct node* currentNode)
{
    if(currentNode->next) freeList(currentNode->next);
    free(currentNode);
}

Is JavaScript's "new" keyword considered harmful?

Case 1: new isn't required and should be avoided

var str = new String('asd');  // type: object
var str = String('asd');      // type: string

var num = new Number(12);     // type: object
var num = Number(12);         // type: number

Case 2: new is required, otherwise you'll get an error

new Date().getFullYear();     // correct, returns the current year, i.e. 2010
Date().getFullYear();         // invalid, returns an error

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

A different take with a simple jQuery plugin

Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.

This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.

You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.

All you have to do is to use this plugin on the client side. An Ajax request would look like this:

$.ajax({
    type: "POST",
    url: "SomeURL",
    data: $.toDictionary(yourComplexJSONobject),
    success: function() { ... },
    error: function() { ... }
});

But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.

FtpWebRequest Download File

Easiest way

The most trivial way to download a binary file from an FTP server using .NET framework is using WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

Advanced options

Use FtpWebRequest, only if you need a greater control, that WebClient does not offer (like TLS/SSL encryption, progress monitoring, ascii/text transfer mode, resuming transfers, etc). Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

Progress monitoring

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar


Downloading folder

If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

try this too

pd.set_option("max_columns", None) # show all cols
pd.set_option('max_colwidth', None) # show full width of showing cols
pd.set_option("expand_frame_repr", False) # print cols side by side as it's supposed to be

Select NOT IN multiple columns

I'm not sure whether you think about:

select * from friend f
where not exists (
    select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)

it works only if id1 is related with id1 and id2 with id2 not both.

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

Python Git Module experiences?

I'd recommend pygit2 - it uses the excellent libgit2 bindings

Unix: How to delete files listed in a file

This will allow file names to have spaces (reproducible example).

# Select files of interest, here, only text files for ex.
find -type f -exec file {} \; > findresult.txt
grep ": ASCII text$" findresult.txt > textfiles.txt
# leave only the path to the file removing suffix and prefix
sed -i -e 's/:.*$//' textfiles.txt
sed -i -e 's/\.\///' textfiles.txt

#write a script that deletes the files in textfiles.txt
IFS_backup=$IFS
IFS=$(echo "\n\b")
for f in $(cat textfiles.txt); 
do 
rm "$f"; 
done
IFS=$IFS_backup

# save script as "some.sh" and run: sh some.sh

Express.js req.body undefined

Most of the time req.body is undefined due to missing JSON parser

const express = require('express');
app.use(express.json());

could be missing for the body-parser

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

and sometimes it's undefined due to cros origin so add them

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

How do I change the owner of a SQL Server database?

To change database owner:

ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa

As of SQL Server 2014 you can still use sp_changedbowner as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.

Ignore Duplicates and Create New List of Unique Values in Excel

In my case the excel was frozen when using the formula of

B2=INDEX($A$2:$A$20, MATCH(0, COUNTIF($B$1:B1, $A$2:$A$20), 0))

because there was many rows (10000). So I did in another way which I show below.

I have copied my original list to a second column and then with the function of Excel "remove duplicates" I could find the list of unique values.

Copied from Microsoft Office Website:

Select all the rows, including the column headers, in the list 

you want to filter.

Click the top left cell of the range, and then drag to the bottom right cell.

On the Data menu, point to Filter, and then click Advanced Filter.
In the Advanced Filter dialog box, click Filter the list, in place.
Select the Unique records only check box, and then click OK.

The filtered list is displayed and the duplicate rows are hidden.

On the Edit menu, click Office Clipboard.

The Clipboard task pane is displayed.

Make sure the filtered list is still selected, and then click Copy Copy button.

The filtered list is highlighted with bounding outlines and the selection appears as an > > item at the top of the Clipboard.

On the Data menu, point to Filter, and then click Show All.

The original list is re-displayed.

Press the DELETE key.

The original list is deleted.

In the Clipboard, click on the filtered list item.

The filtered list appears in the same location as the original list.

Source: Microsoft Office Website (link removed, cause dead)

Possible to view PHP code of a website?

Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.

If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.

Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.

How to split a string and assign it to variables

package main

import (
    "fmt"
    "strings"
)

func main() {
    strs := strings.Split("127.0.0.1:5432", ":")
    ip := strs[0]
    port := strs[1]
    fmt.Println(ip, port)
}

Here is the definition for strings.Split

// Split slices s into all substrings separated by sep and returns a slice of
// the substrings between those separators.
//
// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.
//
// If sep is empty, Split splits after each UTF-8 sequence. If both s
// and sep are empty, Split returns an empty slice.
//
// It is equivalent to SplitN with a count of -1.
func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }

How to check if a json key exists?

just before read key check it like before read

JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
  //it's contain value to be read operation
}
else
{
  //it's not contain key club or isnull so do this operation here
}

isNull function definition

Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL. 

official documentation below link for isNull function

http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)

How to convert a String to Bytearray

In C# running this

UnicodeEncoding encoding = new UnicodeEncoding();
byte[] bytes = encoding.GetBytes("Hello");

Will create an array with

72,0,101,0,108,0,108,0,111,0

byte array

For a character which the code is greater than 255 it will look like this

byte array

If you want a very similar behavior in JavaScript you can do this (v2 is a bit more robust solution, while the original version will only work for 0x00 ~ 0xff)

_x000D_
_x000D_
var str = "Hello?";_x000D_
var bytes = []; // char codes_x000D_
var bytesv2 = []; // char codes_x000D_
_x000D_
for (var i = 0; i < str.length; ++i) {_x000D_
  var code = str.charCodeAt(i);_x000D_
  _x000D_
  bytes = bytes.concat([code]);_x000D_
  _x000D_
  bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);_x000D_
}_x000D_
_x000D_
// 72, 101, 108, 108, 111, 31452_x000D_
console.log('bytes', bytes.join(', '));_x000D_
_x000D_
// 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 220, 122_x000D_
console.log('bytesv2', bytesv2.join(', '));
_x000D_
_x000D_
_x000D_

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Set cookie and get cookie with JavaScript

These are much much better references than w3schools (the most awful web reference ever made):

Examples derived from these references:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

The view or its master was not found or no view engine supports the searched locations

I couldn't find any solution to this problem, until I found out the files didn't exist! This took me a long time to figure out, because the Solution Explorer shows the files!

enter image description here

But when I click on Index.cshtml I get this error:

enter image description here

So that was the reason for this error to show. I hope this answer helps somebody.

Laravel 5 call a model function in a blade view

In new version of Laravel you can use "Service Injection".

https://laravel.com/docs/5.8/blade#service-injection

/resources/views/main.blade.php

@inject('project', 'App\Project')

<h1>{{ $project->get_title() }}</h1>

Microsoft Excel mangles Diacritics in .csv files?

Echo UTF-8 BOM before outputing CSV data. This fixes all character issues in Windows but doesnt work for Mac.

echo "\xEF\xBB\xBF";

It works for me because I need to generate a file which will be used on Windows PCs only.

Why I get 411 Length required error?

you need to add Content-Length: 0 in your request header.

a very descriptive example of how to test is given here

How to access to a child method from the parent in vue.js

To communicate a child component with another child component I've made a method in parent which calls a method in a child with:

this.$refs.childMethod()

And from the another child I've called the root method:

this.$root.theRootMethod()

It worked for me.

Hide element by class in pure Javascript

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').fadeOut('slow');

        });
    </script>

or

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').hide();

        });
    </script>

Java generating non-repeating random numbers

If you're using JAVA 8 or more than use stream functionality following way,

Stream.generate(() -> (new Random()).nextInt(10000)).distinct().limit(10000);

Efficient SQL test query or validation query that will work across all (or most) databases

I use this one:

select max(table_catalog) as x from information_schema.tables

to check connection and ability to run queries (with 1 row as result) for postgreSQL, MySQL and MSSQL.

how to take user input in Array using java?

int length;
    Scanner input = new Scanner(System.in);
    System.out.println("How many numbers you wanna enter?");
    length = input.nextInt();
    System.out.println("Enter " + length + " numbers, one by one...");
    int[] arr = new int[length];
    for (int i = 0; i < arr.length; i++) {
        System.out.println("Enter the number " + (i + 1) + ": ");
        //Below is the way to collect the element from the user
        arr[i] = input.nextInt();

        // auto generate the elements
        //arr[i] = (int)(Math.random()*100);
    }
    input.close();
    System.out.println(Arrays.toString(arr));

SQL - Update multiple records in one query

Try either multi-table update syntax

UPDATE config t1 JOIN config t2
    ON t1.config_name = 'name1' AND t2.config_name = 'name2'
   SET t1.config_value = 'value',
       t2.config_value = 'value2';

Here is SQLFiddle demo

or conditional update

UPDATE config
   SET config_value = CASE config_name 
                      WHEN 'name1' THEN 'value' 
                      WHEN 'name2' THEN 'value2' 
                      ELSE config_value
                      END
 WHERE config_name IN('name1', 'name2');

Here is SQLFiddle demo

How do I tell Gradle to use specific JDK version?

For windows run gradle task with jdk 11 path parameter in quotes

gradlew clean build -Dorg.gradle.java.home="c:/Program Files/Java/jdk-11"

How long to brute force a salted SHA-512 hash? (salt provided)

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.

SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.

To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take

2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years

Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.

So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.

Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.

What is the difference between #import and #include in Objective-C?

In may case I had a global variable in one of my .h files that was causing the problem, and I solved it by adding extern in front of it.

WCF timeout exception detailed investigation

If you are using .Net client then you may not have set

//This says how many outgoing connection you can make to a single endpoint. Default Value is 2
System.Net.ServicePointManager.DefaultConnectionLimit = 200;

here is the original question and answer WCF Service Throttling

Update:

This config goes in .Net client application may be on start up or whenever but before starting your tests.

Moreover you can have it in app.config file as well like following

<system.net>
    <connectionManagement>
      <add maxconnection = "200" address ="*" />
    </connectionManagement>
  </system.net>

Use getElementById on HTMLElement instead of HTMLDocument

I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Set elements = .querySelectorAll(".profile-col1")
        For i = 0 To elements.Length - 1
            Debug.Print String(20, Chr$(61))
            Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
        Next
    End With
End Sub

References:

VBE > Tools > References > Microsoft HTML Object Library

How to make grep only match if the entire line matches?

I'd prefer:

str="ABB.log"; grep -E "^${str}$" a.tmp

cheers

How do I programmatically get the GUID of an application in .NET 2.0

You should be able to read the GUID attribute of the assembly via reflection. This will get the GUID for the current assembly

Assembly asm = Assembly.GetExecutingAssembly();
var attribs = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
Console.WriteLine((attribs[0] as GuidAttribute).Value);

You can replace the GuidAttribute with other attributes as well, if you want to read things like AssemblyTitle, AssemblyVersion, etc.

You can also load another assembly (Assembly.LoadFrom and all) instead of getting the current assembly - if you need to read these attributes of external assemblies (for example, when loading a plugin).

clientHeight/clientWidth returning different values on different browsers

It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.

Git "error: The branch 'x' is not fully merged"

You can simply figure out :

git log --cherry master...experimental

--cherry option is a synonym for --right-only --cherry-mark --no-merges

git-log man page said

it's useful to limit the output to the commits on our side and mark those that have been applied to the other side of a forked history with git log --cherry upstream...mybranch, similar to git cherry upstream mybranch.

FYI. --cherry-pick omits equivalent commits but --cherry-marks doesn't. It's useful to find rebase and force updated changes between upstream and co-working public branch

Detect URLs in text with JavaScript

Based on Crescent Fresh answer

if you want to detect links with http:// OR without http:// and by www. you can use the following

function urlify(text) {
    var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
    //var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url,b,c) {
        var url2 = (c == 'www.') ?  'http://' +url : url;
        return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
    }) 
}

How to generate entire DDL of an Oracle schema (scriptable)?

The get_ddl procedure for a PACKAGE will return both spec AND body, so it will be better to change the query on the all_objects so the package bodies are not returned on the select.

So far I changed the query to this:

SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type, ' ', '_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1')
and object_type not like '%PARTITION'
and object_type not like '%BODY'
order by object_type, object_name;

Although other changes might be needed depending on the object types you are getting...

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

Displaying the build date

Lots of great answers here but I feel like I can add my own because of simplicity, performance (comparing to resource-related solutions) cross platform (works with Net Core too) and avoidance of any 3rd party tool. Just add this msbuild target to the csproj.

<Target Name="Date" BeforeTargets="CoreCompile">
    <WriteLinesToFile File="$(IntermediateOutputPath)gen.cs" Lines="static partial class Builtin { public static long CompileTime = $([System.DateTime]::UtcNow.Ticks) %3B }" Overwrite="true" />
    <ItemGroup>
        <Compile Include="$(IntermediateOutputPath)gen.cs" />
    </ItemGroup>
</Target>

and now you have Builtin.CompileTime or new DateTime(Builtin.CompileTime, DateTimeKind.Utc) if you need it that way.

ReSharper is not gonna like it. You can ignore him or add a partial class to the project too but it works anyway.

laravel foreach loop in controller

Hi, this will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}

because you cannot loop a model with a specific column ($product->sku) from the table.
So you must loop on the whole model:

foreach ($product as $p) {
// code
}

Inside the loop you can retrieve whatever column you want just adding "->[column_name]"

foreach ($product as $p) {
echo $p->sku;
}

Have a great day

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

Simple css:

input[value]:not([value=""])

This code is going to apply the given css on page load if the input is filled up.

Is it possible to use argsort in descending order?

Instead of using np.argsort you could use np.argpartition - if you only need the indices of the lowest/highest n elements.

That doesn't require to sort the whole array but just the part that you need but note that the "order inside your partition" is undefined, so while it gives the correct indices they might not be correctly ordered:

>>> avgDists = [1, 8, 6, 9, 4]
>>> np.array(avgDists).argpartition(2)[:2]  # indices of lowest 2 items
array([0, 4], dtype=int64)

>>> np.array(avgDists).argpartition(-2)[-2:]  # indices of highest 2 items
array([1, 3], dtype=int64)

How to get the current directory in a C program?

Look up the man page for getcwd.

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

Calculate date/time difference in java

Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.

By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.

executing a function in sql plus

As another answer already said, call select myfunc(:y) from dual; , but you might find declaring and setting a variable in sqlplus a little tricky:

sql> var y number

sql> begin
  2  select 7 into :y from dual;
  3  end;
  4  /

PL/SQL procedure successfully completed.

sql> print :y

         Y
----------
         7

sql> select myfunc(:y) from dual;

Laravel 5 Class 'form' not found

Begin by installing this package through Composer. Run the following from the terminal:

composer require "laravelcollective/html":"^5.3.0"

Next, add your new provider to the providers array of config/app.php:

'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
  ],

Finally, add two class aliases to the aliases array of config/app.php:

'aliases' => [
    // ...
      'Form' => Collective\Html\FormFacade::class,
      'Html' => Collective\Html\HtmlFacade::class,
    // ...
  ],

SRC:

https://laravelcollective.com/docs/5.3/html

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

For Chrome:

  1. Set your email manager to Gmail

gmail handler

  1. Write mailto: in the address bar and press enter.

Easier:

  1. Edit search engines:

Edit search engines

Edit search engines

  1. Write mt and enter in address bar.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What do you mean timestamp? If you mean milliseconds since the Unix epoch:

GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();

If you want an actual java.sql.Timestamp object:

Timestamp ts = new Timestamp(millis);

Date validation with ASP.NET validator

Best option would be

Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:

<asp:CompareValidator
    id="dateValidator" runat="server" 
    Type="Date"
    Operator="DataTypeCheck"
    ControlToValidate="txtDatecompleted" 
    ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>

MySQL search and replace some text in a field

 UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);

Like for example, if I want to replace all occurrences of John by Mark I will use below,

UPDATE student SET student_name = replace(student_name, 'John', 'Mark');

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Prevent text selection after double click

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

How do I write dispatch_after GCD in Swift 3, 4, and 5?

Swift 4:

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
   // Code
}

For the time .seconds(Int), .microseconds(Int) and .nanoseconds(Int) may also be used.

Display more Text in fullcalendar

as a possible solution: Add some extra more content to the title. Overwrite this css style:

 .fc-day-grid-event .fc-content {
   white-space: normal; 
}

Today`s date in an excel macro

Here's an example that puts the Now() value in column A.

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)

How to serve up images in Angular2?

I am using the Asp.Net Core angular template project with an Angular 4 front end and webpack. I had to use '/dist/assets/images/' in front of the image name, and store the image in the assets/images directory in the dist directory. eg:

 <img  class="img-responsive" src="/dist/assets/images/UnitBadge.jpg">

Is there a function in python to split a word into a list?

>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

Check the below lines are present in your web.config file

<system.web> <httpRuntime requestPathInvalidCharacters="" /> </system.web>

invalid types 'int[int]' for array subscript

You're trying to access a 3 dimensional array with 4 de-references

You only need 3 loops instead of 4, or int myArray[10][10][10][10];

How to use the switch statement in R functions?

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply changes.

do.this <- "T1"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)

Here it is inside a function:

FUN <- function(df, do.this){
    switch(do.this,
        T1={X <- t(df)
            P <- colSums(df)%*%X
        },
        T2={X <- colMeans(df)
            P <- outer(X, X)
        },
        stop("Enter something that switches me!")
    )
    return(P)
}

FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")

How do AX, AH, AL map onto EAX?

The below snippet examines EAX using GDB.

    (gdb) info register eax
    eax            0xaa55   43605
    (gdb) info register ax
    ax             0xaa55   -21931
    (gdb) info register ah
    ah             0xaa -86
    (gdb) info register al
    al             0x55 85
  1. EAX - Full 32 bit value
  2. AX - lower 16 bit value
  3. AH - Bits from 8 to 15
  4. AL - lower 8 bits of EAX/AX

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

How to write a:hover in inline CSS?

using Javascript:

a) Adding inline style

document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');

b) or a bit harder method - adding "mouseover"

document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };

Note: multi-word styles (i.e.font-size) in Javascript are written together:

element.style.fontSize="12px"

symfony2 : failed to write cache directory

Most likely it means that the directory and/or sub-directories are not writable. Many forget about sub-directories.

Symfony 2

chmod -R 777 app/cache app/logs

Symfony 3 directory structure

chmod -R 777 var/cache var/logs

Additional Resources

Permissions solution by Symfony (mentioned previously).

Permissions solution by KPN University - additionally includes an screen-cast on installation.

Note: If you're using Symfony 3 directory structure, substitute app/cache and app/logs with var/cache and var/logs.

View content of H2 or HSQLDB in-memory database

For HSQLDB, The following worked for me:

DatabaseManager.threadedDBM();

And this brought up the GUI with my tables and data once I pointed it to the right named in-mem database.

It is basically the equivalent of newing up a DatabaseManager (the non Swing variety), which prompts for connection details, and is set to --noexit)

I also tried the Swing version, but it only had a main, and I was unsure of the arguments to pass. If anyone knows, please post here.

Just because I searched for hours for the right database name: The name of the database is the name of your datasource. So try with URL jdbc:hsqldb:mem:dataSource if you have a data source bean with id=dataSource. If this does not work, try testdb which is the default.

How to redirect page after click on Ok button on sweet alert?

I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:

<script>    
          sweetAlert({
                title:'Warning!',
                text: 'Invalid user or password!',
                type:'warning'
          },function(isConfirm){
                alert('ok');
          });
          $('.swal2-confirm').click(function(){
                window.location.href = 'index.php';
          });
</script>

The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...

So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...

Hope this helps you all !

PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !

Where can I download Eclipse Android bundle?

Try www.eclipse.org/downloads/packages/eclipse-android-developers-includes-incubating-components/neonrc3

Extracting time from POSIXct

Here's an update for those looking for a tidyverse method to extract hh:mm::ss.sssss from a POSIXct object. Note that time zone is not included in the output.

library(hms)
as_hms(times)

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

Return current date plus 7 days

$now = date('Y-m-d');
$start_date = strtotime($now);
$end_date = strtotime("+7 day", $start_date);
echo date('Y-m-d', $start_date) . '  + 7 days =  ' . date('Y-m-d', $end_date);

What is a correct MIME type for .docx, .pptx, etc.?

A working method in android to populates the mapping list mime types.

private static void fileMimeTypeMapping() {
     MIMETYPE_MAPPING.put("3gp", Collections.list("video/3gpp"));
     MIMETYPE_MAPPING.put("7z", Collections.list("application/x-7z-compressed"));
     MIMETYPE_MAPPING.put("accdb", Collections.list("application/msaccess"));
     MIMETYPE_MAPPING.put("ai", Collections.list("application/illustrator"));
     MIMETYPE_MAPPING.put("apk", Collections.list("application/vnd.android.package-archive"));
     MIMETYPE_MAPPING.put("arw", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("avi", Collections.list("video/x-msvideo"));
     MIMETYPE_MAPPING.put("bash", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("bat", Collections.list("application/x-msdos-program"));
     MIMETYPE_MAPPING.put("blend", Collections.list("application/x-blender"));
     MIMETYPE_MAPPING.put("bin", Collections.list("application/x-bin"));
     MIMETYPE_MAPPING.put("bmp", Collections.list("image/bmp"));
     MIMETYPE_MAPPING.put("bpg", Collections.list("image/bpg"));
     MIMETYPE_MAPPING.put("bz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("cb7", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cba", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbr", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbt", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbtc", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cbz", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("cc", Collections.list("text/x-c"));
     MIMETYPE_MAPPING.put("cdr", Collections.list("application/coreldraw"));
     MIMETYPE_MAPPING.put("class", Collections.list("application/java"));
     MIMETYPE_MAPPING.put("cnf", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("conf", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("cpp", Collections.list("text/x-c++src"));
     MIMETYPE_MAPPING.put("cr2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("css", Collections.list("text/css"));
     MIMETYPE_MAPPING.put("csv", Collections.list("text/csv"));
     MIMETYPE_MAPPING.put("cvbdl", Collections.list("application/x-cbr"));
     MIMETYPE_MAPPING.put("c", Collections.list("text/x-c"));
     MIMETYPE_MAPPING.put("c++", Collections.list("text/x-c++src"));
     MIMETYPE_MAPPING.put("dcr", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("deb", Collections.list("application/x-deb"));
     MIMETYPE_MAPPING.put("dng", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("doc", Collections.list("application/msword"));
     MIMETYPE_MAPPING.put("docm", Collections.list("application/vnd.ms-word.document.macroEnabled.12"));
     MIMETYPE_MAPPING.put("docx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
     MIMETYPE_MAPPING.put("dot", Collections.list("application/msword"));
     MIMETYPE_MAPPING.put("dotx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.template"));
     MIMETYPE_MAPPING.put("dv", Collections.list("video/dv"));
     MIMETYPE_MAPPING.put("eot", Collections.list("application/vnd.ms-fontobject"));
     MIMETYPE_MAPPING.put("epub", Collections.list("application/epub+zip"));
     MIMETYPE_MAPPING.put("eps", Collections.list("application/postscript"));
     MIMETYPE_MAPPING.put("erf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("exe", Collections.list("application/x-ms-dos-executable"));
     MIMETYPE_MAPPING.put("flac", Collections.list("audio/flac"));
     MIMETYPE_MAPPING.put("flv", Collections.list("video/x-flv"));
     MIMETYPE_MAPPING.put("gif", Collections.list("image/gif"));
     MIMETYPE_MAPPING.put("gpx", Collections.list("application/gpx+xml"));
     MIMETYPE_MAPPING.put("gz", Collections.list("application/gzip"));
     MIMETYPE_MAPPING.put("gzip", Collections.list("application/gzip"));
     MIMETYPE_MAPPING.put("h", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("heic", Collections.list("image/heic"));
     MIMETYPE_MAPPING.put("heif", Collections.list("image/heif"));
     MIMETYPE_MAPPING.put("hh", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("hpp", Collections.list("text/x-h"));
     MIMETYPE_MAPPING.put("htaccess", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("ical", Collections.list("text/calendar"));
     MIMETYPE_MAPPING.put("ics", Collections.list("text/calendar"));
     MIMETYPE_MAPPING.put("iiq", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("impress", Collections.list("text/impress"));
     MIMETYPE_MAPPING.put("java", Collections.list("text/x-java-source"));
     MIMETYPE_MAPPING.put("jp2", Collections.list("image/jp2"));
     MIMETYPE_MAPPING.put("jpeg", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("jpg", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("jps", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("k25", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("kdc", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("key", Collections.list("application/x-iwork-keynote-sffkey"));
     MIMETYPE_MAPPING.put("keynote", Collections.list("application/x-iwork-keynote-sffkey"));
     MIMETYPE_MAPPING.put("kml", Collections.list("application/vnd.google-earth.kml+xml"));
     MIMETYPE_MAPPING.put("kmz", Collections.list("application/vnd.google-earth.kmz"));
     MIMETYPE_MAPPING.put("kra", Collections.list("application/x-krita"));
     MIMETYPE_MAPPING.put("ldif", Collections.list("text/x-ldif"));
     MIMETYPE_MAPPING.put("love", Collections.list("application/x-love-game"));
     MIMETYPE_MAPPING.put("lwp", Collections.list("application/vnd.lotus-wordpro"));
     MIMETYPE_MAPPING.put("m2t", Collections.list("video/mp2t"));
     MIMETYPE_MAPPING.put("m3u", Collections.list("audio/mpegurl"));
     MIMETYPE_MAPPING.put("m3u8", Collections.list("audio/mpegurl"));
     MIMETYPE_MAPPING.put("m4a", Collections.list("audio/mp4"));
     MIMETYPE_MAPPING.put("m4b", Collections.list("audio/m4b"));
     MIMETYPE_MAPPING.put("m4v", Collections.list("video/mp4"));
     MIMETYPE_MAPPING.put("markdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("md", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mdb", Collections.list("application/msaccess"));
     MIMETYPE_MAPPING.put("mdwn", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mkd", Collections.list(MIMETYPE_TEXT_MARKDOWN));
     MIMETYPE_MAPPING.put("mef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("mkv", Collections.list("video/x-matroska"));
     MIMETYPE_MAPPING.put("mobi", Collections.list("application/x-mobipocket-ebook"));
     MIMETYPE_MAPPING.put("mov", Collections.list("video/quicktime"));
     MIMETYPE_MAPPING.put("mp3", Collections.list("audio/mpeg"));
     MIMETYPE_MAPPING.put("mp4", Collections.list("video/mp4"));
     MIMETYPE_MAPPING.put("mpeg", Collections.list("video/mpeg"));
     MIMETYPE_MAPPING.put("mpg", Collections.list("video/mpeg"));
     MIMETYPE_MAPPING.put("mpo", Collections.list("image/jpeg"));
     MIMETYPE_MAPPING.put("msi", Collections.list("application/x-msi"));
     MIMETYPE_MAPPING.put("mts", Collections.list("video/MP2T"));
     MIMETYPE_MAPPING.put("mt2s", Collections.list("video/MP2T"));
     MIMETYPE_MAPPING.put("nef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("numbers", Collections.list("application/x-iwork-numbers-sffnumbers"));
     MIMETYPE_MAPPING.put("odf", Collections.list("application/vnd.oasis.opendocument.formula"));
     MIMETYPE_MAPPING.put("odg", Collections.list("application/vnd.oasis.opendocument.graphics"));
     MIMETYPE_MAPPING.put("odp", Collections.list("application/vnd.oasis.opendocument.presentation"));
     MIMETYPE_MAPPING.put("ods", Collections.list("application/vnd.oasis.opendocument.spreadsheet"));
     MIMETYPE_MAPPING.put("odt", Collections.list("application/vnd.oasis.opendocument.text"));
     MIMETYPE_MAPPING.put("oga", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("ogg", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("ogv", Collections.list("video/ogg"));
     MIMETYPE_MAPPING.put("one", Collections.list("application/msonenote"));
     MIMETYPE_MAPPING.put("opus", Collections.list("audio/ogg"));
     MIMETYPE_MAPPING.put("orf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("otf", Collections.list("application/font-sfnt"));
     MIMETYPE_MAPPING.put("pages", Collections.list("application/x-iwork-pages-sffpages"));
     MIMETYPE_MAPPING.put("pdf", Collections.list("application/pdf"));
     MIMETYPE_MAPPING.put("pfb", Collections.list("application/x-font"));
     MIMETYPE_MAPPING.put("pef", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("php", Collections.list("application/x-php"));
     MIMETYPE_MAPPING.put("pl", Collections.list("application/x-perl"));
     MIMETYPE_MAPPING.put("pls", Collections.list("audio/x-scpls"));
     MIMETYPE_MAPPING.put("png", Collections.list("image/png"));
     MIMETYPE_MAPPING.put("pot", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("potm", Collections.list("application/vnd.ms-powerpoint.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("potx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.template"));
     MIMETYPE_MAPPING.put("ppa", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("ppam", Collections.list("application/vnd.ms-powerpoint.addin.macroEnabled.12"));
     MIMETYPE_MAPPING.put("pps", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("ppsm", Collections.list("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"));
     MIMETYPE_MAPPING.put("ppsx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.slideshow"));
     MIMETYPE_MAPPING.put("ppt", Collections.list("application/vnd.ms-powerpoint"));
     MIMETYPE_MAPPING.put("pptm", Collections.list("application/vnd.ms-powerpoint.presentation.macroEnabled.12"));
     MIMETYPE_MAPPING.put("pptx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
     MIMETYPE_MAPPING.put("ps", Collections.list("application/postscript"));
     MIMETYPE_MAPPING.put("psd", Collections.list("application/x-photoshop"));
     MIMETYPE_MAPPING.put("py", Collections.list("text/x-python"));
     MIMETYPE_MAPPING.put("raf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("rar", Collections.list("application/x-rar-compressed"));
     MIMETYPE_MAPPING.put("reveal", Collections.list("text/reveal"));
     MIMETYPE_MAPPING.put("rss", Collections.list("application/rss+xml"));
     MIMETYPE_MAPPING.put("rtf", Collections.list("application/rtf"));
     MIMETYPE_MAPPING.put("rw2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("schema", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("sgf", Collections.list("application/sgf"));
     MIMETYPE_MAPPING.put("sh-lib", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("sh", Collections.list("text/x-shellscript"));
     MIMETYPE_MAPPING.put("srf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("sr2", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("tar", Collections.list("application/x-tar"));
     MIMETYPE_MAPPING.put("tar.bz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("tar.gz", Collections.list("application/x-compressed"));
     MIMETYPE_MAPPING.put("tbz2", Collections.list("application/x-bzip2"));
     MIMETYPE_MAPPING.put("tcx", Collections.list("application/vnd.garmin.tcx+xml"));
     MIMETYPE_MAPPING.put("tex", Collections.list("application/x-tex"));
     MIMETYPE_MAPPING.put("tgz", Collections.list("application/x-compressed"));
     MIMETYPE_MAPPING.put("tiff", Collections.list("image/tiff"));
     MIMETYPE_MAPPING.put("tif", Collections.list("image/tiff"));
     MIMETYPE_MAPPING.put("ttf", Collections.list("application/font-sfnt"));
     MIMETYPE_MAPPING.put("txt", Collections.list("text/plain"));
     MIMETYPE_MAPPING.put("vcard", Collections.list("text/vcard"));
     MIMETYPE_MAPPING.put("vcf", Collections.list("text/vcard"));
     MIMETYPE_MAPPING.put("vob", Collections.list("video/dvd"));
     MIMETYPE_MAPPING.put("vsd", Collections.list("application/vnd.visio"));
     MIMETYPE_MAPPING.put("vsdm", Collections.list("application/vnd.ms-visio.drawing.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vsdx", Collections.list("application/vnd.ms-visio.drawing"));
     MIMETYPE_MAPPING.put("vssm", Collections.list("application/vnd.ms-visio.stencil.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vssx", Collections.list("application/vnd.ms-visio.stencil"));
     MIMETYPE_MAPPING.put("vstm", Collections.list("application/vnd.ms-visio.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("vstx", Collections.list("application/vnd.ms-visio.template"));
     MIMETYPE_MAPPING.put("wav", Collections.list("audio/wav"));
     MIMETYPE_MAPPING.put("webm", Collections.list("video/webm"));
     MIMETYPE_MAPPING.put("woff", Collections.list("application/font-woff"));
     MIMETYPE_MAPPING.put("wpd", Collections.list("application/vnd.wordperfect"));
     MIMETYPE_MAPPING.put("wmv", Collections.list("video/x-ms-wmv"));
     MIMETYPE_MAPPING.put("xcf", Collections.list("application/x-gimp"));
     MIMETYPE_MAPPING.put("xla", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xlam", Collections.list("application/vnd.ms-excel.addin.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xls", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xlsb", Collections.list("application/vnd.ms-excel.sheet.binary.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xlsm", Collections.list("application/vnd.ms-excel.sheet.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xlsx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
     MIMETYPE_MAPPING.put("xlt", Collections.list("application/vnd.ms-excel"));
     MIMETYPE_MAPPING.put("xltm", Collections.list("application/vnd.ms-excel.template.macroEnabled.12"));
     MIMETYPE_MAPPING.put("xltx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.template"));
     MIMETYPE_MAPPING.put("xrf", Collections.list("image/x-dcraw"));
     MIMETYPE_MAPPING.put("yaml", Arrays.asList("application/yaml", "text/plain"));
     MIMETYPE_MAPPING.put("yml", Arrays.asList("application/yaml", "text/plain"));
     MIMETYPE_MAPPING.put("zip", Collections.list("application/zip"));
     MIMETYPE_MAPPING.put("url", Collections.list("application/internet-shortcut"));
     MIMETYPE_MAPPING.put("webloc", Collections.list("application/internet-shortcut"));
     MIMETYPE_MAPPING.put("js", Arrays.asList("application/javascript", "text/plain"));
     MIMETYPE_MAPPING.put("json", Arrays.asList("application/json", "text/plain"));
     MIMETYPE_MAPPING.put("fb2", Arrays.asList("application/x-fictionbook+xml", "text/plain"));
     MIMETYPE_MAPPING.put("html", Arrays.asList("text/html", "text/plain"));
     MIMETYPE_MAPPING.put("htm", Arrays.asList("text/html", "text/plain"));
     MIMETYPE_MAPPING.put("m", Arrays.asList("text/x-matlab", "text/plain"));
     MIMETYPE_MAPPING.put("svg", Arrays.asList("image/svg+xml", "text/plain"));
     MIMETYPE_MAPPING.put("swf", Arrays.asList("application/x-shockwave-flash", "application/octet-stream"));
     MIMETYPE_MAPPING.put("xml", Arrays.asList("application/xml", "text/plain"));

}

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

SSRS chart does not show all labels on Horizontal axis

It looks as though the horizontal axis (Category Group) labels have very long values - there may not be room to display them all. I suggest changing the labels to have shorter values.

You can set the sort order for the Category Groups in the Category Group Properties - Sorting section - this may have been previously set; if not, I suggest using this to sort as desired.

How to save .xlsx data to file as a blob

The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.

Here's what I did on the server side (asp.net mvc core):

string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);

On the client side, I did the following code:

const xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");

xhr.onload = () => {
    var bin = atob(xhr.response);
    var ab = s2ab(bin); // from example above
    var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'demo.xlsx';

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
};

xhr.send();

And it works perfectly for me.

How to create an empty file at the command line in Windows?

Try this :abc > myFile.txt First, it will create a file with name myFile.txt in present working directory (in command prompt). Then it will run the command abc which is not a valid command. In this way, you have gotten a new empty file with the name myFile.txt.

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

In Servlet technology if you want to pass any input to a particular servlet then you need to pass in init param like below code.

 <servlet>
    <servlet-name>DBController</servlet-name>
    <servlet-class>com.test.controller.DBController</servlet-class>
    <init-param>
        <param-name>username</param-name>
        <param-value>John</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>DBController</servlet-name>
    <url-pattern>/DBController</url-pattern>
</servlet-mapping>

If you want to pass some in put that is common for all servlets then that time you need to configure context param. Example

 <context-param>
    <param-name>email</param-name>
    <param-value>[email protected]</param-value>
</context-param>

SO exactly like this when ever we are working with Spring MVC we need to provide some information to Predefined servlet provided by Spring that is DispatcherServlet through init param. So the configuration is as fallows, here we are providing the spring-servlet.xml as init parameter to DispatcherServlet.

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>Spring MVC App</display-name>

    <servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>

Again we need some context param. That is applicable for whole application. So we can provide the root context that is applicationcontext.xml The configuration is like this:

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationcontext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

Representing Directory & File Structure in Markdown Syntax

You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre> tag to preserve the plain text formatting.

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

So I'm not entirely sure why this works, but it saves an image with my plot:

dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')

I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.

Creating a very simple linked list

Dmytro did a good job, but here is a more concise version.

class Program
{
    static void Main(string[] args)
    {
        LinkedList linkedList = new LinkedList(1);

        linkedList.Add(2);
        linkedList.Add(3);
        linkedList.Add(4);

        linkedList.AddFirst(0);

        linkedList.Print();            
    }
}

public class Node
{
    public Node(Node next, Object value)
    {
        this.next = next;
        this.value = value;
    }

    public Node next;
    public Object value;
}

public class LinkedList
{
    public Node head;

    public LinkedList(Object initial)
    {
        head = new Node(null, initial);
    }

    public void AddFirst(Object value)
    {
        head = new Node(head, value);            
    }

    public void Add(Object value)
    {
        Node current = head;

        while (current.next != null)
        {
            current = current.next;
        }

        current.next = new Node(null, value);
    }

    public void Print()
    {
        Node current = head;

        while (current != null)
        {
            Console.WriteLine(current.value);
            current = current.next;
        }
    }
}

Unfortunately MyApp has stopped. How can I solve this?

Just check the error in log cat.

You get the log cat option from in eclipse:

window->show view->others->Android->Logcat

Log cat contains error.

Other wise you can also check the error by executing an application in debug mode. Firstly set breakpoint after that by doing:

right click on project->debug as->Android application

Add floating point value to android resources/values

As described in this link http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html

Declare in dimen.xml

<item name="my_float_value" type="dimen" format="float">9.52</item>

Referencing from xml

@dimen/my_float_value

Referencing from java

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

How can I create a text box for a note in markdown?

Similar to Etienne's solution, a simple table formats nicely:

| | |
|-|-|
|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|

Another alternative (which comes with more emphasis), is to make the content the header of a body-less table:

|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|
|-|-|

Finally, you can include a horizontal line (thematic break) to create a closed box (although the line style is a little different than the header line in the table):

| | |
|-|-|
|`NOTE` | This is something I want you to notice. It has a lot of text, and I want that text to wrap within a cell to the right of the `NOTE`, instead of under it.|

---

Note the empty line after the text.

$(document).ready shorthand

The shorthand is:

$(function() {
    // Code here
});

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

How to implement a Keyword Search in MySQL?

SELECT 
    *
FROM 
    yourtable
WHERE 
    id LIKE '%keyword%' 
    OR position LIKE '%keyword%'
    OR category LIKE '%keyword%'
    OR location LIKE '%keyword%'
    OR description LIKE '%keyword%'
    OR refno LIKE '%keyword%';

Convert String To date in PHP

For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.

$date = '05/Feb/2010:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
    $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
    $dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
    $dateInfo['is_dst']
);

Versions prior, this should work.

$date = '05/Feb/2010:14:00:01';
$format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
preg_match($format, $date, $dateInfo);
$unixTimestamp = mktime(
    $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
    date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
    date('I')
);

You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.

$day = $date[0].$date[1];
$month = date('n', strtotime($date[3].$date[4].$date[5]));
$year = $date[7].$date[8].$date[9].$date[10];
$hour = $date[12].$date[13];
$minute = $date[15].$date[16];
$second = $date[18].$date[19];

Or substr, or explode, whatever you wish to parse that string.

How to change Maven local repository in eclipse

In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at

Maven User Settings dialog

It's the second file input; the first with information in it.

If it's not clear, [redacted] should be replaced with the local file path to your .m2 folder.

If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.

If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              https://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>

You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.

Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>. See Maven — Settings Reference for more information.

Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.

If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings and <localRepository> should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.

I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.

C# Generics and Type Checking

How about this :

            // Checks to see if the value passed is valid. 
            if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
            {
                throw new ArgumentException();
            }

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

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

Should I use JSLint or JSHint JavaScript validation?

Foreword: Well, that escalated quickly. But decided to pull it through. May this answer be helpful to you and other readers.

I got a bit carried away here

Code Hinting

While JSLint and JSHint are good tools to use, over the years I've come to appreciate what my friend @ugly_syntax calls:

smaller design space.

This is a general principle, much like a "zen monk", limiting the choices one has to make, one can be more productive and creative.

Therefore my current favourite zero-config JS code style:

StandardJS.

UPDATE:

Flow has improved a lot. With it, you can add types to your JS with will help you prevent a lot of bugs. But it can also stay out of your way, for instance when interfacing untyped JS. Give it a try!

Quickstart / TL;DR

Add standard as a dependency to you project

npm install --save standard

Then in package.json, add the following test script:

"scripts": {
    "test": "node_modules/.bin/standard && echo put further tests here"
},

For snazzier output while developing, npm install --global snazzy and run it instead of npm test.

Note: Type checking versus Heuristics

My friend when mentioning design space referred to Elm and I encourage you to give that language a try.

Why? JS is in fact inspired by LISP, which is a special class of languages, which happens to be untyped. Language such as Elm or Purescript are typed functional programming languages.

Type restrict your freedom in order for the compiler to be able to check and guide you when you end up violation the language or your own program's rules; regardless of the size (LOC) of your program.

We recently had a junior colleague implement a reactive interface twice: once in Elm, once in React; have a look to get some idea of what I'm talking about.

Compare Main.elm (typed) ? index.js (untyped, no tests)

(ps. note that the React code is not idiomatic and could be improved)

One final remark,

the reality is that JS is untyped. Who am I to suggest typed programming to you?

See, with JS we are in a different domain: freed from types, we can easily express things that are hard or impossible to give a proper type (which can certainly be an advantage).

But without types there is little to keep our programs in check, so we are forced to introduce tests and (to a lesser extend) code styles.

I recommend you look at LISP (e.g. ClojureScript) for inspiration and invest in testing your codes. Read The way of the substack to get an idea.

Peace.

How to include (source) R script in other scripts

Here is one possible way. Use the exists function to check for something unique in your util.R code.

For example:

if(!exists("foo", mode="function")) source("util.R")

(Edited to include mode="function", as Gavin Simpson pointed out)

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

read complete file without using loop in java

Since Java 11 you can do it even simpler:

import java.nio.file.Files;

Files.readString(Path path);
Files.readString?(Path path, Charset cs)

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

jQuery find file extension (from string)

Since the extension will always be the string after a period in a complete/partial file name, just use the built in split function in js, and test the resultant extension for what you want it to do. If split returns only one piece / no pieces, it does not contain an extension.

What's the quickest way to multiply multiple cells by another number?

To multiply a column of numbers with a constant(same number), I have done like this.

Let C2 to C12 be different numbers which need to be multiplied by a single number (constant). Then type the numbers from C2 to C12.

In D2 type 1 (unity) and in E2 type formula =PRODUCT(C2:C12,CONSTANT). SELECT RIGHT ICON TO APPLY. NOW DRAG E2 THROUGH E12. YOU HAVE DONE IT.

C       D       E=PRODUCT(C2:C12,20)

25  1   500
30      600
35      700
40      800
45      900
50      1000
55      1100
60      1200
65      1300
70      1400
75      1500

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

async/await - when to return a Task vs void?

According to Microsoft documentation, should NEVER use async void

Do not do this: The following example uses async void which makes the HTTP request complete when the first await is reached:

  • Which is ALWAYS a bad practice in ASP.NET Core apps.

  • Accesses the HttpResponse after the HTTP request is complete.

  • Crashes the process.

List all employee's names and their managers by manager name using an inner join

Select e.lastname as employee ,m.lastname as manager
  from employees e,employees m
 where e.managerid=m.employyid(+)

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

Adding onClick event dynamically using jQuery

try this approach if you know your object client name ( it is not important that it is Button or TextBox )

$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');

try this ones if you want add onClick event to a server object with JQuery

$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

How to show matplotlib plots in python

plt.plot(X,y) function just draws the plot on the canvas. In order to view the plot, you have to specify plt.show() after plt.plot(X,y). So,

import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()

How do I remove a single file from the staging area (undo git add)?

If you want to remove files following a certain pattern and you are using git rm --cached, you can use file-glob patterns too.

See here.

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..

"Find next" in Vim

It is n for next and N for previous.

And if you use reverse search with ? (for example, ?cake) instead of /, it is the other way round.

If it is installed on your system, you should try to run vimtutor command from your terminal, which will start a tutorial of the basic Vim commands.

Rob Wells advice about * and # is also very pertinent.

Adjust width and height of iframe to fit with content in it

<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

window.addEventListener('DOMContentLoaded', function(e) {

    var iFrame = document.getElementById( 'iFrame1' );
    resizeIFrameToFitContent( iFrame );

    // or, to resize all iframes:
    var iframes = document.querySelectorAll("iframe");
    for( var i = 0; i < iframes.length; i++) {
        resizeIFrameToFitContent( iframes[i] );
    }
} );

</script>

<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>

How can I count the number of matches for a regex?

matcher.find() does not find all matches, only the next match.

Solution for Java 9+

long matches = matcher.results().count();

Solution for Java 8 and older

You'll have to do the following. (Starting from Java 9, there is a nicer solution)

int count = 0;
while (matcher.find())
    count++;

Btw, matcher.groupCount() is something completely different.

Complete example:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

Handling overlapping matches

When counting matches of aa in aaaa the above snippet will give you 2.

aaaa
aa
  aa

To get 3 matches, i.e. this behavior:

aaaa
aa
 aa
  aa

You have to search for a match at index <start of last match> + 1 as follows:

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3

Origin http://localhost is not allowed by Access-Control-Allow-Origin

I fixed this (for development) with a simple nginx proxy...

# /etc/nginx/sites-enabled/default
server {
  listen 80;
  root /path/to/Development/dir;
  index index.html;

  # from your example
  location /search {
    proxy_pass http://api.master18.tiket.com;
  }
}

What does the fpermissive flag do?

A common case for simply setting -fpermissive and not sweating it exists: the thoroughly-tested and working third-party library that won't compile on newer compiler versions without -fpermissive. These libraries exist, and are very likely not the application developer's problem to solve, nor in the developer's schedule budget to do it.

Set -fpermissive and move on in that case.

What is the easiest way to parse an INI file in Java?

It is just as simple as this.....

//import java.io.FileInputStream;
//import java.io.FileInputStream;

Properties prop = new Properties();
//c:\\myapp\\config.ini is the location of the ini file
//ini file should look like host=localhost
prop.load(new FileInputStream("c:\\myapp\\config.ini"));
String host = prop.getProperty("host");

Remove values from select list based on condition

If you are using JQuery, it goes as follows:

Give an ID to your SELECT

<select name="val" size="1" id="val">
<option value="A">Apple</option>
<option value="C">Cars</option>
<option value="H">Honda</option>
<option value="F">Fiat</option>
<option value="I">Indigo</option>                    
</select>

$("#val option[value='A'],#val option[value='C']").remove();

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

What is the path for the startup folder in windows 2008 server

SHGetKnownFolderPath:

Retrieves the full path of a known folder identified by the folder's KNOWNFOLDERID.

And, FOLDERID_CommonStartup:

Default Path %ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp

There are also managed equivalents, but you haven't told us what you're programming in.

Package php5 have no installation candidate (Ubuntu 16.04)

You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:

sudo apt-get install php5.6 php5.6-mcrypt

Closing Excel Application using VBA

Application.Quit 

Should do the trick.

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Posting parameters to a url using the POST method without using a form

You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.

ReactJS - Add custom event listener to component

If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:

Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.

class MovieItem extends React.Component {

  componentDidMount() {
    // When the component is mounted, add your DOM listener to the "nv" elem.
    // (The "nv" elem is assigned in the render function.)
    this.nv.addEventListener("nv-enter", this.handleNvEnter);
  }

  componentWillUnmount() {
    // Make sure to remove the DOM listener when the component is unmounted.
    this.nv.removeEventListener("nv-enter", this.handleNvEnter);
  }

  // Use a class arrow function (ES7) for the handler. In ES6 you could bind()
  // a handler in the constructor.
  handleNvEnter = (event) => {
    console.log("Nv Enter:", event);
  }

  render() {
    // Here we render a single <div> and toggle the "aria-nv-el-current" attribute
    // using the attribute spread operator. This way only a single <div>
    // is ever mounted and we don't have to worry about adding/removing
    // a DOM listener every time the current index changes. The attrs 
    // are "spread" onto the <div> in the render function: {...attrs}
    const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};

    // Finally, render the div using a "ref" callback which assigns the mounted 
    // elem to a class property "nv" used to add the DOM listener to.
    return (
      <div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">
        ...
      </div>
    );
  }

}

Example on Codepen.io

Read XML Attribute using XmlDocument

Assuming your example document is in the string variable doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1

How do I use a char as the case in a switch-case?

Here's an example:

public class Main {

    public static void main(String[] args) {

        double val1 = 100;
        double val2 = 10;
        char operation = 'd';
        double result = 0;

        switch (operation) {

            case 'a':
                result = val1 + val2; break;

            case 's':
                result = val1 - val2; break;
            case 'd':
                if (val2 != 0)
                    result = val1 / val2; break;
            case 'm':
                result = val1 * val2; break;

            default: System.out.println("Not a defined operation");


        }

        System.out.println(result);
    }
}

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Update int column in table with unique incrementing values

In oracle-based products you may use the following statement:

update table set interfaceID=RowNum where condition;

In PANDAS, how to get the index of a known value?

Using the .loc[] accessor:

In [25]: a.loc[a['c1'] == 8].index[0]
Out[25]: 4

Can also use the get_loc() by setting 'c1' as the index. This will not change the original dataframe.

In [17]: a.set_index('c1').index.get_loc(8)
Out[17]: 4

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Following are the results when we use both [MaxLength] and [StringLength] attributes, in EF code first. If both are used, [MaxLength] wins the race. See the test result in studentname column in below class

 public class Student
 {
    public Student () {}

    [Key]
    [Column(Order=1)]
    public int StudentKey { get; set; }

    //[MaxLength(50),StringLength(60)]    //studentname column will be nvarchar(50)
    //[StringLength(60)]    //studentname column will be nvarchar(60)
    [MaxLength(50)] //studentname column will be nvarchar(50)
    public string StudentName { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }
 }

Pdf.js: rendering a pdf file using a base64 file source instead of url

Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS

_x000D_
_x000D_
        Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
        convertDataURIToBinary: function(dataURI) {_x000D_
          var BASE64_MARKER = ';base64,',_x000D_
            base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
            base64 = dataURI.substring(base64Index),_x000D_
            raw = window.atob(base64),_x000D_
            rawLength = raw.length,_x000D_
            array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
          for (var i = 0; i < rawLength; i++) {_x000D_
            array[i] = raw.charCodeAt(i);_x000D_
          }_x000D_
          return array;_x000D_
        },
_x000D_
_x000D_
_x000D_

How do I restart a program based on user input?

I create this program:

import pygame, sys, time, random, easygui

skier_images = ["skier_down.png", "skier_right1.png",
                "skier_right2.png", "skier_left2.png",
                "skier_left1.png"]

class SkierClass(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("skier_down.png")
        self.rect = self.image.get_rect()
        self.rect.center = [320, 100]
        self.angle = 0

    def turn(self, direction):
        self.angle = self.angle + direction
        if self.angle < -2:  self.angle = -2
        if self.angle >  2:  self.angle =  2
        center = self.rect.center
        self.image = pygame.image.load(skier_images[self.angle])
        self.rect = self.image.get_rect()
        self.rect.center = center
        speed = [self.angle, 6 - abs(self.angle) * 2]
        return speed

    def move(self,speed):
        self.rect.centerx = self.rect.centerx + speed[0]
        if self.rect.centerx < 20:  self.rect.centerx = 20
        if self.rect.centerx > 620: self.rect.centerx = 620

class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self,image_file, location, type):
        pygame.sprite.Sprite.__init__(self)
        self.image_file = image_file
        self.image = pygame.image.load(image_file)
        self.location = location
        self.rect = self.image.get_rect()
        self.rect.center = location
        self.type = type
        self.passed = False

    def scroll(self, t_ptr):
        self.rect.centery = self.location[1] - t_ptr

def create_map(start, end):
    obstacles = pygame.sprite.Group()
    gates = pygame.sprite.Group()
    locations = []
    for i in range(10):
        row = random.randint(start, end)
        col = random.randint(0, 9)
        location = [col * 64 + 20, row * 64 + 20]
        if not (location in locations) :
            locations.append(location)
            type = random.choice(["tree", "flag"])
            if type == "tree": img = "skier_tree.png"
            elif type == "flag": img = "skier_flag.png"
            obstacle = ObstacleClass(img, location, type)
            obstacles.add(obstacle)
    return obstacles

def animate():
    screen.fill([255,255,255])
    pygame.display.update(obstacles.draw(screen))
    screen.blit(skier.image, skier.rect)
    screen.blit(score_text, [10,10])
    pygame.display.flip()

def updateObstacleGroup(map0, map1):
    obstacles = pygame.sprite.Group()
    for ob in map0:  obstacles.add(ob)
    for ob in map1:  obstacles.add(ob)
    return obstacles

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0
obstacles = updateObstacleGroup(map0, map1)
font = pygame.font.Font(None, 50)

a = True

while a:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed = skier.turn(-1)
            elif event.key == pygame.K_RIGHT:
                speed = skier.turn(1)
    skier.move(speed)
    map_position += speed[1]

    if map_position >= 640 and activeMap == 0:
        activeMap = 1
        map0 = create_map(20, 29)
        obstacles = updateObstacleGroup(map0, map1)
    if map_position >=1280 and activeMap == 1:
        activeMap = 0
        for ob in map0:
            ob.location[1] = ob.location[1] - 1280
        map_position = map_position - 1280
        map1 = create_map(10, 19)
        obstacles = updateObstacleGroup(map0, map1)
    for obstacle in obstacles:
        obstacle.scroll(map_position)

    hit = pygame.sprite.spritecollide(skier, obstacles, False)
    if hit:
        if hit[0].type == "tree" and not hit[0].passed:
            skier.image = pygame.image.load("skier_crash.png")
            easygui.msgbox(msg="OOPS!!!")
            choice = easygui.buttonbox("Do you want to play again?", "Play", ("Yes", "No"))
            if choice == "Yes":
                skier = SkierClass()
                speed = [0, 6]
                map_position = 0
                points = 0
                map0 = create_map(20, 29)
                map1 = create_map(10, 19)
                activeMap = 0
                obstacles = updateObstacleGroup(map0, map1)
            elif choice == "No":
                a = False
                quit()
        elif hit[0].type == "flag" and not hit[0].passed:
            points += 10
            obstacles.remove(hit[0])

    score_text = font.render("Score: " + str(points), 1, (0, 0, 0))
    animate()

Link: https://docs.google.com/document/d/1U8JhesA6zFE5cG1Ia3OsTL6dseq0Vwv_vuIr3kqJm4c/edit

Leaflet - How to find existing markers, and delete markers?

(1) add layer group and array to hold layers and reference to layers as global variables:

var search_group = new L.LayerGroup(); var clickArr = new Array();

(2) add map

(3) Add group layer to map

map.addLayer(search_group);

(4) the add to map function, with a popup that contains a link, which when clicked will have a remove option. This link will have, as its id the lat long of the point. This id will then be compared to when you click on one of your created markers and you want to delete it.

 map.on('click', function(e) {
        var clickPositionMarker = L.marker([e.latlng.lat,e.latlng.lng],{icon: idMarker});
        clickArr.push(clickPositionMarker);
        mapLat = e.latlng.lat;
        mapLon = e.latlng.lng;
        clickPositionMarker.addTo(search_group).bindPopup("<a name='removeClickM' id="+e.latlng.lat+"_"+e.latlng.lng+">Remove Me</a>")
                .openPopup();   

                /*   clickPositionMarker.on('click', function(e) {
                  markerDelAgain(); 
                }); */


});

(5) The remove function, compare the marker lat long to the id fired in the remove:

$(document).on("click","a[name='removeClickM']", function (e) {

      // Stop form from submitting normally
    e.preventDefault();

    for(i=0;i<clickArr.length;i++) {

    if(search_group.hasLayer(clickArr[i]))
    {
        if(clickArr[i]._latlng.lat+"_"+clickArr[i]._latlng.lng==$(this).attr('id'))
            {
                hideLayer(search_group,clickArr[i]);
                clickArr.splice(clickArr.indexOf(clickArr[i]), 1);
            }

    }

    }