Programs & Examples On #Paredit

Paredit is an emacs minor mode for controlled editing of s-expressions.

How to change the DataTable Column Name?

Use this

dataTable.Columns["OldColumnName"].ColumnName = "NewColumnName";

process.start() arguments

Not really a direct answer, but I'd highly recommend using LINQPad for this kind of "exploratory" C# programming.

I have the following as a saved "query" in LINQPad:

var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c echo Foo && echo Bar";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardOutput.ReadToEnd().Dump();

Feel free to adapt as needed.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Just type .htaccess. as filename. Notice the dot at the end of htaccess. This will change in Windows to .htaccess without a dot at the end.

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

Difference between Visibility.Collapsed and Visibility.Hidden

Even though a bit old thread, for those who still looking for the differences:

Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.

If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.

As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.

How to change current working directory using a batch file

Just use cd /d %root% to switch driver letters and change directories.

Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.

Note that pushd will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd for that directory.

How to get value of Radio Buttons?

For Win Forms :

To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:

string value = "";
bool isChecked = radioButton1.Checked;
if(isChecked )
  value=radioButton1.Text;
else
  value=radioButton2.Text;

For Web Forms :

<asp:RadioButtonList ID="rdoPriceRange" runat="server" RepeatLayout="Flow">
    <asp:ListItem Value="Male">Male</asp:ListItem>
    <asp:ListItem Value="Female">Female</asp:ListItem>
</asp:RadioButtonList>

And CS-in some button click

string value=rdoPriceRange.SelectedItem.Value.ToString();

How to convert a negative number to positive?

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10

PHP Unset Array value effect on other indexes

The keys are maintained with the removed key missing but they can be rearranged by doing this:

$array = array(1,2,3,4,5);
unset($array[2]);
$arranged = array_values($array);
print_r($arranged);

Outputs:

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 5
)

Notice that if we do the following without rearranging:

unset($array[2]);
$array[]=3;

The index of the value 3 will be 5 because it will be pushed to the end of the array and will not try to check or replace missing index. This is important to remember when using FOR LOOP with index access.

How to display my location on Google Maps for Android API v2

The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.

Google Documentation

The actual documentation that Google provides gives you your answer. You just need to

If you are using Kotlin

// map is a GoogleMap object
map.isMyLocationEnabled = true


If you are using Java

// map is a GoogleMap object
map.setMyLocationEnabled(true);

and watch the magic happen.

Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above

Connection pooling options with JDBC: DBCP vs C3P0

Here are some articles that show that DBCP has significantly higher performance than C3P0 or Proxool. Also in my own experience c3p0 does have some nice features, like prepared statement pooling and is more configurable than DBCP, but DBCP is plainly faster in any environment I have used it in.

Difference between dbcp and c3p0? Absolutely nothing! (A Sakai developers blog) http://blogs.nyu.edu/blogs/nrm216/sakaidelic/2007/12/difference_between_dbcp_and_c3.html

See also the like to the JavaTech article "Connection Pool Showdown" in the comments on the blog post.

Numpy: Divide each row by a vector element

As has been mentioned, slicing with None or with np.newaxes is a great way to do this. Another alternative is to use transposes and broadcasting, as in

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function. There really are a lot of ways to do this.

For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

What does 'super' do in Python?

The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.

However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

What are the file limits in Git (number and size)?

There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.

There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.

%find . -type f | wc -l
791887
%time git add .
git add .  6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status  0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G     .
%cd .git
%du -sh .
7.9G    .

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

The dll is missing in the published (deployed environment). That is the reason why it is working in the local i.e. Visual Studio but not in the Azure Website Environment.

Just do Copy Local = true in the properties for the assembly(System.Web.Http.WebHost) and then do a redeploy, it should work fine.

Count number of days between two dates

With the Date (and DateTime) classes you can do (end_date - start_date).to_i to get the number of days difference.

jackson deserialization json to java-objects

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

What you actually have is a List<product> To describe generic types, due to Java's type erasure, you must use a TypeReference. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

Datatable to html Table

public static string toHTML_Table(DataTable dt)
{
    if (dt.Rows.Count == 0) return ""; // enter code here

    StringBuilder builder = new StringBuilder();
    builder.Append("<html>");
    builder.Append("<head>");
    builder.Append("<title>");
    builder.Append("Page-");
    builder.Append(Guid.NewGuid());
    builder.Append("</title>");
    builder.Append("</head>");
    builder.Append("<body>");
    builder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    builder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
    builder.Append("<tr align='left' valign='top'>");
    foreach (DataColumn c in dt.Columns)
    {
        builder.Append("<td align='left' valign='top'><b>");
        builder.Append(c.ColumnName);
        builder.Append("</b></td>");
    }
    builder.Append("</tr>");
    foreach (DataRow r in dt.Rows)
    {
        builder.Append("<tr align='left' valign='top'>");
        foreach (DataColumn c in dt.Columns)
        {
            builder.Append("<td align='left' valign='top'>");
            builder.Append(r[c.ColumnName]);
            builder.Append("</td>");
        }
        builder.Append("</tr>");
    }
    builder.Append("</table>");
    builder.Append("</body>");
    builder.Append("</html>");

    return builder.ToString();
}

incompatible character encodings: ASCII-8BIT and UTF-8

I got the same cryptic error message from Rails 4.1, Ruby 2.3.3 in a recent project, stacktrace originating in layout application.html.haml

After a wild goose chase, the culprit was a UTF-8 character which recently had been added to the footer of all pages. For some weird reason the error would only show up intermittently.

Replacing the UTF-8 character with the corresponding HTML escape sequence &#xHHHH; solved the issue.

I hope this saves other people some time in the future..

Force IE compatibility mode off using tags

There is the "edge" mode.

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>My Web Page</title>
   </head>
   <body>
      <p>Content goes here.</p>
   </body>
</html>

From the linked MSDN page:

Edge mode tells Windows Internet Explorer to display content in the highest mode available, which actually breaks the “lock-in” paradigm. With Internet Explorer 8, this is equivalent to IE8 mode. If a (hypothetical) future release of Internet Explorer supported a higher compatibility mode, pages set to Edge mode would appear in the highest mode supported by that version; however, those same pages would still appear in IE8 mode when viewed with Internet Explorer 8.

However, "edge" mode is not encouraged in production use:

It is recommended that Web developers restrict their use of Edge mode to test pages and other non-production uses because of the possible unexpected results of rendering page content in future versions of Windows Internet Explorer.

I honestly don't entirely understand why. But according to this, the best way to go at the moment is using IE=8.

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

ScalaTest in sbt: is there a way to run a single test without tags?

This is now supported (since ScalaTest 2.1.3) within interactive mode:

testOnly *MySuite -- -z foo

to run only the tests whose name includes the substring "foo".

For exact match rather than substring, use -t instead of -z.

How to get folder path for ClickOnce application

Assuming the question is about accessing files in the application folder after the ClickOnce (true == System.Deployment.ApplicationDeploy.IsNetworkDeployed) application is installed on the user's PC, their are three ways to get this folder by the application itself:

String path1 = System.AppDomain.CurrentDomain.BaseDirectory;
String path2 = System.IO.Directory.GetCurrentDirectory();    
String path3 = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; //Remove the last path component, the executing assembly itself.

These work from VS IDE and from a deployed/installed ClickedOnce app, no "true == System.Deployment.ApplicationDeploy.IsNetworkDeployed" check required. ClickOnce picks up any files included in the Visual Studio 2017 project so really the application can access any and all deployed files using relative paths from within the application.

This is based on Windows 10 and Visual Studio 2017

Make a dictionary with duplicate keys in Python

If you want to have lists only when they are necessary, and values in any other cases, then you can do this:

class DictList(dict):
    def __setitem__(self, key, value):
        try:
            # Assumes there is a list on the key
            self[key].append(value)
        except KeyError: # If it fails, because there is no key
            super(DictList, self).__setitem__(key, value)
        except AttributeError: # If it fails because it is not a list
            super(DictList, self).__setitem__(key, [self[key], value])

You can then do the following:

dl = DictList()
dl['a']  = 1
dl['b']  = 2
dl['b'] = 3

Which will store the following {'a': 1, 'b': [2, 3]}.


I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:

my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
    rev_med[v] = k

Which will generate the same output as above: {'a': 1, 'b': [2, 3]}.


CAVEAT: This implementation relies on the non-existence of the append method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,

dl = DictList()
dl['a']  = 1
dl['b']  = [2]
dl['b'] = 3

would produce the same result as before {'a': 1, 'b': [2, 3]}, but one might expected the following: {'a': 1, 'b': [[2], 3]}.

How do I choose the URL for my Spring Boot webapp?

The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path

Basically the post discusses multiple ways of realizing this viz.

  1. Java Config
  2. Command Line Arguments
  3. Java System Properties
  4. OS Environment Variables
  5. application.properties in Current Directory
  6. application.properties in the classpath (src/main/resources or the packaged jar file)

How to create directory automatically on SD card

Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)

not allowed characters in file/folder names

" * / : < > ? \ |

U may find this code helpful in such a case.

The below code removes all ":" and replaces them with "-"

//actualFileName = "qwerty:asdfg:zxcvb" say...

    String[] tempFileNames;
    String tempFileName ="";
    String delimiter = ":";
    tempFileNames = actualFileName.split(delimiter);
    tempFileName = tempFileNames[0];
    for (int j = 1; j < tempFileNames.length; j++){
        tempFileName = tempFileName+" - "+tempFileNames[j];
    }
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
    if (!file.exists()) {
        if (!file.mkdirs()) {
        Log.e("TravellerLog :: ", "Problem creating Image folder");
        }
    }

Using GPU from a docker container?

Use x11docker by mviereck:

https://github.com/mviereck/x11docker#hardware-acceleration says

Hardware acceleration

Hardware acceleration for OpenGL is possible with option -g, --gpu.

This will work out of the box in most cases with open source drivers on host. Otherwise have a look at wiki: feature dependencies. Closed source NVIDIA drivers need some setup and support less x11docker X server options.

This script is really convenient as it handles all the configuration and setup. Running a docker image on X with gpu is as simple as

x11docker --gpu imagename

How to create an Observable from static data similar to http one in Angular?

This is how you can create a simple observable for static data.

let observable = Observable.create(observer => {
  setTimeout(() => {
    let users = [
      {username:"balwant.padwal",city:"pune"},
      {username:"test",city:"mumbai"}]

    observer.next(users); // This method same as resolve() method from Angular 1
    console.log("am done");
    observer.complete();//to show we are done with our processing
    // observer.error(new Error("error message"));
  }, 2000);

})

to subscribe to it is very easy

observable.subscribe((data)=>{
  console.log(data); // users array display
});

I hope this answer is helpful. We can use HTTP call instead static data.

Sequence contains more than one element

SingleOrDefault method throws an Exception if there is more than one element in the sequence.

Apparently, your query in GetCustomer is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.

pip3: command not found but python3-pip is already installed

You can use python3 -m pip as a synonym for pip3. That has saved me a couple of times.

Effect of NOLOCK hint in SELECT statements

It will be faster because it doesnt have to wait for locks

Using jQuery, Restricting File Size Before Uploading

Like others have said, it's not possible with just JavaScript due to the security model of such.

If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.

http://www.uploadify.com/

http://swfupload.org/

How to load image files with webpack file-loader

I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.

I used the following settings in the webpack:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},

This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.

Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.

I updated my webpack with the following settings

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},

I then used the following command to import the images

import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">

      <img  style={{ width: 300, height: 150 }} src={img} />
</div>

Hibernate openSession() vs getCurrentSession()

SessionFactory: "One SessionFactory per application per DataBase" ( e.g., if you use 3 DataBase's in our application , you need to create sessionFactory object per each DB , totally you need to create 3 sessionFactorys . or else if you have only one DataBase One sessionfactory is enough ).

Session: "One session for one request-response cycle". you can open session when request came and you can close session after completion of request process. Note:-Don't use one session for web application.

how to auto select an input field and the text in it on page load

From http://www.codeave.com/javascript/code.asp?u_log=7004:

_x000D_
_x000D_
var input = document.getElementById('myTextInput');_x000D_
input.focus();_x000D_
input.select();
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
_x000D_
_x000D_

Sending string via socket (python)

This piece of code is incorrect.

while 1:
    (clientsocket, address) = serversocket.accept()
    print ("connection found!")
    data = clientsocket.recv(1024).decode()
    print (data)
    r='REceieve'
    clientsocket.send(r.encode())

The call on accept() on the serversocket blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

That's the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

How to access remote server with local phpMyAdmin client?

Follow this blog post. You can do it very easily. https://wadsashika.wordpress.com/2015/01/06/manage-remote-mysql-database-locally-using-phpmyadmin/

The file config.inc.php contains the configuration settings for your phpMyAdmin installation. It uses an array to store sets of config options for every server it can connect to and by default there is only one, your own machine, or localhost. In order to connect to another server, you would have to add another set of config options to the config array. You have to edit this configuration file.

First open config.inc.php file held in phpMyAdmin folder. In wamp server, you can find it in wamp\apps\phpmyadmin folder. Then add following part to that file.

$i++;
$cfg['Servers'][$i]['host']          = 'hostname/Ip Adress';
$cfg['Servers'][$i]['port']          = '';
$cfg['Servers'][$i]['socket']        = '';
$cfg['Servers'][$i]['connect_type']  = 'tcp';
$cfg['Servers'][$i]['extension']     = 'mysql';
$cfg['Servers'][$i]['compress']      = FALSE;
$cfg['Servers'][$i]['auth_type']     = 'config';
$cfg['Servers'][$i]['user']          = 'username';
$cfg['Servers'][$i]['password']      = 'password';

Let’s see what is the meaning of this variables.

$i++ :- Incrementing variable for each server
$cfg[‘Servers’][$i][‘host’] :- Server host name or IP adress
$cfg[‘Servers’][$i][‘port’] :- MySQL port (Leave a blank for default port. Default MySQL port is 3306)
$cfg[‘Servers’][$i][‘socket’] :- Path to the socket (Leave a blank for default socket)
$cfg[‘Servers’][$i][‘connect_type’] :- How to connect to MySQL server (‘tcp’ or ‘socket’)
$cfg[‘Servers’][$i][‘extension’] :- php MySQL extension to use (‘mysql’ or ‘msqli’)
$cfg[‘Servers’][$i][‘compress’] :- Use compressed protocol for the MySQL connection (requires PHP >= 4.3.0)
$cfg[‘Servers’][$i][‘auth_type’] :- Method of Authentication
$cfg[‘Servers’][$i][‘username’] :- Username to the MySQL database in remote server
$cfg[‘Servers’][$i][‘password’] :- Password to the MySQL database int he remote server

After adding this configuration part, restart you server and now your phpMyAdmin home page will change and it will show a field to select the server.

Now you can select you server and access your remote database by entering username and password for that database.

How to set size for local image using knitr for markdown?

Here's some options that keep the file self-contained without retastering the image:

Wrap the image in div tags

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

Use a stylesheet

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

If you have more than one image you might need to use the nth-child pseudo-selector for this second option.

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

Isn't the size of character in Java 2 bytes?

In ASCII text file each character is just one byte

Laravel 4: how to "order by" using Eloquent ORM

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();

How to group by month from Date field using sql

I used the FORMAT function to accomplish this:

select
 FORMAT(Closing_Date, 'yyyy_MM') AS Closing_Month
 , count(*) cc 
FROM
 MyTable
WHERE
 Defect_Status1 IS NOT NULL
 AND Closing_Date >= '2011-12-01'
 AND Closing_Date < '2016-07-01' 
GROUP BY FORMAT(Closing_Date, 'yyyy_MM')
ORDER BY Closing_Month

hibernate - get id after save object

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

Is there an embeddable Webkit component for Windows / C# development?

Haven't tried yet but found WebKit.NET on SourceForge. It was moved to GitHub.

Warning: Not maintained anymore, last commits are from early 2013

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

This is a improve code from @MiFi. This one order in abs but not excluding the negative values.

   def top_correlation (df,n):
    corr_matrix = df.corr()
    correlation = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
                 .stack()
                 .sort_values(ascending=False))
    correlation = pd.DataFrame(correlation).reset_index()
    correlation.columns=["Variable_1","Variable_2","Correlacion"]
    correlation = correlation.reindex(correlation.Correlacion.abs().sort_values(ascending=False).index).reset_index().drop(["index"],axis=1)
    return correlation.head(n)

top_correlation(ANYDATA,10)

Why catch and rethrow an exception in C#?

One possible reason to catch-throw is to disable any exception filters deeper up the stack from filtering down (random old link). But of course, if that was the intention, there would be a comment there saying so.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

If I understand your issue this should work

&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.

Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html

Regular Expression to reformat a US phone number in Javascript

Possible solution:

function normalize(phone) {
    //normalize string and remove all unnecessary characters
    phone = phone.replace(/[^\d]/g, "");

    //check if number length equals to 10
    if (phone.length == 10) {
        //reformat and return phone number
        return phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    }

    return null;
}

var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();
}


public interface InterfaceB {
  public int print();
}

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
  {
    System.out.println("Inside InterfaceA");
  }
  public int print()
  {
    System.out.println("Inside InterfaceB");
    return 5;
  }
}

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

How to access first element of JSON object array?

To answer your titular question, you use [0] to access the first element, but as it stands mandrill_events contains a string not an array, so mandrill_events[0] will just get you the first character, '['.

So either correct your source to:

var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };

and then req.mandrill_events[0], or if you're stuck with it being a string, parse the JSON the string contains:

var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
var mandrill_events = JSON.parse(req.mandrill_events);
var result = mandrill_events[0];

How to remove duplicates from a list?

Two suggestions:

  • Use a HashSet instead of an ArrayList. This will speed up the contains() checks considerably if you have a long list

  • Make sure Customer.equals() and Customer.hashCode() are implemented properly, i.e. they should be based on the combined values of the underlying fields in the customer object.

Nginx: stat() failed (13: permission denied)

I've just had the same problem on a CentOS 7 box.

Seems I'd hit selinux. Putting selinux into permissive mode (setenforce permissive) has worked round the problem for now. I'll try and get back with a proper fix.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

Docker - a way to give access to a host USB or serial device?

With current versions of Docker, you can use the --device flag to achieve what you want, without needing to give access to all USB devices.

For example, if you wanted to make only /dev/ttyUSB0 accessible within your Docker container, you could do something like:

docker run -t -i --device=/dev/ttyUSB0 ubuntu bash

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Worked by adding this in pom.xml:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Even you have SDK 13 or 14.

How to debug Apache mod_rewrite

There's the htaccess tester.

It shows which conditions were tested for a certain URL, which ones met the criteria and which rules got executed.

It seems to have some glitches, though.

How to copy directories with spaces in the name

There is a bug in robocopy in interpreting the source name. If you include a back slash at the end of the path to describe a folder it keeps including the string for the source into the rest of the line. ie

robocopy "C:\back up\" %destination% /e Nothing here will go to the destination string

robocopy "C:\back up" %destination% /e but this works

I may be wrong but I think both should work!

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

In short, it is used in decorator syntax and for matrix multiplication.

In the context of decorators, this syntax:

@decorator
def decorated_function():
    """this function is decorated"""

is equivalent to this:

def decorated_function():
    """this function is decorated"""

decorated_function = decorator(decorated_function)

In the context of matrix multiplication, a @ b invokes a.__matmul__(b) - making this syntax:

a @ b

equivalent to

dot(a, b)

and

a @= b

equivalent to

a = dot(a, b)

where dot is, for example, the numpy matrix multiplication function and a and b are matrices.

How could you discover this on your own?

I also do not know what to search for as searching Python docs or Google does not return relevant results when the @ symbol is included.

If you want to have a rather complete view of what a particular piece of python syntax does, look directly at the grammar file. For the Python 3 branch:

~$ grep -C 1 "@" cpython/Grammar/Grammar 

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: decorator+
--
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
            '<<=' | '>>=' | '**=' | '//=')
--
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power

We can see here that @ is used in three contexts:

  • decorators
  • an operator between factors
  • an augmented assignment operator

Decorator Syntax:

A google search for "decorator python docs" gives as one of the top results, the "Compound Statements" section of the "Python Language Reference." Scrolling down to the section on function definitions, which we can find by searching for the word, "decorator", we see that... there's a lot to read. But the word, "decorator" is a link to the glossary, which tells us:

decorator

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

def f(...):
    ...
f = staticmethod(f)

@staticmethod
def f(...):
    ...

The same concept exists for classes, but is less commonly used there. See the documentation for function definitions and class definitions for more about decorators.

So, we see that

@foo
def bar():
    pass

is semantically the same as:

def bar():
    pass

bar = foo(bar)

They are not exactly the same because Python evaluates the foo expression (which could be a dotted lookup and a function call) before bar with the decorator (@) syntax, but evaluates the foo expression after bar in the other case.

(If this difference makes a difference in the meaning of your code, you should reconsider what you're doing with your life, because that would be pathological.)

Stacked Decorators

If we go back to the function definition syntax documentation, we see:

@f1(arg)
@f2
def func(): pass

is roughly equivalent to

def func(): pass
func = f1(arg)(f2(func))

This is a demonstration that we can call a function that's a decorator first, as well as stack decorators. Functions, in Python, are first class objects - which means you can pass a function as an argument to another function, and return functions. Decorators do both of these things.

If we stack decorators, the function, as defined, gets passed first to the decorator immediately above it, then the next, and so on.

That about sums up the usage for @ in the context of decorators.

The Operator, @

In the lexical analysis section of the language reference, we have a section on operators, which includes @, which makes it also an operator:

The following tokens are operators:

+       -       *       **      /       //      %      @
<<      >>      &       |       ^       ~
<       >       <=      >=      ==      !=

and in the next page, the Data Model, we have the section Emulating Numeric Types,

object.__add__(self, other)
object.__sub__(self, other) 
object.__mul__(self, other) 
object.__matmul__(self, other) 
object.__truediv__(self, other) 
object.__floordiv__(self, other)

[...] These methods are called to implement the binary arithmetic operations (+, -, *, @, /, //, [...]

And we see that __matmul__ corresponds to @. If we search the documentation for "matmul" we get a link to What's new in Python 3.5 with "matmul" under a heading "PEP 465 - A dedicated infix operator for matrix multiplication".

it can be implemented by defining __matmul__(), __rmatmul__(), and __imatmul__() for regular, reflected, and in-place matrix multiplication.

(So now we learn that @= is the in-place version). It further explains:

Matrix multiplication is a notably common operation in many fields of mathematics, science, engineering, and the addition of @ allows writing cleaner code:

S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

instead of:

S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

While this operator can be overloaded to do almost anything, in numpy, for example, we would use this syntax to calculate the inner and outer product of arrays and matrices:

>>> from numpy import array, matrix
>>> array([[1,2,3]]).T @ array([[1,2,3]])
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])
>>> array([[1,2,3]]) @ array([[1,2,3]]).T
array([[14]])
>>> matrix([1,2,3]).T @ matrix([1,2,3])
matrix([[1, 2, 3],
        [2, 4, 6],
        [3, 6, 9]])
>>> matrix([1,2,3]) @ matrix([1,2,3]).T
matrix([[14]])

Inplace matrix multiplication: @=

While researching the prior usage, we learn that there is also the inplace matrix multiplication. If we attempt to use it, we may find it is not yet implemented for numpy:

>>> m = matrix([1,2,3])
>>> m @= m.T
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: In-place matrix multiplication is not (yet) supported. Use 'a = a @ b' instead of 'a @= b'.

When it is implemented, I would expect the result to look like this:

>>> m = matrix([1,2,3])
>>> m @= m.T
>>> m
matrix([[14]])

Editable text to string

This code work correctly only when u put into button click because at that time user put values into editable text and then when user clicks button it fetch the data and convert into string

EditText dob=(EditText)findviewbyid(R.id.edit_id);
String  str=dob.getText().toString();

Convert one date format into another in PHP

The Basics

The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.

$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);

Or as a one-liner:

$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02'));

Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.

Using DateTime()

As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:

$date = new DateTime('2008-07-01T22:35:17.02');
$new_date_format = $date->format('Y-m-d H:i:s');

Working with Unix timestamps

date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:

$new_date_format = date('Y-m-d H:i:s', '1234567890');

DateTime() works with Unix timestamps by adding an @ before the timestamp:

$date = new DateTime('@1234567890');
$new_date_format = $date->format('Y-m-d H:i:s');

If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:

  • Trim the last three digits off using substr()

Trimming the last three digits can be acheived several ways, but using substr() is the easiest:

$timestamp = substr('1234567899000', -3);
  • Divide the substr by 1000

You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:

$timestamp = bcdiv('1234567899000', '1000');

To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:

$timestamp = strtotime('1973-04-18');

With DateTime() you can use DateTime::getTimestamp()

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->getTimestamp();

If you're running PHP 5.2 you can use the U formatting option instead:

$date = new DateTime('2008-07-01T22:35:17.02');
$timestamp = $date->format('U');

Working with non-standard and ambiguous date formats

Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.

$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM');
$new_date_format = $date->format('Y-m-d H:i:s');

In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:

$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s');

$new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s');

Session 'app': Error Launching activity

I had the same error as in the headline. after I changed the version name and version code in the gradle, the sync happened and then it worked. so maybe even only sync can help sometimes.

Pandas DataFrame Groupby two columns and get counts

Inserting data into a pandas dataframe and providing column name.

import pandas as pd
df = pd.DataFrame([['A','C','A','B','C','A','B','B','A','A'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['Alphabet','Words']]
print(df)   #printing dataframe.

This is our printed data:

enter image description here

For making a group of dataframe in pandas and counter,
You need to provide one more column which counts the grouping, let's call that column as, "COUNTER" in dataframe.

Like this:

df['COUNTER'] =1       #initially, set that counter to 1.
group_data = df.groupby(['Alphabet','Words'])['COUNTER'].sum() #sum function
print(group_data)

OUTPUT:

enter image description here

Tools for creating Class Diagrams

Just discovered GenMyModel, an awesome UML modeler to design class diagram online

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

Sniff HTTP packets for GET and POST requests from an application

post in http
Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet

How to set "style=display:none;" using jQuery's attr method?

You can use the jquery attr() method to achieve the setting of teh attribute and the method removeAttr() to delete the attribute for your element msform As seen in the code

$('#msform').attr('style', 'display:none;');


$('#msform').removeAttr('style');

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

HTML display result in text (input) field?

With .value and INPUT tag

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
    </FORM>

  </BODY>
</HTML>

with innerHTML and DIV

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').innerHTML = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <DIV  ID="add"></DIV>
    </FORM>

  </BODY>
</HTML>

How should I import data from CSV into a Postgres table using pgAdmin 3?

You may have a table called 'test'

COPY test(gid, "name", the_geom)
FROM '/home/data/sample.csv'
WITH DELIMITER ','
CSV HEADER

Hibernate error: ids for this class must be manually assigned before calling save():

For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that

    private String U_id;

will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue annotation or by assigning a value manually.

In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id, e.g.

  public Role (String U_id) { ... }

This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.

Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role using the default constructor, just declare it as private.

How to initialize a static array?

Nope, no difference. It's just syntactic sugar. Arrays.asList(..) creates an additional list.

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

From the documentation (MySQL 8) :

      Type | Maximum length
-----------+-------------------------------------
  TINYTEXT |           255 (2 8−1) bytes
      TEXT |        65,535 (216−1) bytes = 64 KiB
MEDIUMTEXT |    16,777,215 (224−1) bytes = 16 MiB
  LONGTEXT | 4,294,967,295 (232−1) bytes =  4 GiB

Note that the number of characters that can be stored in your column will depend on the character encoding.

C#: how to get first char of a string?

Just MyString[0]. This uses the String.Chars indexer.

How to export a MySQL database to JSON?

THis is somthing that should be done in the application layer.

For example, in php it is a s simple as

Edit Added the db connection stuff. No external anything needed.

$sql = "select ...";
$db = new PDO ( "mysql:$dbname", $user, $password) ;
$stmt = $db->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();

file_put_contents("output.txt", json_encode($result));

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

Editor does not contain a main type

***

Just close and reopen

*** your project in eclipse. Sometime there are linkage problems. This solved my problem

" app-release.apk" how to change this default generated apk name

add android.applicationVariants.all block like below in you app level gradle

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            lintOptions {
                disable 'MissingTranslation'
            }
            signingConfig signingConfigs.release
            android.applicationVariants.all { variant ->
                variant.outputs.all {
                    outputFileName = "${applicationId}_${versionCode}_${variant.flavorName}_${variant.buildType.name}.apk"
                }
            }
        }
        debug {
            applicationIdSuffix '.debug'
            versionNameSuffix '_debug'
        }
    }

available at 2019/03/25

Git push rejected after feature branch rebase

My way of avoiding the force push is to create a new branch and continuing work on that new branch and after some stability, remove the old branch that was rebased:

  • Rebasing the checked out branch locally
  • Branching from the rebased branch to a new branch
  • Pushing that branch as a new branch to remote. and deleting the old branch on remote

Where and why do I have to put the "template" and "typename" keywords?

I am placing JLBorges's excellent response to a similar question verbatim from cplusplus.com, as it is the most succinct explanation I've read on the subject.

In a template that we write, there are two kinds of names that could be used - dependant names and non- dependant names. A dependant name is a name that depends on a template parameter; a non-dependant name has the same meaning irrespective of what the template parameters are.

For example:

template< typename T > void foo( T& x, std::string str, int count )
{
    // these names are looked up during the second phase
    // when foo is instantiated and the type T is known
    x.size(); // dependant name (non-type)
    T::instance_count ; // dependant name (non-type)
    typename T::iterator i ; // dependant name (type)
      
    // during the first phase, 
    // T::instance_count is treated as a non-type (this is the default)
    // the typename keyword specifies that T::iterator is to be treated as a type.

    // these names are looked up during the first phase
    std::string::size_type s ; // non-dependant name (type)
    std::string::npos ; // non-dependant name (non-type)
    str.empty() ; // non-dependant name (non-type)
    count ; // non-dependant name (non-type)
}

What a dependant name refers to could be something different for each different instantiation of the template. As a consequence, C++ templates are subject to "two-phase name lookup". When a template is initially parsed (before any instantiation takes place) the compiler looks up the non-dependent names. When a particular instantiation of the template takes place, the template parameters are known by then, and the compiler looks up dependent names.

During the first phase, the parser needs to know if a dependant name is the name of a type or the name of a non-type. By default, a dependant name is assumed to be the name of a non-type. The typename keyword before a dependant name specifies that it is the name of a type.


Summary

Use the keyword typename only in template declarations and definitions provided you have a qualified name that refers to a type and depends on a template parameter.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Squash my last X commits together using Git

Tried all approaches mention here. But finally my issue resolved by following this link. https://gist.github.com/longtimeago/f7055aa4c3bba8a62197

$ git fetch upstream
$ git checkout omgpull 
$ git rebase -i upstream/master

 < choose squash for all of your commits, except the first one >
 < Edit the commit message to make sense, and describe all your changes >

$ git push origin omgpull -f

jQuery hasAttr checking to see if there is an attribute on an element

You're so close it's crazy.

if($(this).attr("name"))

There's no hasAttr but hitting an attribute by name will just return undefined if it doesn't exist.

This is why the below works. If you remove the name attribute from #heading the second alert will fire.

Update: As per the comments, the below will ONLY work if the attribute is present AND is set to something not if the attribute is there but empty

<script type="text/javascript">
$(document).ready(function()
{
    if ($("#heading").attr("name"))
      alert('Look, this is showing because it\'s not undefined');
    else
      alert('This would be called if it were undefined or is there but empty');
});
</script>
<h1 id="heading" name="bob">Welcome!</h1>

HTML - Alert Box when loading page

you need a tiny bit of Javascript.

<script type="text/javascript">
window.onload = function(){ 
                alert("Hi there");
                }
</script>

This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script> tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.

How to close a web page on a button click, a hyperlink or a link button click?

public class Form1 : Form
{
public Form1()
{
    InitializeComponents(); // or whatever that method is called :)
    this.button.Click += new RoutedEventHandler(buttonClick);
}

private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}
}

How to hide action bar before activity is created, and then show it again?

Just add this to your MainActivity in the onCreate function.

val actionBar = supportActionBar?.apply { hide() }

Email Address Validation in Android on EditText

try this

public static final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(

              "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
              "\\@" +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
              "(" +
              "\\." +
              "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
              ")+"
          );

and in tne edit text

final String emailText = email.getText().toString();
EMAIL_ADDRESS_PATTERN.matcher(emailText).matches()

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

What are the best PHP input sanitizing functions?

Database Input - How to prevent SQL Injection

  1. Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
    • In the case of non-strings you need to ensure that the data actually is the correct type
    • In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
  2. Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
  3. When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)

You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).

$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);

Output from database - How to prevent XSS (Cross Site Scripting)

Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:

$html['username'] = htmlspecialchars($clean['username'])

And Finally... what you requested

I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.

function filterThis($string) {
    return mysql_real_escape_string($string);
}

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

moment.js, how to get day of week number

From the docs page, notice they have these helpful headers

http://momentjs.com/docs/#/get-set/weekday/
(I didn't see them at first)

With header sections for:

  • Date of Month
  • Day of Week
  • etc

.

  var now = moment();
  var day  = now.day();
  var date = now.date(); // Number

Send POST data on redirect with JavaScript/jQuery?

This is quite handy to use:

var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:

myRedirect("/yourRedirectingUrl", "arg", "argValue");

How to sort a list of lists by a specific index of the inner list?

Make sure that you do not have any null or NaN values in the list you want to sort. If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.

Check out Python: sort function breaks in the presence of nan

Procedure expects parameter which was not supplied

First - why is that an EXEC? Shouldn't that just be

AS
SELECT Column_Name, ...
FROM ...
WHERE TABLE_NAME = @template

The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name', it would search WHERE TABLE_NAME = Column_Name, which is very rare (to have table and column named the same).

Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL (keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.

Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...

Spark dataframe: collect () vs select ()

To answer the questions directly:

Will collect() behave the same way if called on a dataframe?

Yes, spark.DataFrame.collect is functionally the same as spark.RDD.collect. They serve the same purpose on these different objects.

What about the select() method?

There is no such thing as spark.RDD.select, so it cannot be the same as spark.DataFrame.select.

Does it also work the same way as collect() if called on a dataframe?

The only thing that is similar between select and collect is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.

Here's my own description: collect is the opposite of sc.parallelize. select is the same as the SELECT in any SQL statement.

If you are still having trouble understanding what collect actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:

How do you find the current user in a Windows environment?

It's always annoyed me how Windows doesn't have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:

#include <windows.h>
#include <stdio.h>

int main(int argc, char **argv) {
    printf("%s", GetUserName());
}

And just use that in your batch file.

Python - 'ascii' codec can't decode byte

You can try this

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

Or

You can also try following

Add following line at top of your .py file.

# -*- coding: utf-8 -*- 

How do I line up 3 divs on the same row?

I'm not sure how I ended up on this post but since most of the answers are using floats, absolute positioning, and other options which aren't optimal now a days, I figured I'd give a new answer that's more up to date on it's standards (float isn't really kosher anymore).

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction:row;_x000D_
}_x000D_
_x000D_
.column {_x000D_
  flex: 1 1 0px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="column">Column 1</div>_x000D_
    <div class="column">Column 2<br>Column 2<br>Column 2<br>Column 2<br></div>_x000D_
    <div class="column">Column 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I was having the same issue using foreach. I saved the list to $servers and used this which worked:

ForEach ($_ in $Servers) { Write-Host "Host $($_)" | Get-WmiObject win32_SystemEnclosure -Computer $_ | format-table -auto @{Label="Service Tag"; Expression={$_.serialnumber}}
}

C string append

do the following:

strcat(new_str,str1);
strcat(new_str,str2);

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

When using the Docker compose files, publish, publishes to obj/Docker/Publish. When I copied my files there and pointed my Dockerfile to this directory (as generated), it works…

Hide vertical scrollbar in <select> element

Change padding-bottom , i.e may be the simplest possible way .

How to ignore the certificate check when ssl

Mention has been made that before .NET 4.5 the property on the request to access its ServicePointManager was not available.

Here is .NET 4.0 code that will give you access to the ServicePoint on a per-request basis. It doesn't give you access to the per-request callback, but it should let you find out more details about the problem. Just access the scvPoint.Certificate (or ClientCertificate if you prefer) properties.

WebRequest request = WebRequest.Create(uri);

// oddity: these two .Address values are not necessarily the same!
//  The service point appears to be related to the .Host, not the Uri itself.
//  So, check the .Host vlaues before fussing in the debugger.
//
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
if (null != svcPoint)
{
    if (!request.RequestUri.Host.Equals(svcPoint.Address.Host, StringComparison.OrdinalIgnoreCase))
    {
        Debug.WriteLine(".Address              == " + request.RequestUri.ToString());
        Debug.WriteLine(".ServicePoint.Address == " + svcPoint.Address.ToString());
    }
    Debug.WriteLine(".IssuerName           == " + svcPoint.Certificate.GetIssuerName());
}

Detecting locked tables (locked by LOCK TABLE)

The simplest way is :

SHOW OPEN TABLES WHERE In_use > 0

You get the locked tables only of the current database.

Finding first and last index of some value in a list in Python

As a small helper function:

def rindex(mylist, myvalue):
    return len(mylist) - mylist[::-1].index(myvalue) - 1

Keras input explanation: input_shape, units, batch_size, dim, etc

Units:

The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit

Shapes

Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Export DataTable to Excel with Open Xml SDK in c#

You could try taking a look at this libary. I've used it for one of my projects and found it very easy to work with, reliable and fast (I only used it for exporting data).

http://epplus.codeplex.com/

Invalid attempt to read when no data is present

I was having 2 values which could contain null values.

while(dr.Read())
 {
    Id = dr["Id"] as int? ?? default(int?);
    Alt =  dr["Alt"].ToString() as string ?? default(string);
    Name = dr["Name"].ToString()
 }

resolved the issue

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Just import following package,

import org.hibernate.cfg.Configuration;

Android: how to parse URL String with spaces to URI object?

java.net.URLEncoder.encode(finalPartOfString, "utf-8");

This will URL-encode the string.

finalPartOfString is the part after the last slash - in your case, the name of the song, as it seems.

How to change the MySQL root account password on CentOS7?

Use the below Steps to reset the password.

$ sudo systemctl start mysqld

Reset the MySql server root password.

$sudo grep 'temporary password' /var/log/mysqld.log

Output Something like-:

 10.744785Z 1 [Note] A temporary password is generated for root@localhost: o!5y,oJGALQa

Use the above password during reset mysql_secure_installation process.

<pre>
    $ sudo mysql_secure_installation
</pre>
   Securing the MySQL server deployment.

   Enter password for user root: 

You have successfully reset the root password of MySql Server. Use the below command to check the mysql server connecting or not.

$ mysql -u root -p

http://gotechnies.com/install-latest-mysql-5-7-rhelcentos-7/

Error during installing HAXM, VT-X not working

I had exactly the same problem. And this is how I could fix it.

Step 1: Turn virtualization on in BIOS settings.

Step 2: Control Panel -> "Programs" -> "Turn Windows features on or off" (under "Programs and Features") and locate "Hyper-V", uncheck, reboot.

Step 3: In Avast->Settings->Troubleshooting. Uncheck "Enable hardware-assisted virtualization" & "Enable avast self-defense module"

Final step and the main:
Go to MyPC / right click / Advanced System Settings / Advanced / In Performance click SETTINGS / Data Execution Prevention and enable DEP for all programs and services.

The last step helped me to solve this problem. Hope you too.

Get all photos from Instagram which have a specific hashtag with PHP

If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.

 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = 'YOUR_TAG_HERE';
    $client_id = "YOUR_CLIENT_ID";
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;

    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);

    //Now parse through the $results array to display your results... 
    foreach($results['data'] as $item){
        $image_link = $item['images']['low_resolution']['url'];
        echo '<img src="'.$image_link.'" />';
    }

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

How to convert an integer to a string in any base?

num = input("number")
power = 0
num = int(num)
while num > 10:
    num = num / 10
    power += 1

print(str(round(num, 2)) + "^" + str(power))

Got a NumberFormatException while trying to parse a text file for objects

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

Are strongly-typed functions as parameters possible in TypeScript?

In TS we can type functions in the in the following manners:

Functions types/signatures

This is used for real implementations of functions/methods it has the following syntax:

(arg1: Arg1type, arg2: Arg2type) : ReturnType

Example:

function add(x: number, y: number): number {
    return x + y;
}

class Date {
  setTime(time: number): number {
   // ...
  }

}

Function Type Literals

Function type literals are another way to declare the type of a function. They're usually applied in the function signature of a higher-order function. A higher-order function is a function which accepts functions as parameters or which returns a function. It has the following syntax:

(arg1: Arg1type, arg2: Arg2type) => ReturnType

Example:

type FunctionType1 = (x: string, y: number) => number;

class Foo {
    save(callback: (str: string) => void) {
       // ...
    }

    doStuff(callback: FunctionType1) {
       // ...
    }

}

How to delete items from a dictionary while iterating over it?

With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:

Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:

my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )

# Iterate on the list:
for k in key_list:
    print(key_list)
    print(my_dic)
    del( my_dic[k] )


print( my_dic )
# {}

how to check redis instance version?

Run the command INFO. The version will be the first item displayed.

The advantage of this over redis-server --version is that sometimes you don't have access to the server (e.g. when it's provided to you on the cloud), in which case INFO is your only option.

How can I delete all of my Git stashes at once?

I had another requirement like only few stash have to be removed, below code would be helpful in that case.

#!/bin/sh
for i in `seq 5 8`
do
   git stash drop stash@{$i}
done

/* will delete from 5 to 8 index*/

How to programmatically move, copy and delete files and directories on SD?

Xamarin Android

public static bool MoveFile(string CurrentFilePath, string NewFilePath)
{
    try
    {
        using (var f = new File(CurrentFilePath))
        using (var i = new FileInputStream(f))
        using (var o = new FileOutputStream(NewFilePath))
        {
            i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);
            f.Delete();
        }

        return true;
    }
    catch { return false; }
}

public static bool CopyFile(string CurrentFilePath, string NewFilePath)
{
    try
    {
        using (var i = new FileInputStream(CurrentFilePath))
        using (var o = new FileOutputStream(NewFilePath))
            i.Channel.TransferTo(0, i.Channel.Size(), o.Channel);

        return true;
    }
    catch { return false; }
}

public static bool DeleteFile(string FilePath)
{
    try
    {
        using (var file = new File(FilePath))
            file.Delete();

        return true;
    }
    catch { return false; }
}

Javascript array sort and unique

I'm afraid you can't combine these functions, ie. you gotta do something like this:-

myData.unique().sort();

Alternatively you can implement a kind of sortedset (as available in other languages) - which carries both the notion of sorting and removing duplicates, as you require.

Hope this helps.

References:-

Array.sort

Array.unique

Python - round up to the nearest ten

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

MySQL DISTINCT on a GROUP_CONCAT()

Using DISTINCT will work

SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table

REf:- this

phpMyAdmin - The MySQL Extension is Missing

Installing bzip2 and zip PHP extensions solved my issue in Ubuntu:

sudo apt-get install php7.0-bz2
sudo apt-get install php7.0-zip

Use php(you version)-(extension) to install and enable any missing modules that is required in the phpmyadmin readme.

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

Creating a timer in python

# this is kind of timer, stop after the input minute run out.    
import time
min=int(input('>>')) 
while min>0:
    print min
    time.sleep(60) # every minute 
    min-=1  # take one minute 

SQL how to increase or decrease one for a int column in one command

If my understanding is correct, updates should be pretty simple. I would just do the following.

UPDATE TABLE SET QUANTITY = QUANTITY + 1 and
UPDATE TABLE SET QUANTITY = QUANTITY - 1 where QUANTITY > 0

You may need additional filters to just update a single row instead of all the rows.

For inserts, you can cache some unique id related to your record locally and check against this cache and decide whether to insert or not. The alternative approach is to always insert and check for PK violation error and ignore since this is a redundant insert.

How to call a .NET Webservice from Android using KSOAP2?

It's very simple. You are getting the result into an Object which is a primitive one.

Your code:

Object result = (Object)envelope.getResponse();

Correct code:

SoapObject result=(SoapObject)envelope.getResponse();

//To get the data.
String resultData=result.getProperty(0).toString();
// 0 is the first object of data.

I think this should definitely work.

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

Imported a csv-dataset to R but the values becomes factors

for me the solution was to include skip = 0 (number of rows to skip at the top of the file. Can be set >0)

mydata <- read.csv(file = "file.csv", header = TRUE, sep = ",", skip = 22)

JavaFX 2.1 TableView refresh items

initialize() method

fullNameColumn = new TableColumn("Full name");
fullNameColumn.setCellValueFactory(new PropertyValueFactory<User, String>("fullName"));
usernameColumn = new TableColumn("Username");
usernameColumn.setCellValueFactory(new PropertyValueFactory<User, String>("test"));
emailColumn = new TableColumn("Email");
emailColumn.setCellValueFactory(new PropertyValueFactory<User, String>("email"));
reseller_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
reseller_table.getColumns().addAll(usernameColumn, fullNameColumn, emailColumn);

ObservableList<User> data = FXCollections.observableArrayList(User.getResellers());
reseller_table.setItems(data);

User Class (Hibernate POJO Class)

private SimpleStringProperty test;

public void setFullName(String fullName) {
  this.fullName = fullName;
  this.test = new SimpleStringProperty(fullName);    
}

public SimpleStringProperty testProperty() {
  return test;
}

refresh() method

ObservableList<User> data = FXCollections.observableArrayList(User.getResellers());
reseller_table.setItems(data);

Add days Oracle SQL

If you want to add N days to your days. You can use the plus operator as follows -

SELECT ( SYSDATE + N ) FROM DUAL;

adb uninstall failed

In my case I often get this issue when I first complise a app in debug mode and later try to install the google signed app.

That is because both apps have the same package name but diffent signatures. Since I upgraded to Android lollypop I sometimes even get this error if I uninstall the app via the settings\Apps. If you have this problem check if the app is installed in a other User profile and uninstall it in all user accounts.

Vue.js dynamic images not working

<img src="../assets/graph_selected.svg"/>

The static path is resolved by Webpack as a module dependency through loader. But for dynamic path you need to use require to resolve the path. You can then switch between images using a boolean variable & ternary expression.

<img :src="this.graph ? require( `../assets/graph_selected.svg`) 
: require( `../assets/graph_unselected.svg`) " alt="">

And of course toggle the value of the boolean through some event handler.

Find closing HTML tag in Sublime Text

None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.

Is not an enclosing class Java

Shape shape = new Shape();
Shape.ZShape zshape = shape.new ZShape();

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

Customizing the template within a Directive

The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:

<!-- Usage: -->
<form>
  <form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
  return { 
    restrict: 'E', 
    compile: function(element, attrs) {
      var fieldGetter = $parse(attrs.field);

      return function (scope, element, attrs) {
        var template, field, id;
        field = fieldGetter(scope);
        template = '..your dom structure here...'
        element.replaceWith($compile(template)(scope));
      }
    }
  }
})

I've created a gist with more complete code and a writeup of the approach.

how to check if item is selected from a comboBox in C#

Use:

if(comboBox.SelectedIndex > -1) //somthing was selected

To get the selected item you do:

Item m = comboBox.Items[comboBox.SelectedIndex];

As Matthew correctly states, to get the selected item you could also do

Item m = comboBox.SelectedItem;

READ_EXTERNAL_STORAGE permission for Android

Step1: add permission on android manifest.xml

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

Step2: onCreate() method

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
    } else {
        readDataExternal();
    }

Step3: override onRequestPermissionsResult method to get callback

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_MEDIA:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                readDataExternal();
            }
            break;

        default:
            break;
    }
}

Note: readDataExternal() is method to get data from external storage.

Thanks.

jQuery Event : Detect changes to the html/text of a div

Try the MutationObserver:

browser support: http://caniuse.com/#feat=mutationobserver

_x000D_
_x000D_
<html>_x000D_
  <!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->_x000D_
_x000D_
  <head>_x000D_
    </head>_x000D_
  <body>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script type="text/javascript">_x000D_
      // Inspect the array of MutationRecord objects to identify the nature of the change_x000D_
function mutationObjectCallback(mutationRecordsList) {_x000D_
  console.log("mutationObjectCallback invoked.");_x000D_
_x000D_
  mutationRecordsList.forEach(function(mutationRecord) {_x000D_
    console.log("Type of mutation: " + mutationRecord.type);_x000D_
    if ("attributes" === mutationRecord.type) {_x000D_
      console.log("Old attribute value: " + mutationRecord.oldValue);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
      _x000D_
// Create an observer object and assign a callback function_x000D_
var observerObject = new MutationObserver(mutationObjectCallback);_x000D_
_x000D_
      // the target to watch, this could be #yourUniqueDiv _x000D_
      // we use the body to watch for changes_x000D_
var targetObject = document.body; _x000D_
      _x000D_
// Register the target node to observe and specify which DOM changes to watch_x000D_
      _x000D_
      _x000D_
observerObject.observe(targetObject, { _x000D_
  attributes: true,_x000D_
  attributeFilter: ["id", "dir"],_x000D_
  attributeOldValue: true,_x000D_
  childList: true_x000D_
});_x000D_
_x000D_
// This will invoke the mutationObjectCallback function (but only after all script in this_x000D_
// scope has run). For now, it simply queues a MutationRecord object with the change information_x000D_
targetObject.appendChild(document.createElement('div'));_x000D_
_x000D_
// Now a second MutationRecord object will be added, this time for an attribute change_x000D_
targetObject.dir = 'rtl';_x000D_
_x000D_
_x000D_
      </script>_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

ImportError: numpy.core.multiarray failed to import

I was getting the same error and was able to solve it by updating my numpy installation to 1.8.0:

pip install -U numpy

Append String in Swift

let firstname = "paresh"
let lastname = "hirpara"
let itsme = "\(firstname) \(lastname)"

Specifying Font and Size in HTML table

This worked for me and also worked with bootstrap tables

<style>
    .table td, .table th {
        font-size: 10px;
    }
</style>

How can I remove specific rules from iptables?

Execute the same commands but replace the "-A" with "-D". For example:

iptables -A ...

becomes

iptables -D ...

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

How to show a confirm message before delete?

<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>

<!-- language: lang-js -->
<script>
function del_product(id){
    $('.process').css('display','block');
    $('.process').html('<img src="./images/loading.gif">');
    $.ajax({
        'url':'./process.php?action=del_product&id='+id,
        'type':"post",
        success: function(result){
            info=JSON.parse(result);
            if(result.status==1){
                setTimeout(function(){
                    $('.process').hide();
                    $('.tr_'+id).hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            } else if(result.status==0){
                setTimeout(function(){
                    $('.process').hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            }
        }
    });
}
</script>

What does ^M character mean in Vim?

To translate the new line instead of removing it:

:%s/\r/\r/g

How to delete projects in Intellij IDEA 14?

In my strange case, Intellij remembers forever about my project even if I delete .iml... Thus I did the following:

  1. Close project. Delete the .iml file.
  2. Rename my project directory (say my_proj) to my_proj_backup.
  3. (Possibly not needed) Open my_proj_backup in Intellij and close.
  4. Create an empty directory called my_proj, and open it in Intellij. Then close it.
  5. Remove the my_proj and move my_proj_backup back to my_proj. Then open my_proj in Intellij.

Then it happily forgot the old my_proj :)

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

C++ cast to derived class

You can't cast a base object to a derived type - it isn't of that type.

If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:

DerivedType D;
BaseType B;

BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type

DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I solve this problem from a different perspective.

I think if the server sends JSON data with Content-Type: text/html header. It doesn't mean the server guy intended to send you some html but accidentally changed to JSON. It does mean the server guy just doesn't care about what the Content-Type header is. So if the server guy doesn't care as the client side you better ignore the Content-Type header as well. To ignore the Content-Type header check in AFNetworking

manager.responseSerializer.acceptableContentTypes = nil;

In this way the AFJSONResponseSerializer (the default one) will serialize the JSON data without checking Content-Type in response header.

jQuery: How to get to a particular child of a parent?

This will find the first parent with class box then find the first child class with regex matching something and get the id.

$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")

FFmpeg: How to split video efficiently?

Here's a useful script, it helps you split automatically: A script for splitting videos using ffmpeg

#!/bin/bash
 
# Written by Alexis Bezverkhyy <[email protected]> in 2011
# This is free and unencumbered software released into the public domain.
# For more information, please refer to <http://unlicense.org/>
 
function usage {
        echo "Usage : ffsplit.sh input.file chunk-duration [output-filename-format]"
        echo -e "\t - input file may be any kind of file reconginzed by ffmpeg"
        echo -e "\t - chunk duration must be in seconds"
        echo -e "\t - output filename format must be printf-like, for example myvideo-part-%04d.avi"
        echo -e "\t - if no output filename format is given, it will be computed\
 automatically from input filename"
}
 
IN_FILE="$1"
OUT_FILE_FORMAT="$3"
typeset -i CHUNK_LEN
CHUNK_LEN="$2"
 
DURATION_HMS=$(ffmpeg -i "$IN_FILE" 2>&1 | grep Duration | cut -f 4 -d ' ')
DURATION_H=$(echo "$DURATION_HMS" | cut -d ':' -f 1)
DURATION_M=$(echo "$DURATION_HMS" | cut -d ':' -f 2)
DURATION_S=$(echo "$DURATION_HMS" | cut -d ':' -f 3 | cut -d '.' -f 1)
let "DURATION = ( DURATION_H * 60 + DURATION_M ) * 60 + DURATION_S"
 
if [ "$DURATION" = '0' ] ; then
        echo "Invalid input video"
        usage
        exit 1
fi
 
if [ "$CHUNK_LEN" = "0" ] ; then
        echo "Invalid chunk size"
        usage
        exit 2
fi
 
if [ -z "$OUT_FILE_FORMAT" ] ; then
        FILE_EXT=$(echo "$IN_FILE" | sed 's/^.*\.\([a-zA-Z0-9]\+\)$/\1/')
        FILE_NAME=$(echo "$IN_FILE" | sed 's/^\(.*\)\.[a-zA-Z0-9]\+$/\1/')
        OUT_FILE_FORMAT="${FILE_NAME}-%03d.${FILE_EXT}"
        echo "Using default output file format : $OUT_FILE_FORMAT"
fi
 
N='1'
OFFSET='0'
let 'N_FILES = DURATION / CHUNK_LEN + 1'
 
while [ "$OFFSET" -lt "$DURATION" ] ; do
        OUT_FILE=$(printf "$OUT_FILE_FORMAT" "$N")
        echo "writing $OUT_FILE ($N/$N_FILES)..."
        ffmpeg -i "$IN_FILE" -vcodec copy -acodec copy -ss "$OFFSET" -t "$CHUNK_LEN" "$OUT_FILE"
        let "N = N + 1"
        let "OFFSET = OFFSET + CHUNK_LEN"
done

MS Access: how to compact current database in VBA

DBEngine.CompactDatabase source, dest

How to read until EOF from cin in C++

while(std::cin) {
 // do something
}

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

error CS0103: The name ' ' does not exist in the current context

Simply move the declaration outside of the if block.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store2_logo.gif";
    }
}

<a href="@Url.RouteUrl("HomePage")" class="logo"><img  alt="" src="@imgsrc"></a>

You could make it a bit cleaner.

@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
    {
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
    imgsrc="/content/images/uploaded/store1_logo.jpg";
    }
else
    {
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
    }
}

How to remove a variable from a PHP session array

if (isset($_POST['remove'])) {
    $key=array_search($_GET['name'],$_SESSION['name']);
    if($key!==false)
    unset($_SESSION['name'][$key]);
    $_SESSION["name"] = array_values($_SESSION["name"]);
} 

Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.

Delete the first three rows of a dataframe in pandas

Use iloc:

df = df.iloc[3:]

will give you a new df without the first three rows.

Why doesn't Python have multiline comments?

Personally my comment style in say Java is like

/*
 * My multi-line comment in Java
 */

So having single-line only comments isn't such a bad thing if your style is typical to the preceding example because in comparison you'd have

#
# My multi-line comment in Python
#

VB.NET is also a language with single-line only commenting, and personally I find it annoying as comments end up looking less likes comments and more like some kind of quote

'
' This is a VB.NET example
'

Single-line-only comments end up having less character-usage than multi-line comments, and are less likely to be escaped by some dodgy characters in a regex statement perhaps? I'd tend to agree with Ned though.

Finding absolute value of a number without using Math.abs()

In case of the absolute value of an integer x without using Math.abs(), conditions or bit-wise operations, below could be a possible solution in Java.

(int)(((long)x*x - 1)%(double)x + 1);

Because Java treats a%b as a - a/b * b, the sign of the result will be same as "a" no matter what sign of "b" is; (x*x-1)%x will equal abs(x)-1; type casting of "long" is to prevent overflow and double allows dividing by zero.

Again, x = Integer.MIN_VALUE will cause overflow due to subtracting 1.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

Answer for MYSQL USERS:

ALTER TABLE ChildTableName 
DROP FOREIGN KEY `fk_table`;
ALTER TABLE ChildTableName 
ADD CONSTRAINT `fk_t1_t2_tt`
  FOREIGN KEY (`parentTable`)
  REFERENCES parentTable (`columnName`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

Using Spring 3 autowire in a standalone Java application

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

How to run 'sudo' command in windows

There kind of is. I created Sudo for Windows back in 2007? 08? Here's the security paper I wrote about it - https://www.sans.org/reading-room/whitepapers/bestprac/sudo-windows-sudowin-1726. Pretty sure http://sudowin.sf.net still works too.

How to show DatePickerDialog on Button click?

Following code works..

datePickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(0);
        }
    });

@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
    return new DatePickerDialog(this, datePickerListener, year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int selectedYear,
                          int selectedMonth, int selectedDay) {
        day = selectedDay;
        month = selectedMonth;
        year = selectedYear;
        datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
                + selectedYear);
    }
};

Recommended Fonts for Programming?

I've been hanging on to this link for more than a year, it's an article entitled "Five great programming fonts". The five are good fonts, but the article includes comments with a dozen more interesting answers.

http://forums.programming-designs.com/viewtopic.php?pid=3338

Unnamed/anonymous namespaces vs. static functions

I recently began replacing static keywords with anonymous namespaces in my code but immediately ran into a problem where the variables in the namespace were no longer available for inspection in my debugger. I was using VC60, so I don't know if that is a non-issue with other debuggers. My workaround was to define a 'module' namespace, where I gave it the name of my cpp file.

For example, in my XmlUtil.cpp file, I define a namespace XmlUtil_I { ... } for all of my module variables and functions. That way I can apply the XmlUtil_I:: qualification in the debugger to access the variables. In this case, the _I distinguishes it from a public namespace such as XmlUtil that I may want to use elsewhere.

I suppose a potential disadvantage of this approach compared to a truly anonymous one is that someone could violate the desired static scope by using the namespace qualifier in other modules. I don't know if that is a major concern though.

How to convert a 3D point into 2D perspective projection?

I think this will probably answer your question. Here's what I wrote there:

Here's a very general answer. Say the camera's at (Xc, Yc, Zc) and the point you want to project is P = (X, Y, Z). The distance from the camera to the 2D plane onto which you are projecting is F (so the equation of the plane is Z-Zc=F). The 2D coordinates of P projected onto the plane are (X', Y').

Then, very simply:

X' = ((X - Xc) * (F/Z)) + Xc

Y' = ((Y - Yc) * (F/Z)) + Yc

If your camera is the origin, then this simplifies to:

X' = X * (F/Z)

Y' = Y * (F/Z)

Volley JsonObjectRequest Post request not working

When you working with JsonObject request you need to pass the parameters right after you pass the link in the initialization , take a look on this code :

        HashMap<String, String> params = new HashMap<>();
        params.put("user", "something" );
        params.put("some_params", "something" );

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

           // Some code 

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //handle errors
        }
    });


}

Round button with text and icon in flutter

Use Column or Row in a Button child, Row for horizontal button, Column for vertical, and dont forget to contain it with the size you need:

Container(
  width: 120.0,
  height: 30.0,
  child: RaisedButton(
    color: Color(0XFFFF0000),
    child: Row(
      children: <Widget>[
        Text('Play this song', style: TextStyle(color: Colors.white),),
        Icon(Icons.play_arrow, color: Colors.white,),
      ],
    ),
  ),
),

How to get changes from another branch

git fetch origin our-team

or

git pull origin our-team

but first you should make sure that you already on the branch you want to update to (featurex).

Converting string to Date and DateTime

$d = new DateTime('10-16-2003');

$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16

Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.

How to get summary statistics by group

after 5 long years I'm sure not much attention is going to be received for this answer, But still to make all options complete, here is the one with data.table

library(data.table)
setDT(df)[ , list(mean_gr = mean(dt), sum_gr = sum(dt)) , by = .(group)]
#   group mean_gr sum_gr
#1:     A      61    244
#2:     B      66    396
#3:     C      68    408
#4:     D      61    488 

How to use TLS 1.2 in Java 6

I also got a similar error when forced to use TLS1.2 for java 6. And I handled it thanks to this library:

  1. Clone Source Code: https://github.com/tobszarny/ssl-provider-jvm16

  2. Add Main Class:

    public static void main(String[] args) throws Exception {
        try {
            String apiUrl = "https://domain/api/query?test=123";
    
            URL myurl = new URL(apiUrl);
            HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
            con.setSSLSocketFactory(new TSLSocketConnectionFactory());
            int responseCode = con.getResponseCode();
            System.out.println("GET Response Code :: " + responseCode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

Find everything between two XML tags with RegEx

It is not good to use this method but if you really want to split it with regex

<primaryAddress.*>((.|\n)*?)<\/primaryAddress>

the verified answer returns the tags but this just return the value between tags.

Jquery get form field value

You have to use value attribute to get its value

<input type="text" name="FirstName" value="First Name" />

try -

var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();

Get Hours and Minutes (HH:MM) from date

If you want to display 24 hours format use:

SELECT FORMAT(GETDATE(),'HH:mm')

and to display 12 hours format use:

SELECT FORMAT(GETDATE(),'hh:mm')

How do I determine if a checkbox is checked?

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<label><input class="lifecheck" id="lifecheck" type="checkbox" checked >Lives</label>_x000D_
_x000D_
<script type="application/javascript" >_x000D_
    lfckv = document.getElementsByClassName("lifecheck");_x000D_
    if (true === lfckv[0].checked) {_x000D_
      alert('the checkbox is checked');_x000D_
    }_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

so after you can add event in javascript to have dynamical event affected with the checkbox .

thanks

How to reset Jenkins security settings from the command line?

changing the <useSecurity>true</useSecurity> to <useSecurity>false</useSecurity> will not be enough, you should remove <authorizationStrategy> and <securityRealm> elements too and restart your jenkins server by doing sudo service jenkins restart .

remember this, set <usesecurity> to false only may cause a problem for you, since these instructions are mentioned in thier official documentation here.

making matplotlib scatter plots from dataframes in Python's pandas

There is little to be added to Garrett's great answer, but pandas also has a scatter method. Using that, it's as easy as

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
df.plot.scatter('col1', 'col2', df['col3'])

plotting sizes in col3 to col1-col2

Excel: the Incredible Shrinking and Expanding Controls

It's very weird. The Width & Height properties don't shrink when queried (either in code or using the properties sheet), but apparently they DO change.

I noticed that if I use the properties sheet and change the width from the standard 15 to, say, 14 and then BACK to 15, it fixes it.

The code below works for me (and has an amusing visual effect on the sheet: you click, it shrinks, the screen flickers, and it expands back).

MY SOLUTION in code (on the click event for the checkbox):

Dim myCtrl As OLEObject
For Each myCtrl In ActiveSheet.OLEObjects
  myLab = myCtrl.Name
  myCtrl.Height = 14 ' to "wake up" the property.
  myCtrl.Height = 15 ' to reset it back to normal
  myCtrl.Width = 12 ' just making sure
Next myCtrl

Ruby, Difference between exec, system and %x() or Backticks

system

The system method calls a system program. You have to provide the command as a string argument to this method. For example:

>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true

The invoked program will use the current STDIN, STDOUT and STDERR objects of your Ruby program. In fact, the actual return value is either true, false or nil. In the example the date was printed through the IO object of STDIN. The method will return true if the process exited with a zero status, false if the process exited with a non-zero status and nil if the execution failed.

As of Ruby 2.6, passing exception: true will raise an exception instead of returning false or nil:

>> system('invalid')
=> nil

>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)

Another side effect is that the global variable $? is set to a Process::Status object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.

>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>

Backticks

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

>> `date`
=> Wed Sep 4 22:22:51 CEST 2013   

The global variable $? is set through the backticks, too. With backticks you can also make use string interpolation.

%x()

Using %x is an alternative to the backticks style. It will return the output, too. Like its relatives %w and %q (among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date), %x{date} and %x-date- are all synonyms. Like backticks %x can make use of string interpolation.

exec

By using Kernel#exec the current process (your Ruby script) is replaced with the process invoked through exec. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

Open3.popen3

Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3 comes in handy:

require 'open3'

Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end

Description for event id from source cannot be found

Restart your system!

A friend of mine had exactly the same problem. He tried all the described options but nothing seemed to work. After many studies, also of Microsoft's description, he concluded to restart the system. It worked!!

It seems that the operating system does not in all cases refresh the list of registered event sources. Only after a restart you can be sure the event sources are registered properly.

How to add a TextView to LinearLayout in Android

Hey i have checked your code, there is no serious error in your code. this is complete code:

main.xml:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content" 
android:orientation="vertical">
</LinearLayout>

this is Stackoverflow.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Stackoverflow extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View linearLayout =  findViewById(R.id.info);
        //LinearLayout layout = (LinearLayout) findViewById(R.id.info);

        TextView valueTV = new TextView(this);
        valueTV.setText("hallo hallo");
        valueTV.setId(5);
        valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

        ((LinearLayout) linearLayout).addView(valueTV);
    }
}

copy this code, and run it. it is completely error free. take care...

Check if a value exists in pandas dataframe index

with DataFrame: df_data

>>> df_data
  id   name  value
0  a  ampha      1
1  b   beta      2
2  c     ce      3

I tried:

>>> getattr(df_data, 'value').isin([1]).any()
True
>>> getattr(df_data, 'value').isin(['1']).any()
True

but:

>>> 1 in getattr(df_data, 'value')
True
>>> '1' in getattr(df_data, 'value')
False

So fun :D

Python/Json:Expecting property name enclosed in double quotes

JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:

{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}

If that's not something you can do, you could use ast.literal_eval() instead of json.loads()

How to determine MIME type of file in android?

mime from local file:

String url = file.getAbsolutePath();
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mime = fileNameMap.getContentTypeFor("file://"+url);