Programs & Examples On #Infix notation

Operators are written infix-style when they are placed between the operands they act on (e.g. 2 + 2).

What do Push and Pop mean for Stacks?

Hopefully this will help you visualize a Stack, and how it works.

Empty Stack:

|     |
|     |
|     |
-------

After Pushing A, you get:

|     |
|     |
|  A  |
-------

After Pushing B, you get:

|     |
|  B  |
|  A  |
-------

After Popping, you get:

|     |
|     |
|  A  |
-------

After Pushing C, you get:

|     |
|  C  |
|  A  |
-------

After Popping, you get:

|     |
|     |
|  A  |
-------

After Popping, you get:

|     |
|     |
|     |
-------

Run Python script at startup in Ubuntu

Create file ~/.config/autostart/MyScript.desktop with

[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=

X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0

It helps me!

Java HTML Parsing

The HTMLParser project (http://htmlparser.sourceforge.net/) might be a possibility. It seems to be pretty decent at handling malformed HTML. The following snippet should do what you need:

Parser parser = new Parser(htmlInput);
CssSelectorNodeFilter cssFilter = 
    new CssSelectorNodeFilter("DIV.targetClassName");
NodeList nodes = parser.parse(cssFilter);

Design Patterns web based applications

In the beaten-up MVC pattern, the Servlet is "C" - controller.

Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.

I would not, though, start writing raw Servlet classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.

Add space between HTML elements only using CSS

If you want to align various items and you like to have same margin around all sides, you can use the following. Each element withing container, regardless of type, will receive the same surrounding margin.

enter image description here

.container {
  display: flex;
}
.container > * {
  margin: 5px;
}

If you wish to align items in a row, but have the first element touch the leftmost edge of container, and have all other elements be equally spaced, you can use this:

enter image description here

.container {
  display: flex;
}
.container > :first-child {
  margin-right: 5px;
}
.container > *:not(:first-child) {
  margin: 5px;
}

Webview load html from assets directory

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wb = new WebView(this);
        wb.loadUrl("file:///android_asset/index.html");
        setContentView(wb);
    }


keep your .html in `asset` folder

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

Using $setValidity inside a Controller

$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().

See also section "Custom Validation" on the Forms page, if you haven't already.

Also, for the first argument to $setValidity, use just 'filetype' and 'size'.

ResourceDictionary in a separate assembly

Resource-Only DLL is an option for you. But it is not required necessarily unless you want to modify resources without recompiling applications. Have just one common ResourceDictionary file is also an option. It depends how often you change resources and etc.

<ResourceDictionary Source="pack://application:,,,/
     <MyAssembly>;component/<FolderStructureInAssembly>/<ResourceFile.xaml>"/>

MyAssembly - Just assembly name without extension

FolderStructureInAssembly - If your resources are in a folde, specify folder structure

When you are doing this it's better to aware of siteOfOrigin as well.

WPF supports two authorities: application:/// and siteoforigin:///. The application:/// authority identifies application data files that are known at compile time, including resource and content files. The siteoforigin:/// authority identifies site of origin files. The scope of each authority is shown in the following figure.

enter image description here

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

How to get current working directory in Java?

One way would be to use the system property System.getProperty("user.dir"); this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/ the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

Setting the MySQL root user password on OS X

  1. Stop the mysqld server.

    • Mac OSX: System Preferences > MySQL > Stop MySQL Server
    • Linux (From Terminal): sudo systemctl stop mysqld.service
  2. Start the server in safe mode with privilege bypass

    • From Terminal: sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3. In a new terminal window:

    • sudo /usr/local/mysql/bin/mysql -u root
  4. This will open the mysql command line. From here enter:

    • UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';

    • FLUSH PRIVILEGES;

    • quit

  5. Stop the mysqld server again and restart it in normal mode.

    • Mac OSX (From Terminal): sudo /usr/local/mysql/support-files/mysql.server restart
    • Linux Terminal: sudo systemctl restart mysqld

jQuery, get ID of each element in a class using .each?

patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){
  return n.id;
});
alert(arrayOfIds);

How to find my realm file?

Under Tools -> Android Device Monitor

And under File Explorer. Search for the apps. And the file is under data/data.

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

Creating a simple configuration file and parser in C++

I've searched config parsing libraries for my project recently and found these libraries:

Convert a 1D array to a 2D array in numpy

some_array.shape = (1,)+some_array.shape

or get a new one

another_array = numpy.reshape(some_array, (1,)+some_array.shape)

This will make dimensions +1, equals to adding a bracket on the outermost

Detecting user leaving page with react-router

For react-router 2.4.0+

NOTE: It is advisable to migrate all your code to the latest react-router to get all the new goodies.

As recommended in the react-router documentation:

One should use the withRouter higher order component:

We think this new HoC is nicer and easier, and will be using it in documentation and examples, but it is not a hard requirement to switch.

As an ES6 example from the documentation:

import React from 'react'
import { withRouter } from 'react-router'

const Page = React.createClass({

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
      if (this.state.unsaved)
        return 'You have unsaved information, are you sure you want to leave this page?'
    })
  }

  render() {
    return <div>Stuff</div>
  }

})

export default withRouter(Page)

Javascript Regular Expression Remove Spaces

In production and works across line breaks

This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.

text.replace(/[\n\r\s\t]+/g, ' ')

The declared package does not match the expected package ""

This happened to me when I was checking out a project from an svn repository in eclipse. There were jar files in my .m2 folder that eclipse wasn't looking at. To fix the issue I did:

right click project folder Configure > Convert to Maven Project

and that solved the issue.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

Error 1022 - Can't write; duplicate key in table

From the two linksResolved Successfully and Naming Convention, I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.

Error 1022: Can't write; duplicate key in table

How do I set hostname in docker-compose?

Based on docker documentation: https://docs.docker.com/compose/compose-file/#/command

I simply put hostname: <string> in my docker-compose file.

E.g.:

[...]

lb01:
  hostname: at-lb01
  image: at-client-base:v1

[...]

and container lb01 picks up at-lb01 as hostname.

How to edit the legend entry of a chart in Excel?

Left Click on chart. «PivotTable Field List» will appear on right. On the right down quarter of PivotTable Field List (S Values), you see the names of the legends. Left Click on the legend name. Left Click on the «Value field settings». At the top there is «Source Name». You can’t change it. Below there is «Custom Name». Change the Custom Name as you wish. Now the legend name on the chart has the new name you gave.

Change UITableView height dynamically

This can be massively simplified with just 1 line of code in viewDidAppear:

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        tableViewHeightConstraint.constant = tableView.contentSize.height
    }

Understanding the main method of python

The Python approach to "main" is almost unique to the language(*).

The semantics are a bit subtle. The __name__ identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__ is set to "__main__" (the literal string: __main__).

This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:

#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
    pass

def some_function(*args,**kwargs):
    pass

if __name__ == '__main__':
    print("This only executes when %s is executed rather than imported" % __file__)

Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.

It's important to understand that all of the code above the if __name__ line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print statement before the if __name__ line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).

I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.

Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__" to isolate a block of code which calls a suite of unit tests that apply to this module.

(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).

Summary: if __name__ == '__main__': has two primary use cases:

  • Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)
  • Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.

It's fairly common to def main(*args) and have if __name__ == '__main__': simply call main(*sys.argv[1:]) if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module() and calling test_module() in your if __name__ == '__main__:' suite.

  • (Ruby also implements a similar feature if __file__ == $0).

Eclipse: Enable autocomplete / content assist

For me, it helped after I changed the theme to 'mac' since I am running on a MacOSX.

Eclipse: >Preferences > General > Appearance > Choose 'Mac' from the menu.

Are there any standard exit status codes in Linux?

When Linux returns 0, it means success. Anything else means failure, each program has its own exit codes, so it would been quite long to list them all... !

About the 11 error code, it's indeed the segmentation fault number, mostly meaning that the program accessed a memory location that was not assigned.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

Checking if an object is a number in C#

You could use code like this:

if (n is IConvertible)
  return ((IConvertible) n).ToDouble(CultureInfo.CurrentCulture);
else
  // Cannot be converted.

If your object is an Int32, Single, Double etc. it will perform the conversion. Also, a string implements IConvertible but if the string isn't convertible to a double then a FormatException will be thrown.

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

How to change legend title in ggplot

This should work:

p <- ggplot(df, aes(x=rating, fill=cond)) + 
           geom_density(alpha=.3) + 
           xlab("NEW RATING TITLE") + 
           ylab("NEW DENSITY TITLE")
p <- p + guides(fill=guide_legend(title="New Legend Title"))

(or alternatively)

p + scale_fill_discrete(name = "New Legend Title")

Received fatal alert: handshake_failure through SSLHandshakeException

This can also happend when the client needs to present a certificate. After the server lists the certificate chain, the following can happen:

3. Certificate Request The server will issue a certificate request from the client. The request will list all of the certificates the server accepts.

*** CertificateRequest
Cert Types: RSA
Cert Authorities:
<CN=blah, OU=blah, O=blah, L=blah, ST=blah, C=blah>
<CN=yadda, DC=yadda, DC=yadda>
<CN=moreblah, OU=moreblah, O=moreblah, C=moreblah>
<CN=moreyada, OU=moreyada, O=moreyada, C=moreyada>
... the rest of the request
*** ServerHelloDone

4. Client Certificate Chain This is the certificate the client is sending to the server.

*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject: EMAILADDRESS=client's email, CN=client, OU=client's ou, O=client's Org, L=client's location, ST=client's state, C=client's Country
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
  ... the rest of the certificate
*** ClientKeyExchange, RSA PreMasterSecret, TLSv1    
... key exchange info 

If there isn't a certificate in the chain and the server requires one, you'll get the handshake error here. A likely cause is the path to your certificate wasn't found.

5. Certificate Verify The client asks the server to verify the certificate

*** CertificateVerify
... payload of verify check

This step will only happen if you are sending a certificate.

6. Finished The server will respond with a verify response

*** Finished
verify_data:  { 345, ... }

Troubleshooting misplaced .git directory (nothing to commit)

Here is another twist on it. My .gitignore file seemed to have been modified / corrupted so that a file I was ignoring

e.g.

/Project/Folder/StyleCop.cache

got changed to this (Note now 2 separate lines)

/Project/Folder
StyleCop.cache

so git was ignoring any files I added to the project and below.

Very weird, no idea how the .gitignore file was changed, but took me a while to spot. Once fixed, the hundreds of css and js files I added went in.

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

You should import the the project

https://issuetracker.google.com/issues/37008041

This error shows up when there is a module in your project whose .iml file does not contain: external.system.id="GRADLE" Can you please check your .iml files? Also, instead of opening the project, import it, that will completely rewrite your .iml files and you won't see that error again.

importing pyspark in python shell

I got this error because the python script I was trying to submit was called pyspark.py (facepalm). The fix was to set my PYTHONPATH as recommended above, then rename the script to pyspark_test.py and clean up the pyspark.pyc that was created based on my scripts original name and that cleared this error up.

Android: I lost my android key store, what should I do?

You can create a new keystore, but the Android Market wont allow you to upload the apk as an update - worse still, if you try uploading the apk as a new app it will not allow it either as it knows there is a 'different' version of the same apk already in the market even if you delete your previous version from the market

Do your absolute best to find that keystore!!

When you find it, email it to yourself so you have a copy on your gmail that you can go and get in the case you loose it from your hard drive!

MVC 4 Razor adding input type date

You will get it by tag type="date"...then it will render beautiful calendar and all...

@Html.TextBoxFor(model => model.EndTime, new { type = "date" })

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

Return None if Dictionary key is not available

A one line solution would be:

item['key'] if 'key' in item else None

This is useful when trying to add dictionary values to a new list and want to provide a default:

eg.

row = [item['key'] if 'key' in item else 'default_value']

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

I've always assumed this was necessary as the output from the mapper is the input for the reducer, so it was sorted based on the keyspace and then split into buckets for each reducer input. You want to ensure all the same values of a Key end up in the same bucket going to the reducer so they are reduced together. There is no point sending K1,V2 and K1,V4 to different reducers as they need to be together in order to be reduced.

Tried explaining it as simply as possible

Reading string from input with space character?

Try this:

scanf("%[^\n]s",name);

\n just sets the delimiter for the scanned string.

Reading Space separated input in python

For python 3 use this

inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")

input() accepts a string from STDIN.

split() splits the string about whitespace character and returns a list of strings.

map() passes each element of the 2nd argument to the first argument and returns a map object

Finally list() converts the map to a list

How To Accept a File POST

Here are two ways to accept a file. One using in memory provider MultipartMemoryStreamProvider and one using MultipartFormDataStreamProvider which saves to a disk. Note, this is only for one file upload at a time. You can certainty extend this to save multiple-files. The second approach can support large files. I've tested files over 200MB and it works fine. Using in memory approach does not require you to save to disk, but will throw out of memory exception if you exceed a certain limit.

private async Task<Stream> ReadStream()
{
    Stream stream = null;
    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
        var buffer = await file.ReadAsByteArrayAsync();
        stream = new MemoryStream(buffer);
    }

    return stream;
}

private async Task<Stream> ReadLargeStream()
{
    Stream stream = null;
    string root = Path.GetTempPath();
    var provider = new MultipartFormDataStreamProvider(root);
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.FileData)
    {
        var path = file.LocalFileName;
        byte[] content = File.ReadAllBytes(path);
        File.Delete(path);
        stream = new MemoryStream(content);
    }

    return stream;
}

How to get the size of a JavaScript object?

I believe you forgot to include 'array'.

  typeOf : function(value) {
        var s = typeof value;
        if (s === 'object')
        {
            if (value)
            {
                if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function')
                {
                    s = 'array';
                }
            }
            else
            {
                s = 'null';
            }
        }
        return s;
    },

   estimateSizeOfObject: function(value, level)
    {
        if(undefined === level)
            level = 0;

        var bytes = 0;

        if ('boolean' === typeOf(value))
            bytes = 4;
        else if ('string' === typeOf(value))
            bytes = value.length * 2;
        else if ('number' === typeOf(value))
            bytes = 8;
        else if ('object' === typeOf(value) || 'array' === typeOf(value))
        {
            for(var i in value)
            {
                bytes += i.length * 2;
                bytes+= 8; // an assumed existence overhead
                bytes+= estimateSizeOfObject(value[i], 1)
            }
        }
        return bytes;
    },

   formatByteSize : function(bytes)
    {
        if (bytes < 1024)
            return bytes + " bytes";
        else
        {
            var floatNum = bytes/1024;
            return floatNum.toFixed(2) + " kb";
        }
    },

EXC_BAD_ACCESS signal received

I've been debuging, and refactoring code to solve this error for the last four hours. A post above led me to see the problem:

Property before: startPoint = [[DataPoint alloc] init] ; startPoint= [DataPointList objectAtIndex: 0];
. . . x = startPoint.x - 10; // EXC_BAD_ACCESS

Property after: startPoint = [[DataPoint alloc] init] ; startPoint = [[DataPointList objectAtIndex: 0] retain];

Goodbye EXC_BAD_ACCESS

change Oracle user account status from EXPIRE(GRACE) to OPEN

Compilation from jonearles' answer, http://kishantha.blogspot.com/2010/03/oracle-enterprise-manager-console.html and http://blog.flimatech.com/2011/07/17/changing-oracle-password-in-11g-using-alter-user-identified-by-values/ (Oracle 11g):

To stop this happening in the future do the following.

  • Login to sqlplus as sysdba -> sqlplus "/as sysdba"
  • Execute ->ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED PASSWORD_LIFE_TIME UNLIMITED;

To reset users' status, run the query:

select
'alter user ' || su.name || ' identified by values'
   || ' ''' || spare4 || ';'    || su.password || ''';'
from sys.user$ su 
join dba_users du on ACCOUNT_STATUS like 'EXPIRED%' and su.name = du.username;

and execute some or all of the result set.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:

function AjaxFeed(){

    return $.ajax({
        url:            'http://somesite.com/somejsonfile.php',
        data:           {something: true},
        dataType:       'jsonp',

        /* Very important */
        contentType:    'application/json',
    });
}

function GetData() {
    AjaxFeed()

    /* Everything worked okay. Hooray */
    .done(function(data){
        return data;
    })

    /* Okay jQuery is stupid manually fix things */
    .fail(function(jqXHR) {

        /* Build HTML and update */
        var data = jQuery.parseJSON(jqXHR.responseText);

        return data;
    });
}

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

For what it's worth, I've tried both Eigen and Armadillo. Below is a brief evaluation.

Eigen Advantages: 1. Completely self-contained -- no dependence on external BLAS or LAPACK. 2. Documentation decent. 3. Purportedly fast, although I haven't put it to the test.

Disadvantage: The QR algorithm returns just a single matrix, with the R matrix embedded in the upper triangle. No idea where the rest of the matrix comes from, and no Q matrix can be accessed.

Armadillo Advantages: 1. Wide range of decompositions and other functions (including QR). 2. Reasonably fast (uses expression templates), but again, I haven't really pushed it to high dimensions.

Disadvantages: 1. Depends on external BLAS and/or LAPACK for matrix decompositions. 2. Documentation is lacking IMHO (including the specifics wrt LAPACK, other than changing a #define statement).

Would be nice if an open source library were available that is self-contained and straightforward to use. I have run into this same issue for 10 years, and it gets frustrating. At one point, I used GSL for C and wrote C++ wrappers around it, but with modern C++ -- especially using the advantages of expression templates -- we shouldn't have to mess with C in the 21st century. Just my tuppencehapenny.

Recursive Fibonacci

I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.

unsigned fib(unsigned n) {
    if(n == 0) return 0;
    if(n == 1) return 1;
    return fib(n-1) + fib(n-2);
}

This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).

You should better use this approach or if you want to use recursion try this:

unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)     
{
    if(n == 0) return 0;
    if(n == 1) return 1;
    if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
    return prev1+prev2;
}

This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.

Docker official registry (Docker Hub) URL

For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be

docker.io/<dockerimagename>:version

The suggestion above of registry.hub.docker.com/library/<dockerimagename> did not work for me.

I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)

Why when I transfer a file through SFTP, it takes longer than FTP?

For comparison, I tried transfering a 299GB ntfs disk image from an i5 laptop running Raring Ringtail Ubuntu alpha 2 live cd to an i7 desktop running Ubuntu 12.04.1. Reported speeds:

over wifi + powerline: scp: 5MB/sec (40 Mbit/sec)

over gigabit ethernet + netgear G5608 v3:

scp: 44MB/sec

sftp: 47MB/sec

sftp -C: 13MB/sec

So, over a good gigabit link, sftp is slightly faster than scp, 2010-era fast CPUs seem fast enough to encrypt, but compression isn't a win in all cases.

Over a bad gigabit ethernet link, though, I've had sftp far outperform scp. Something about scp being very chatty, see "scp UNBELIEVABLY slow" on comp.security.ssh from 2008: https://groups.google.com/forum/?fromgroups=#!topic/comp.security.ssh/ldPV3msFFQw http://fixunix.com/ssh/368694-scp-unbelievably-slow.html

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

How to define two angular apps / modules in one page?

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp

See also

Detect iPhone/iPad purely by css

You might want to try the solution from this O'Reilly article.

The important part are these CSS media queries:

<link rel="stylesheet" media="all and (max-device-width: 480px)" href="iphone.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css"> 
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="ipad-landscape.css"> 

Difference between database and schema

Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.

pandas dataframe create new columns and fill with calculated values from same df

You can do this easily manually for each column like this:

df['A_perc'] = df['A']/df['sum']

If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):

ds.div(ds['sum'], axis=0)

And if you want this in one step added to the same dataframe:

>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
          A         B         C         D       sum    A_perc    B_perc  \
1  0.151722  0.935917  1.033526  0.941962  3.063127  0.049532  0.305543   
2  0.033761  1.087302  1.110695  1.401260  3.633017  0.009293  0.299283   
3  0.761368  0.484268  0.026837  1.276130  2.548603  0.298739  0.190013   

     C_perc    D_perc  sum_perc  
1  0.337409  0.307517         1  
2  0.305722  0.385701         1  
3  0.010530  0.500718         1  

How to recover corrupted Eclipse workspace?

I have some experience at recovering from eclipse when it becomes unstartable for whatever reason, could these blog entries help you?

link (archived)

also search for "cannot start eclipse" (I am a new user, I can only post a single hyperlink, so I have to just ask that you search for the second :( sorry)

perhaps those allow you to recover your workspace as well, I hope it helps.

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

TypeError: Cannot read property 'then' of undefined

You need to return your promise to the calling function.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.

example

The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

Query based on multiple where clauses in Firebase

var ref = new Firebase('https://your.firebaseio.com/');

Query query = ref.orderByChild('genre').equalTo('comedy');
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
            Movie movie = dataSnapshot.getValue(Movie.class);
            if (movie.getLead().equals('Jack Nicholson')) {
                console.log(movieSnapshot.getKey());
            }
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

Maximum number of threads per process in Linux?

To set permanently,

vim /etc/sysctl.conf

and add

kernel.threads-max = "value"

Java: is there a map function?

There is no notion of a function in the JDK as of java 6.

Guava has a Function interface though and the
Collections2.transform(Collection<E>, Function<E,E2>)
method provides the functionality you require.

Example:

// example, converts a collection of integers to their
// hexadecimal string representations
final Collection<Integer> input = Arrays.asList(10, 20, 30, 40, 50);
final Collection<String> output =
    Collections2.transform(input, new Function<Integer, String>(){

        @Override
        public String apply(final Integer input){
            return Integer.toHexString(input.intValue());
        }
    });
System.out.println(output);

Output:

[a, 14, 1e, 28, 32]

These days, with Java 8, there is actually a map function, so I'd probably write the code in a more concise way:

Collection<String> hex = input.stream()
                              .map(Integer::toHexString)
                              .collect(Collectors::toList);

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

The error in question may also be caused by disabled JarScanner in tomcat/conf/context.xml.

See also Upgrade from Tomcat 8.0.39 to 8.0.41 results in 'failed to scan' errors.

<JarScanner scanManifest="false"/> allows to avoid both problems.

Using bootstrap with bower

Also remember that with a command like:

bower search twitter

You get a result with a list of any package related to twitter. This way you are up to date of everything regarding Twitter and Bower like for instance knowing if there is brand new bower component.

Assigning more than one class for one event

Approach #1

function doSomething(){
    if ($(this).hasClass('clickedTag')){
        // code here
    }
    else {
         // and here
    }
}

$('.tag1').click(doSomething);
$('.tag2').click(doSomething);

// or, simplifying further
$(".tag1, .tag2").click(doSomething);

Approach #2

This will also work:

?$(".tag1, .tag2").click(function(){
   alert("clicked");    
});?

Fiddle

I prefer a separate function (approach #1) if there is a chance that logic will be reused.

See also How can I select an element with multiple classes? for handling multiple classes on the same item.

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

Although this is a old thread, I have come across the same error recently while running nslookup in CentOS 7 and google search led me to some of the discussions in SO including this one. However, adding the nameservers entries to /etc/resolv.conf alone did not help as the nameserver values in resolv.conf were overwritten by the NetworkManager with the default DNS nameservers that are in the eth profile associated to the ethernet IP config.

As mentioned by @m-canvar, set the following entries in /etc/resolv.conf

search yourdomain.com
nameserver 8.8.8.8
nameserver 4.2.2.1
nameserver 8.8.4.4

To prevent overwriting these entries by NetworkManager, there are two two approaches:

Option 1: Either set NM_CONTROLLED=no in the eth profile associated to the IPv4/IPv6 profile.

Option 2: Disable NetworkManager service from running.

chkconfig NetworkManager off
service NetworkManager stop

More details can be referred in my post about this error and solution.

str_replace with array

Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :

$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
    $query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;

Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

CSS - display: none; not working

Remove display: block; in the div #tfl style property

<div id="tfl" style="display: block; width: 187px; height: 260px;

Inline style take priority then css file

Cannot install Aptana Studio 3.6 on Windows

If your issue is related to a failed Windows install, and you are receiving a message related to installer _jsnode_windows.msi CRC error:

Aptana Studio (Aptana Studio 3, build: 3.6.1.201410201044) currently requires Nodejs 0.5.XX-0.11.xx

Even though the current release of nodejs seems to be 5.X.X . Apparently there will be a new release in Nov 2015 that corrects this defect.

Pre-installing x0.10.36-x64 allowed me to proceed with a successful install. If version numbers can be believed, this seems to be an ancient release of nodejs, but hey - I saw a very impressive demo of Aptana Studio and really wanted to install it. :-)

I also pre-installed GIT for windows, but I'm not sure if that was necessary or not.

Android Studio - Gradle sync project failed

Update for 2018:

I have faced this issue recently and it was resolved by updating android studio & updating gradle when prompted then rebuilding the project

How can I inject a property value into a Spring Bean which was configured using annotations?

You can do this in Spring 3 using EL support. Example:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

systemProperties is an implicit object and strategyBean is a bean name.

One more example, which works when you want to grab a property from a Properties object. It also shows that you can apply @Value to fields:

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;

Here is a blog post I wrote about this for a little more info.

copy db file with adb pull results in 'permission denied' error

  1. Create a folder in sdcard :
adb shell "su 0 mkdir /sdcard/com.test"
  1. Move your files to the new folder :
adb shell "su 0 mv -F /data/data/com.test/files/ /sdcard/com.test/"
  1. You can now use adb pull :
adb pull /sdcard/com.test

How to center text vertically with a large font-awesome icon?

Another option to fine-tune the line height of an icon is by using a percentage of the vertical-align property. Usually, 0% is a the bottom, and 100% at the top, but one could use negative values or more than a hundred to create interesting effects.

.my-element i.fa {
    vertical-align: 100%; // top
    vertical-align: 50%; // middle
    vertical-align: 0%; // bottom
}

Practical uses of different data structures

Few more Practical Application of data structures

Red-Black Trees (Used when there is frequent Insertion/Deletion and few searches) - K-mean Clustering using red black tree, Databases, Simple-minded database, searching words inside dictionaries, searching on web

AVL Trees (More Search and less of Insertion/Deletion) - Data Analysis and Data Mining and the applications which involves more searches

Min Heap - Clustering Algorithms

UITableViewCell Selected Background Color on Multiple Selection

You can also set cell's selectionStyle to.none in interface builder. The same solution as @AhmedLotfy provided, only from IB.

enter image description here

Is there a concise way to iterate over a stream with indices in Java 8?

In addition to protonpack, jOO?'s Seq provides this functionality (and by extension libraries that build on it like cyclops-react, I am the author of this library).

Seq.seq(Stream.of(names)).zipWithIndex()
                         .filter( namesWithIndex -> namesWithIndex.v1.length() <= namesWithIndex.v2 + 1)
                         .toList();

Seq also supports just Seq.of(names) and will build a JDK Stream under the covers.

The simple-react equivalent would similarly look like

 LazyFutureStream.of(names)
                 .zipWithIndex()
                 .filter( namesWithIndex -> namesWithIndex.v1.length() <= namesWithIndex.v2 + 1)
                 .toList();

The simple-react version is more tailored for asynchronous / concurrent processing.

How do I print colored output with Python 3?

I would like to show you about how to color code. There is also a game to it if you would like to play it down below. Copy and paste if you would like and make sure to have a good day everyone! Also, this is for Python 3, not 2. ( Game )

   # The Color Game!
# Thank you for playing this game.
# Hope you enjoy and please do not copy it. Thank you!

#

import colorama
from colorama import Fore
score = 0

def Check_Answer(answer):
    if (answer == "no"):
        print('correct')
        return True
    else:
        print('wrong')

answer = input((Fore.RED + "This is green."))
if Check_Answer(answer) == True:
    score = score + 1
else:
    pass

answer = input((Fore.BLACK + "This is red."))
if Check_Answer(answer) == True:
    score = score + 1
else:
    pass

answer = input((Fore.BLUE + "This is black."))

if Check_Answer(answer) == True:
    score = score + 1
else:
    pass

print('Your Score is ', score)

Now for the color coding. It also comes with a list of colors YOU can try.

# Here is how to color code in Python 3!
# Some featured color codes are : RED, BLUE, GREEN, YELLOW, OR WHITE. I don't think purple or pink are not out yet.
# Here is how to do it. (Example is down below!)

import colorama
from colorama import Fore
print(Fore.RED + "This is red..")

How to check programmatically if an application is installed or not in Android?

Try with this:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Add respective layout
        setContentView(R.layout.main_activity);

        // Use package name which we want to check
        boolean isAppInstalled = appInstalledOrNot("com.check.application");  

        if(isAppInstalled) {
            //This intent will help you to launch if the package is already installed
            Intent LaunchIntent = getPackageManager()
                .getLaunchIntentForPackage("com.check.application");
            startActivity(LaunchIntent);

            Log.i("Application is already installed.");       
        } else {
            // Do whatever we want to do if application not installed
            // For example, Redirect to play store

            Log.i("Application is not currently installed.");
        }
    }

    private boolean appInstalledOrNot(String uri) {
        PackageManager pm = getPackageManager();
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
        }

        return false;
    }

}

How do I move an existing Git submodule within a Git repository?

In my case, I wanted to move a submodule from one directory into a subdirectory, e.g. "AFNetworking" -> "ext/AFNetworking". These are the steps I followed:

  1. Edit .gitmodules changing submodule name and path to be "ext/AFNetworking"
  2. Move submodule's git directory from ".git/modules/AFNetworking" to ".git/modules/ext/AFNetworking"
  3. Move library from "AFNetworking" to "ext/AFNetworking"
  4. Edit ".git/modules/ext/AFNetworking/config" and fix the [core] worktree line. Mine changed from ../../../AFNetworking to ../../../../ext/AFNetworking
  5. Edit "ext/AFNetworking/.git" and fix gitdir. Mine changed from ../.git/modules/AFNetworking to ../../git/modules/ext/AFNetworking
  6. git add .gitmodules
  7. git rm --cached AFNetworking
  8. git submodule add -f <url> ext/AFNetworking

Finally, I saw in the git status:

matt$ git status
# On branch ios-master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   .gitmodules
#   renamed:    AFNetworking -> ext/AFNetworking

Et voila. The above example doesn't change the directory depth, which makes a big difference to the complexity of the task, and doesn't change the name of the submodule (which may not really be necessary, but I did it to be consistent with what would happen if I added a new module at that path.)

React : difference between <Route exact path="/" /> and <Route path="/" />

Please try this.

       <Router>
          <div>
            <Route exact path="/" component={Home} />
            <Route path="/news" component={NewsFeed} />
          </div>
        </Router> 

            

Why is setTimeout(fn, 0) sometimes useful?

The problem was you were trying to perform a Javascript operation on a non existing element. The element was yet to be loaded and setTimeout() gives more time for an element to load in the following ways:

  1. setTimeout() causes the event to be ansynchronous therefore being executed after all the synchronous code, giving your element more time to load. Asynchronous callbacks like the callback in setTimeout() are placed in the event queue and put on the stack by the event loop after the stack of synchronous code is empty.
  2. The value 0 for ms as a second argument in function setTimeout() is often slightly higher (4-10ms depending on browser). This slightly higher time needed for executing the setTimeout() callbacks is caused by the amount of 'ticks' (where a tick is pushing a callback on the stack if stack is empty) of the event loop. Because of performance and battery life reasons the amount of ticks in the event loop are restricted to a certain amount less than 1000 times per second.

Changing the page title with Jquery

I use this one:

document.title = "your_customize_title";

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

How can I stop redis-server?

systemd, ubuntu 16.04:

$ sudo systemctl is-active redis-server
active

$ sudo systemctl is-enabled redis-server
enabled

$ sudo systemctl disable redis-server
Synchronizing state of redis-server.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install disable redis-server
Removed /etc/systemd/system/redis.service.

$ sudo systemctl stop redis-server

"SMTP Error: Could not authenticate" in PHPMailer

There is no issue with your code.

Follow below two simple steps to send emails from phpmailer.

  • You have to disable 2-step verification setting for google account if you have enabled.

  • Turn ON allow access to less secure app.

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

How do you add a Dictionary of items into another Dictionary

Swift 3:

extension Dictionary {

    mutating func merge(with dictionary: Dictionary) {
        dictionary.forEach { updateValue($1, forKey: $0) }
    }

    func merged(with dictionary: Dictionary) -> Dictionary {
        var dict = self
        dict.merge(with: dictionary)
        return dict
    }
}

let a = ["a":"b"]
let b = ["1":"2"]
let c = a.merged(with: b)

print(c) //["a": "b", "1": "2"]

Is there a 'foreach' function in Python 3?

I think this answers your question, because it is like a "for each" loop.
The script below is valid in python (version 3.8):

a=[1,7,77,7777,77777,777777,7777777,765,456,345,2342,4]
if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

How to use session in JSP pages to get information?

JSP implicit objects likes session, request etc. are not available inside JSP declaration <%! %> tags.

You could use it directly in your expression as

<td>Username: </td>
<td><input type="text" value="<%= session.getAttribute("username") %>" /></td>

On other note, using scriptlets in JSP has been long deprecated. Use of EL (expression language) and JSTL tags is highly recommended. For example, here you could use EL as

<td>Username: </td>
<td><input type="text" value="${username}" /></td>

The best part is that scope resolution is done automatically. So, here username could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as

<td><input type="text" value="${requestScope.username}" /></td> or,
<td><input type="text" value="${sessionScope.username}" /></td> or,
<td><input type="text" value="${applicationScope.username}" /></td>

"break;" out of "if" statement?

I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if inside. So, I'll try to answer this question with this particular interpretation.

If you have if inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if or was it ended "naturally"? So, your sample code can be modified in this way:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; break;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

The problem with this code is that the if statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break statement) variant will be:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; continue;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.

UPDATE:

Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break to exit from both loops and switch.

Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.

Correct way to delete cookies server-side

For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :

public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
    ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
    Date expiry = time.toInstant().toEpochMilli();
    NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
    return newCookie;
}

And use it the common way to set cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

and to delete the cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

org.hibernate.PersistentObjectException: detached entity passed to persist

Two solutions 1. use merge if you want to update the object 2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it) 3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL) @JoinColumn(name = "stock_id")

Then use CascadeType.ALL to CascadeType.MERGE

thanks Shahid Abbasi

Oracle PL/SQL : remove "space characters" from a string

Shorter version of:

REGEXP_REPLACE( my_value, '[[:space:]]', '' )

Would be:

REGEXP_REPLACE( my_value, '\s')

Neither of the above statements will remove "null" characters.

To remove "nulls" encase the statement with a replace

Like so:

REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))

How to rename a pane in tmux?

For those scripting tmux, there is a command called rename-window so e.g.

tmux rename-window -t <window> <newname>

Making HTTP Requests using Chrome Developer tools

To GET requests with headers, use this format.

   fetch('http://example.com', {
      method: 'GET',
      headers: new Headers({
               'Content-Type': 'application/json',
               'someheader': 'headervalue'
               })
    })
    .then(res => res.json())
    .then(console.log)

How to change color of ListView items on focus and on click

<selector xmlns:android="http://schemas.android.com/apk/res/android" >    
    <item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" /> 
    <item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>

Using Python's list index() method on a list of tuples or objects?

One possibility is to use the itemgetter function from the operator module:

import operator

f = operator.itemgetter(0)
print map(f, tuple_list).index("cherry") # yields 1

The call to itemgetter returns a function that will do the equivalent of foo[0] for anything passed to it. Using map, you then apply that function to each tuple, extracting the info into a new list, on which you then call index as normal.

map(f, tuple_list)

is equivalent to:

[f(tuple_list[0]), f(tuple_list[1]), ...etc]

which in turn is equivalent to:

[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]

which gives:

["pineapple", "cherry", ...etc]

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

Boxplot show the value of mean

You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:

fun_mean <- function(x){
  return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}


ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)

enter image description here

PHP: merge two arrays while keeping keys instead of reindexing?

Hello year 2010 question.

The OP.'s requirement is preserve keys (keep keys) and not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to be not possible.

If you use array_merge() the numeric keys will always re-index or renumbered.
If you use array_replace(), array_replace_recursive() it will be overlap or overwrite from the right to the left. The value with the same key on first array will be replaced with second array.
If you use $array1 + $array2 as the comment was mentioned, if the keys are same then it will keep the value from first array but drop the second array.

Custom function.

Here is my function that I just wrote to work on the same requirements. You are free to use for any purpose.

/**
 * Array custom merge. Preserve indexed array key (numbers) but overwrite string key (same as PHP's `array_merge()` function).
 * 
 * If the another array key is string, it will be overwrite the first array.<br>
 * If the another array key is integer, it will be add to first array depend on duplicated key or not. 
 * If it is not duplicate key with the first, the key will be preserve and add to the first array.
 * If it is duplicated then it will be re-index the number append to the first array.
 *
 * @param array $array1 The first array is main array.
 * @param array ...$arrays The another arrays to merge with the first.
 * @return array Return merged array.
 */
function arrayCustomMerge(array $array1, array ...$arrays): array
{
    foreach ($arrays as $additionalArray) {
        foreach ($additionalArray as $key => $item) {
            if (is_string($key)) {
                // if associative array.
                // item on the right will always overwrite on the left.
                $array1[$key] = $item;
            } elseif (is_int($key) && !array_key_exists($key, $array1)) {
                // if key is number. this should be indexed array.
                // and if array 1 is not already has this key.
                // add this array with the key preserved to array 1.
                $array1[$key] = $item;
            } else {
                // if anything else...
                // get all keys from array 1 (numbers only).
                $array1Keys = array_filter(array_keys($array1), 'is_int');
                // next key index = get max array key number + 1.
                $nextKeyIndex = (intval(max($array1Keys)) + 1);
                unset($array1Keys);
                // set array with the next key index.
                $array1[$nextKeyIndex] = $item;
                unset($nextKeyIndex);
            }
        }// endforeach; $additionalArray
        unset($item, $key);
    }// endforeach;
    unset($additionalArray);

    return $array1;
}// arrayCustomMerge

Testing.

<?php
$array1 = [
    'cat', 
    'bear', 
    'fruitred' => 'apple',
    3.1 => 'dog',
    null => 'null',
];
$array2 = [
    1 => 'polar bear',
    20 => 'monkey',
    'fruitred' => 'strawberry',
    'fruityellow' => 'banana',
    null => 'another null',
];

// require `arrayCustomMerge()` function here.

function printDebug($message)
{
    echo '<pre>';
    print_r($message);
    echo '</pre>' . PHP_EOL;
}

echo 'array1: <br>';
printDebug($array1);
echo 'array2: <br>';
printDebug($array2);


echo PHP_EOL . '<hr>' . PHP_EOL . PHP_EOL;


echo 'arrayCustomMerge:<br>';
$merged = arrayCustomMerge($array1, $array2);
printDebug($merged);


assert($merged[0] == 'cat', 'array key 0 should be \'cat\'');
assert($merged[1] == 'bear', 'array key 1 should be \'bear\'');
assert($merged['fruitred'] == 'strawberry', 'array key \'fruitred\' should be \'strawberry\'');
assert($merged[3] == 'dog', 'array key 3 should be \'dog\'');
assert(array_search('another null', $merged) !== false, '\'another null\' should be merged.');
assert(array_search('polar bear', $merged) !== false, '\'polar bear\' should be merged.');
assert($merged[20] == 'monkey', 'array key 20 should be \'monkey\'');
assert($merged['fruityellow'] == 'banana', 'array key \'fruityellow\' should be \'banana\'');
The results.
array1:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => apple
    [3] => dog
    [] => null
)

array2:

Array
(
    [1] => polar bear
    [20] => monkey
    [fruitred] => strawberry
    [fruityellow] => banana
    [] => another null
)

---
arrayCustomMerge:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => strawberry
    [3] => dog
    [] => another null
    [4] => polar bear
    [20] => monkey
    [fruityellow] => banana
)

How to compare two dates along with time in java

An alternative is Joda-Time.

Use DateTime

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();

Get the (last part of) current directory name in C#

This is a slightly different answer, depending on what you have. If you have a list of files and need to get the name of the last directory that the file is in you can do this:

string path = "/attachments/1828_clientid/2938_parentid/somefiles.docx";
string result = new DirectoryInfo(path).Parent.Name;

This will return "2938_parentid"

What is the difference between Normalize.css and Reset CSS?

The major difference is that:

  • CSS resets aim to remove all built-in browser styling. Standard elements like H1-6, p, strong, em, et cetera end up looking exactly alike, having no decoration at all. You're then supposed to add all decoration yourself.

  • Normalize CSS aims to make built-in browser styling consistent across browsers. Elements like H1-6 will appear bold, larger et cetera in a consistent way across browsers. You're then supposed to add only the difference in decoration your design needs.

If your design a) follows common conventions for typography et cetera, and b) Normalize.css works for your target audience, then using Normalize.CSS instead of a CSS reset will make your own CSS smaller and faster to write.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I have a similar problem and as I'm newbie, here are some facts for somebody to comment:

I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):

fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))

Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Edge execution Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: Chrome execution The value in the second column is blocked:other and there is also an error in Console tab:

GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT

In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests: Incognito execution

My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).

How to find indices of all occurrences of one string in another in JavaScript?

Here is regex free version:

function indexes(source, find) {
  if (!source) {
    return [];
  }
  // if find is empty string return all indexes.
  if (!find) {
    // or shorter arrow function:
    // return source.split('').map((_,i) => i);
    return source.split('').map(function(_, i) { return i; });
  }
  var result = [];
  for (i = 0; i < source.length; ++i) {
    // If you want to search case insensitive use 
    // if (source.substring(i, i + find.length).toLowerCase() == find) {
    if (source.substring(i, i + find.length) == find) {
      result.push(i);
    }
  }
  return result;
}

indexes("I learned to play the Ukulele in Lebanon.", "le")

EDIT: and if you want to match strings like 'aaaa' and 'aa' to find [0, 2] use this version:

function indexes(source, find) {
  if (!source) {
    return [];
  }
  if (!find) {
      return source.split('').map(function(_, i) { return i; });
  }
  var result = [];
  var i = 0;
  while(i < source.length) {
    if (source.substring(i, i + find.length) == find) {
      result.push(i);
      i += find.length;
    } else {
      i++;
    }
  }
  return result;
}

How to make inline plots in Jupyter Notebook larger?

Yes, play with figuresize and dpi like so (before you call your subplot):

fig=plt.figure(figsize=(12,8), dpi= 100, facecolor='w', edgecolor='k')

As @tacaswell and @Hagne pointed out, you can also change the defaults if it's not a one-off:

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 100 # 200 e.g. is really fine, but slower

How do I find out my MySQL URL, host, port and username?

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

How to upload file to server with HTTP POST multipart/form-data?

Here is what worked for me while sending the file as mult-form data:

    public T HttpPostMultiPartFileStream<T>(string requestURL, string filePath, string fileName)
    {
        string content = null;

        using (MultipartFormDataContent form = new MultipartFormDataContent())
        {
            StreamContent streamContent;
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                streamContent = new StreamContent(fileStream);

                streamContent.Headers.Add("Content-Type", "application/octet-stream");
                streamContent.Headers.Add("Content-Disposition", string.Format("form-data; name=\"file\"; filename=\"{0}\"", fileName));
                form.Add(streamContent, "file", fileName);

                using (HttpClient client = GetAuthenticatedHttpClient())
                {
                    HttpResponseMessage response = client.PostAsync(requestURL, form).GetAwaiter().GetResult();
                    content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();



                    try
                    {
                        return JsonConvert.DeserializeObject<T>(content);
                    }
                    catch (Exception ex)
                    {
                        // Log the exception
                    }

                    return default(T);
                }
            }
        }
    }

GetAuthenticatedHttpClient used above can be:

private HttpClient GetAuthenticatedHttpClient()
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri(<yourBaseURL>));
    httpClient.DefaultRequestHeaders.Add("Token, <yourToken>);
    return httpClient;
}

Get user location by IP address

IPInfoDB has an API that you can call in order to find a location based on an IP address.

For "City Precision", you call it like this (you'll need to register to get a free API key):

 http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

Here's an example in both VB and C# that shows how to call the API.

How to delete mysql database through shell command

Try the following command:

mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]

Difference between using Makefile and CMake to compile the code

The statement about CMake being a "build generator" is a common misconception.

It's not technically wrong; it just describes HOW it works, but not WHAT it does.

In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.

So, what is the real difference?

  • CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make has some built-in C/C++ rules as well, but they are useless at best.

  • CMake does a two-step build: it generates a low-level build script in ninja or make or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile are only executed at the generation stage. Thus, CMake build can be orders of magnitude faster.

  • The grammar of CMake is much easier to support for external tools than make's.

  • Once make builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake tracks it, make leaves it up to you. If one of library sources was removed since the previous version of Makefile, make won't rebuild it.

  • Modern CMake (starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies. These transitive dependencies can be exposed to or hidden from the dependent packages. CMake will manage directories for you. With make, you're stuck on a file-by-file and manage-directories-by-hand level.

You could code up something in make using intermediate files to cover the last two gaps, but you're on your own. make does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.

To be honest, this is what CMake and make have in common -- their languages are pretty horrible. Here's what comes to mind:

  • They have no user-defined types;
  • CMake has three data types: string, list, and a target with properties. make has one: string;
  • you normally pass arguments to functions by setting global variables.
    • This is partially dealt with in modern CMake - you can set a target's properties: set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}");
  • referring to an undefined variable is silently ignored by default;

'Framework not found' in Xcode

delete all frameworks from Embedded Binaries and re-add it

npm install Error: rollbackFailedOptional

Make sure you can access the corporate repository you configured in npm is available.Check you VPN connection.

Else reset it back to default repository like below.

npm config set registry http://registry.npmjs.org/

Good Luck!!

How to implement HorizontalScrollView like Gallery?

Try this code:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="100dip"
tools:context=".MainActivity" >
<HorizontalScrollView
    android:id="@+id/hsv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:fillViewport="true"
    android:measureAllChildren="false"
    android:scrollbars="none" >
    <LinearLayout
        android:id="@+id/innerLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >
        <LinearLayout
            android:id="@+id/asthma_action_plan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/action_plan" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/controlled_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/controlled" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/as_needed_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/as_needed" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/rescue_medication"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/rescue" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_symptoms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/symptoms" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/your_triggers"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/triggers" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/wheeze_rate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/wheeze_rate" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/peak_flow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="match_parent" >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/peak_flow" />
                <TextView
                    android:layout_width="0.2dp"
                    android:layout_height="fill_parent"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ln" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>
</HorizontalScrollView>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="0.2dp"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/hsv"
    android:background="@drawable/ln" />
<LinearLayout
    android:id="@+id/prev"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/prev_arrow" />
</LinearLayout>
<LinearLayout
    android:id="@+id/next"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:paddingLeft="5dip"
    android:paddingRight="5dip"
    android:descendantFocusability="blocksDescendants" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/next_arrow" />
</LinearLayout>
</RelativeLayout>

grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:src="@drawable/ic_launcher" />
</LinearLayout>

MainActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
        rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;

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

    prev = (LinearLayout) findViewById(R.id.prev);
    next = (LinearLayout) findViewById(R.id.next);
    horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
    gestureDetector = new GestureDetector(new MyGestureDetector());
    asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
    controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
    asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
    rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
    yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
    yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
    wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
    peakFlow = (LinearLayout) findViewById(R.id.peak_flow);

    Display display = getWindowManager().getDefaultDisplay();
    mWidth = display.getWidth(); // deprecated
    viewWidth = mWidth / 3;
    layouts = new ArrayList<LinearLayout>();
    params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);

    asthmaActionPlan.setLayoutParams(params);
    controlledMedication.setLayoutParams(params);
    asNeededMedication.setLayoutParams(params);
    rescueMedication.setLayoutParams(params);
    yourSymtoms.setLayoutParams(params);
    yourTriggers.setLayoutParams(params);
    wheezeRate.setLayoutParams(params);
    peakFlow.setLayoutParams(params);

    layouts.add(asthmaActionPlan);
    layouts.add(controlledMedication);
    layouts.add(asNeededMedication);
    layouts.add(rescueMedication);
    layouts.add(yourSymtoms);
    layouts.add(yourTriggers);
    layouts.add(wheezeRate);
    layouts.add(peakFlow);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    + viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    horizontalScrollView.smoothScrollTo(
                            (int) horizontalScrollView.getScrollX()
                                    - viewWidth,
                            (int) horizontalScrollView.getScrollY());
                }
            }, 100L);
        }
    });

    horizontalScrollView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }
            return false;
        }
    });
}

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        if (e1.getX() < e2.getX()) {
            currPosition = getVisibleViews("left");
        } else {
            currPosition = getVisibleViews("right");
        }

        horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
                .getLeft(), 0);
        return true;
    }
}

public int getVisibleViews(String direction) {
    Rect hitRect = new Rect();
    int position = 0;
    int rightCounter = 0;
    for (int i = 0; i < layouts.size(); i++) {
        if (layouts.get(i).getLocalVisibleRect(hitRect)) {
            if (direction.equals("left")) {
                position = i;
                break;
            } else if (direction.equals("right")) {
                rightCounter++;
                position = i;
                if (rightCounter == 2)
                    break;
            }
        }
    }
    return position;
}
}

Let me know if any issue enjoy...

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

2019: Use AppCompatActivity

At the time of this writing (check the link to confirm it is still true), the Android Documentation recommends using AppCompatActivity if you are using an App Bar.

This is the rational given:

Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library's version of Toolbar, and they are available on any device that can use the support library.

For this reason, you should use the support library's Toolbar class to implement your activities' app bars. Using the support library's toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material design experience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn't support material design unless the device is running Android 5.0 (API level 21) or later.

The general directions for adding a ToolBar are

  1. Add the v7 appcompat support library
  2. Make all your activities extend AppCompatActivity
  3. In the Manifest declare that you want NoActionBar.
  4. Add a ToolBar to each activity's xml layout.
  5. Get the ToolBar in each activity's onCreate.

See the documentation directions for more details. They are quite clear and helpful.

How to get enum value by string or int

Simply try this

It's another way

public enum CaseOriginCode
{
    Web = 0,
    Email = 1,
    Telefoon = 2
}

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}

Adding backslashes without escaping [Python]

printing a list can also cause this problem (im new in python, so it confused me a bit too):

>>>myList = ['\\']
>>>print myList
['\\']
>>>print ''.join(myList)
\ 

similarly:

>>>myList = ['\&']
>>>print myList
['\\&']
>>>print ''.join(myList)
\&

How can I list ALL DNS records?

When you query for ANY you will get a list of all records at that level but not below.

# try this
dig google.com any

This may return A records, TXT records, NS records, MX records, etc if the domain name is exactly "google.com". However, it will not return child records (e.g., www.google.com). More precisely, you MAY get these records if they exist. The name server does not have to return these records if it chooses not to do so (for example, to reduce the size of the response).

An AXFR is a zone transfer and is likely what you want. However, these are typically restricted and not available unless you control the zone. You'll usually conduct a zone transfer directly from the authoritative server (the @ns1.google.com below) and often from a name server that may not be published (a stealth name server).

# This will return "Transfer failed"
dig @ns1.google.com google.com axfr

If you have control of the zone, you can set it up to get transfers that are protected with a TSIG key. This is a shared secret the the client can send to the server to authorize the transfer.

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

how do I insert a column at a specific column index in pandas?

df.insert(loc, column_name, value)

This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.

You can pass an optional parameter allow_duplicates with True value to create a new column with already existing column name.

Here is an example:



    >>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
    >>> df
       b  c
    0  1  3
    1  2  4
    >>> df.insert(0, 'a', -1)
    >>> df
       a  b  c
    0 -1  1  3
    1 -1  2  4
    >>> df.insert(0, 'a', -2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
        self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
      File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
        raise ValueError(f"cannot insert {item}, already exists")
    ValueError: cannot insert a, already exists
    >>> df.insert(0, 'a', -2,  allow_duplicates = True)
    >>> df
       a  a  b  c
    0 -2 -1  1  3
    1 -2 -1  2  4

What's a good way to extend Error in JavaScript?

I would take a step back and consider why you want to do that? I think the point is to deal with different errors differently.

For example, in Python, you can restrict the catch statement to only catch MyValidationError, and perhaps you want to be able to do something similar in javascript.

catch (MyValidationError e) {
    ....
}

You can't do this in javascript. There's only going to be one catch block. You're supposed to use an if statement on the error to determine its type.

catch(e) { if(isMyValidationError(e)) { ... } else { // maybe rethrow? throw e; } }

I think I would instead throw a raw object with a type, message, and any other properties you see fit.

throw { type: "validation", message: "Invalid timestamp" }

And when you catch the error:

catch(e) {
    if(e.type === "validation") {
         // handle error
    }
    // re-throw, or whatever else
}

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

What is Android's file system?

Johan is close - it depends on the hardware manufacturer. For example, Samsung Galaxy S phones uses Samsung RFS (proprietary). However, the Nexus S (also made by Samsung) with Android 2.3 uses Ext4 (presumably because Google told them to - the Nexus S is the current Google experience phone). Many community developers have also started moving to Ext4 because of this shift.

C# delete a folder and all files and folders within that folder

For those of you running into the DirectoryNotFoundException, add this check:

if (Directory.Exists(path)) Directory.Delete(path, true);

I can't install python-ldap

"Don't blindly remove/install software"

In a Ubuntu/Debian based distro, you could use apt-file to find the name of the exact package that includes the missing header file.

# do this once
sudo apt-get install apt-file
sudo apt-file update

$ apt-file search lber.h
libldap2-dev: /usr/include/lber.h

As you could see from the output of apt-file search lber.h, you'd just need to install the package libldap2-dev.

sudo apt-get install libldap2-dev

How to use greater than operator with date?

I have tried but above not working after research found below the solution.

SELECT * FROM my_table where DATE(start_date) > '2011-01-01';

Ref

UICollectionView auto scroll to cell at IndexPath

As an alternative to mentioned above. Call after data load:

Swift

collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .right)

How can I list ALL grants a user received?

select distinct 'GRANT '||privilege||' ON '||OWNER||'.'||TABLE_NAME||' TO '||RP.GRANTEE
from DBA_ROLE_PRIVS RP join ROLE_TAB_PRIVS RTP 
on (RP.GRANTED_ROLE = RTP.role)  
where (OWNER in ('YOUR USER') --Change User Name
   OR RP.GRANTEE in ('YOUR USER')) --Change User Name
and RP.GRANTEE not in ('SYS', 'SYSTEM')
;

How do I use an image as a submit button?

Why not:

<button type="submit">
<img src="mybutton.jpg" />
</button>

How to generate classes from wsdl using Maven and wsimport?

Even though this is bit late response, may be helpful for someone. Look like you have used pluginManagement. If you use pluginManagement , it will not pick the plug-in execution.

It should be under

<build>
<plugins>           
        <plugin> 

MVC 4 - how do I pass model data to a partial view?

Three ways to pass model data to partial view (there may be more)

This is view page

Method One Populate at view

@{    
    PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
    ctry1.CountryName="India";
    ctry1.ID=1;    

    PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
    ctry2.CountryName="Africa";
    ctry2.ID=2;

    List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
    CountryList.Add(ctry1);
    CountryList.Add(ctry2);    

}

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}

Method Two Pass Through ViewBag

@{
    var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}

Method Three pass through model

@{
    Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

enter image description here

Linux shell sort file according to the second column?

FWIW, here is a sort method for showing which processes are using the most virt memory.

memstat | sort -k 1 -t':' -g -r | less

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

How to get the separate digits of an int number?

Integer.toString(1100) gives you the integer as a string. Integer.toString(1100).getBytes() to get an array of bytes of the individual digits.

Edit:

You can convert the character digits into numeric digits, thus:

  String string = Integer.toString(1234);
  int[] digits = new int[string.length()];

  for(int i = 0; i<string.length(); ++i){
    digits[i] = Integer.parseInt(string.substring(i, i+1));
  }
  System.out.println("digits:" + Arrays.toString(digits));

use a javascript array to fill up a drop down select box

Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.

var cuisines = ["Chinese","Indian"];     
var sel = document.getElementById('CuisineList');
for(var i = 0; i < cuisines.length; i++) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisines[i];
    opt.value = cuisines[i];
    sel.appendChild(opt);
}

DEMO

UPDATE: Using createDocumentFragment and forEach

If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.

var cuisines = ["Chinese","Indian"];     

var sel = document.getElementById('CuisineList');
var fragment = document.createDocumentFragment();

cuisines.forEach(function(cuisine, index) {
    var opt = document.createElement('option');
    opt.innerHTML = cuisine;
    opt.value = cuisine;
    fragment.appendChild(opt);
});

sel.appendChild(fragment);

DEMO

Opening new window in HTML for target="_blank"

You can't influence neither type (tab/window) nor dimensions that way. You'll have to use JavaScript's window.open() for that.

How do I remove an object from an array with JavaScript?

var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];

// get index of object with id:37

var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);

Spring Boot + JPA : Column name annotation ignored

For hibernate5 I solved this issue by puting next lines in my application.properties file:

spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Render HTML in React Native

I found this component. https://github.com/jsdf/react-native-htmlview

This component takes HTML content and renders it as native views, with customisable style and handling of links, etc.

How can I convert a comma-separated string to an array?

Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

Adding a loop like this,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.

Vagrant stuck connection timeout retrying

My solution turned out to be none of the above exactly. I'm running Ubuntu 14 as guest inside a Windows 7 host. I had been running this vagrant box fine, but I started it up again after not using it for a couple of months, and it kept coming up with the SSH connection timeout. It turned out that somehow the key pair didn't work - so I copied the Vagrant public key into Ubuntu according to the instructions on this page. But that wasn't all. I then discovered that the private key in my base box was different than the private key here. Putting this private key in as the vagrant_private_key file in C:\Users\your-user.vagrant.d\boxes\vagrant-box-name\nnnnnnnn\virtualbox after placing the public key into Ubuntu fixed the problem.

Selector on background color of TextView

Even this works.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:state_focused="true" android:drawable="@color/dim_orange_btn_pressed" />
    <item android:drawable="@android:color/white" />
</selector>

I added the android:drawable attribute to each item, and their values are colors.

By the way, why do they say that color is one of the attributes of selector? They don't write that android:drawable is required.

Color State List Resource

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

How can I make a list of lists in R?

Using your example::

list1 <- list()
list1[1] = 1
list1[2] = 2
list2 <- list()
list2[1] = 'a'
list2[2] = 'b'
list_all <- list(list1, list2)

Use '[[' to retrieve an element of a list:

b = list_all[[1]]
 b
[[1]]
[1] 1

[[2]]
[1] 2

class(b)
[1] "list"

Can I install the "app store" in an IOS simulator?

No, according to Apple here:

Note: You cannot install apps from the App Store in simulation environments.

CSS how to make an element fade in and then fade out?

Use css @keyframes

.elementToFadeInAndOut {
    opacity: 1;
    animation: fade 2s linear;
}


@keyframes fade {
  0%,100% { opacity: 0 }
  50% { opacity: 1 }
}

here is a DEMO

_x000D_
_x000D_
.elementToFadeInAndOut {_x000D_
    width:200px;_x000D_
    height: 200px;_x000D_
    background: red;_x000D_
    -webkit-animation: fadeinout 4s linear forwards;_x000D_
    animation: fadeinout 4s linear forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
  0%,100% { opacity: 0; }_x000D_
  50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
  0%,100% { opacity: 0; }_x000D_
  50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
_x000D_
_x000D_

Reading: Using CSS animations

You can clean the code by doing this:

_x000D_
_x000D_
.elementToFadeInAndOut {_x000D_
    width:200px;_x000D_
    height: 200px;_x000D_
    background: red;_x000D_
    -webkit-animation: fadeinout 4s linear forwards;_x000D_
    animation: fadeinout 4s linear forwards;_x000D_
    opacity: 0;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeinout {_x000D_
  50% { opacity: 1; }_x000D_
}_x000D_
_x000D_
@keyframes fadeinout {_x000D_
  50% { opacity: 1; }_x000D_
}
_x000D_
<div class=elementToFadeInAndOut></div>
_x000D_
_x000D_
_x000D_

What is the LD_PRELOAD trick?

it's easy to export mylib.so to env:

$ export LD_PRELOAD=/path/mylib.so
$ ./mybin

to disable :

$ export LD_PRELOAD=

What does elementFormDefault do in XSD?

I have noticed that XMLSpy(at least 2011 version)needs a targetNameSpace defined if elementFormDefault="qualified" is used. Otherwise won't validate. And also won't generate xmls with namespace prefixes

Rename all files in directory from $filename_h to $filename_half?

Are you looking for a pure bash solution? There are many approaches, but here's one.

for file in *_h.png ; do mv "$file" "${file%%_h.png}_half.png" ; done

This presumes that the only files in the current directory that end in _h.png are the ones you want to rename.

Much more specifically

for file in 0{5..6}_h.png ; do mv "$file" "${file/_h./_half.}" ; done

Presuming those two examples are your only. files.

For the general case, file renaming in has been covered before.

Checking if a file is a directory or just a file

Use the S_ISDIRmacro:

int isDirectory(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

Using context in a fragment

to get the context inside the Fragment will be possible using getActivity() :

public Database()
{
    this.context = getActivity();
    DBHelper = new DatabaseHelper(this.context);
}
  • Be careful, to get the Activity associated with the fragment using getActivity(), you can use it but is not recommended it will cause memory leaks.

I think a better aproach must be getting the Activity from the onAttach() method:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}

Better way to find control in ASP.NET

Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
                                                        where T : Control
{
    foreach (Control child in parent.Controls)
    {
        if (child is T)
        {
            yield return (T)child;
        }
        else if (child.Controls.Count > 0)
        {
            foreach (T grandChild in child.FindControlsOfType<T>())
            {
                yield return grandChild;
            }
        }
    }
}

How to change values in a tuple?

Frist, ask yourself why you want to mutate your tuple. There is a reason why strings and tuple are immutable in Ptyhon, if you want to mutate your tuple then it should probably be a list instead.

Second, if you still wish to mutate your tuple then you can convert your tuple to a list then convert it back, and reassign the new tuple to the same variable. This is great if you are only going to mutate your tuple once. Otherwise, I personally think that is counterintuitive. Because It is essentially creating a new tuple and every time if you wish to mutate the tuple you would have to perform the conversion. Also If you read the code it would be confusing to think why not just create a list? But it is nice because it doesn't require any library.

I suggest using mutabletuple(typename, field_names, default=MtNoDefault) from mutabletuple 0.2. I personally think this way is a more intuitive and readable. The personal reading the code would know that writer intends to mutate this tuple in the future. The downside compares to the list conversion method above is that this requires you to import additional py file.

from mutabletuple import mutabletuple

myTuple = mutabletuple('myTuple', 'v w x y z')
p = myTuple('275', '54000', '0.0', '5000.0', '0.0')
print(p.v) #print 275
p.v = '200' #mutate myTuple
print(p.v) #print 200

TL;DR: Don't try to mutate tuple. if you do and it is a one-time operation convert tuple to list, mutate it, turn list into a new tuple, and reassign back to the variable holding old tuple. If desires tuple and somehow want to avoid listand want to mutate more than once then create mutabletuple.

How do you remove all the options of a select box and then add one option and select it with jQuery?

I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.

var ClearOptionsFast = function(id) {
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}

More info here.

ReSharper "Cannot resolve symbol" even when project builds

I tested ALL of the other answers in this page (before writing this answer) such as:

  1. VS -> Tools -> Options -> ReSharper Suspend button and Resume

  2. Clear ReSharper cache

  3. And others

But unfortunately none of them solved my problem. Maybe my problem was complicated than your problem. I said about them in my EDITs in the question, then the following answer was correct solution for me but maybe other answers solve your problem. please test them first.

I was forced to reinstall my OS and use a newer version of my tools. :(

Now i use VS 2013 + R# v8 and when i have any problem with my resharper i just try the following instruction and it solve my problems:

VS -> Tools -> Options -> ReSharper Suspend button and Resume

PHP - find entry by object property from an array of objects

I solved this problem by keying the array with the ID. It's simpler and possibly faster for this scenario where the ID is what you're looking for.

[420] => stdClass Object
        (
            [name] => Mary
         )

[10957] => stdClass Object
        (
            [name] => Blah
         )
...

Now I can directly address the array:

$array[$v]->name = ...

Or, if I want to verify the existence of an ID:

if (array_key_exists($v, $array)) { ...

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

How to list all databases in the mongo shell?

From the command line issue

mongo --quiet --eval  "printjson(db.adminCommand('listDatabases'))"

which gives output

{
    "databases" : [
        {
            "name" : "admin",
            "sizeOnDisk" : 978944,
            "empty" : false
        },
        {
            "name" : "local",
            "sizeOnDisk" : 77824,
            "empty" : false
        },
        {
            "name" : "meteor",
            "sizeOnDisk" : 778240,
            "empty" : false
        }
    ],
    "totalSize" : 1835008,
    "ok" : 1
}

How do I reload a page without a POSTDATA warning in Javascript?

You can't refresh without the warning; refresh instructs the browser to repeat the last action. It is up to the browser to choose whether to warn the user if repeating the last action involves resubmitting data.

You could re-navigate to the same page with a fresh session by doing:

window.location = window.location.href;

How do I select text nodes with jQuery?

if you want to strip all tags, then try this

function:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

usage:

var newText=$('selector').html().stripTags();

How to reverse MD5 to get the original string?

Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.

for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html

I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:

Bruter.java:

import java.util.ArrayList;

public class Bruter {

    public ArrayList<String> characters = new ArrayList<>();
    public boolean found = false;
    public int maxLength;
    public int minLength;
    public int count;
    long starttime, endtime;
    public int minutes, seconds, hours, days;
    public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
        '&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
        ';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
    public boolean done = false;
    public boolean paused = false;

    public boolean isFound() {
        return found;
    }

    public void setPaused(boolean paused) {
        this.paused = paused;
    }

    public boolean isPaused() {
        return paused;
    }

    public void setFound(boolean found) {
        this.found = found;
    }

    public synchronized void setEndtime(long endtime) {
        this.endtime = endtime;
    }

    public int getCounter() {
        return count;
    }

    public long getRemainder() {
        return getNumberOfPossibilities() - count;
    }

    public long getNumberOfPossibilities() {
        long possibilities = 0;
        for (int i = minLength; i <= maxLength; i++) {
            possibilities += (long) Math.pow(characters.size(), i);
        }
        return possibilities;
    }

    public void addExtendedSet() {
        for (char c = (char) 0; c <= (char) 31; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addStandardCharacterSet() {
        for (char c = (char) 32; c <= (char) 127; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addLowerCaseLetters() {
        for (char c = 'a'; c <= 'z'; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addDigits() {
        for (int c = 0; c <= 9; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addUpperCaseLetters() {
        for (char c = 'A'; c <= 'Z'; c++) {
            characters.add(String.valueOf(c));
        }
    }

    public void addSpecialCharacters() {
        for (char c : specialCharacters) {
            characters.add(String.valueOf(c));
        }
    }

    public void setMaxLength(int i) {
        maxLength = i;
    }

    public void setMinLength(int i) {
        minLength = i;
    }

    public int getPerSecond() {
        int i;
        try {
            i = (int) (getCounter() / calculateTimeDifference());
        } catch (Exception ex) {
            return 0;
        }
        return i;

    }

    public String calculateTimeElapsed() {
        long timeTaken = calculateTimeDifference();
        seconds = (int) timeTaken;
        if (seconds > 60) {
            minutes = (int) (seconds / 60);
            if (minutes * 60 > seconds) {
                minutes = minutes - 1;
            }

            if (minutes > 60) {
                hours = (int) minutes / 60;
                if (hours * 60 > minutes) {
                    hours = hours - 1;
                }
            }

            if (hours > 24) {
                days = (int) hours / 24;
                if (days * 24 > hours) {
                    days = days - 1;
                }
            }
            seconds -= (minutes * 60);
            minutes -= (hours * 60);
            hours -= (days * 24);
            days -= (hours * 24);
        }
        return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
    }

    private long calculateTimeDifference() {
        long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
        return timeTaken;
    }

    public boolean excludeChars(String s) {
        char[] arrayChars = s.toCharArray();
        for (int i = 0; i < arrayChars.length; i++) {
            characters.remove(arrayChars[i] + "");
        }
        if (characters.size() < maxLength) {
            return false;
        } else {
            return true;

        }
    }

    public int getMaxLength() {
        return maxLength;
    }

    public int getMinLength() {
        return minLength;
    }

    public void setIsDone(Boolean b) {
        done = b;
    }

    public boolean isDone() {
        return done;
    }
}

HashBruter.java:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;

public class HashBruter extends Bruter {
    /*
     * public static void main(String[] args) {
     *
     * final HashBruter hb = new HashBruter();
     *
     * hb.setMaxLength(5); hb.setMinLength(1);
     *
     * hb.addSpecialCharacters(); hb.addUpperCaseLetters();
     * hb.addLowerCaseLetters(); hb.addDigits();
     *
     * hb.setType("sha-512");
     *
     * hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
     *
     * Thread thread = new Thread(new Runnable() {
     *
     * @Override public void run() { hb.tryBruteForce(); } });
     *
     * thread.start();
     *
     * while (!hb.isFound()) { System.out.println("Hash: " +
     * hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
     * hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
     * hb.getCounter()); System.out.println("Estimated hashes left: " +
     * hb.getRemainder()); }
     *
     * System.out.println("Found " + hb.getType() + " hash collision: " +
     * hb.getGeneratedHash() + " password is: " + hb.getPassword());
     *
     * }
     */

    public String hash, generatedHash, password;
    public String type;

    public String getType() {
        return type;
    }

    public String getPassword() {
        return password;
    }

    public void setHash(String p) {
        hash = p;
    }

    public void setType(String digestType) {
        type = digestType;
    }

    public String getGeneratedHash() {
        return generatedHash;
    }

    public void tryBruteForce() {
        starttime = System.nanoTime();
        for (int size = minLength; size <= maxLength; size++) {
            if (found == true || done == true) {
                break;
            } else {
                while (paused) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
                generateAllPossibleCombinations("", size);
            }
        }
        done = true;
    }

    private void generateAllPossibleCombinations(String baseString, int length) {
        while (paused) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        if (found == false || done == false) {
            if (baseString.length() == length) {
                if(type.equalsIgnoreCase("crc32")) {
                generatedHash = generateCRC32(baseString);
                } else if(type.equalsIgnoreCase("adler32")) {
                generatedHash = generateAdler32(baseString);
                } else if(type.equalsIgnoreCase("crc16")) {
                    generatedHash=generateCRC16(baseString);
                } else if(type.equalsIgnoreCase("crc64")) {
                    generatedHash=generateCRC64(baseString.getBytes());
                }
                else {
                generatedHash = generateHash(baseString.toCharArray());
                }
                    password = baseString;
                if (hash.equals(generatedHash)) {
                    password = baseString;
                    found = true;
                    done = true;
                }
                count++;
            } else if (baseString.length() < length) {
                for (int n = 0; n < characters.size(); n++) {
                    generateAllPossibleCombinations(baseString + characters.get(n), length);
                }
            }
        }
    }

    private String generateHash(char[] passwordChar) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(type);
        } catch (NoSuchAlgorithmException e1) {
            JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
        }
        String passwordString = new String(passwordChar);
        byte[] passwordByte = passwordString.getBytes();
        md.update(passwordByte, 0, passwordByte.length);
        byte[] encodedPassword = md.digest();
        String encodedPasswordInString = toHexString(encodedPassword);
        return encodedPasswordInString;
    }

    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
            '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

    private String toHexString(byte[] block) {
        StringBuffer buf = new StringBuffer();
        int len = block.length;
        for (int i = 0; i < len; i++) {
            byte2hex(block[i], buf);
        }
        return buf.toString();
    }

    private String generateCRC32(String baseString) {

                //Convert string to bytes
                byte bytes[] = baseString.getBytes();

                Checksum checksum = new CRC32();

                /*
                 * To compute the CRC32 checksum for byte array, use
                 *
                 * void update(bytes[] b, int start, int length)
                 * method of CRC32 class.
                 */

                checksum.update(bytes,0,bytes.length);

                /*
                 * Get the generated checksum using
                 * getValue method of CRC32 class.
                 */
                return String.valueOf(checksum.getValue());
    }   
    private String generateAdler32(String baseString) {

                //Convert string to bytes
                byte bytes[] = baseString.getBytes();

                Checksum checksum = new Adler32();

                /*
                 * To compute the CRC32 checksum for byte array, use
                 *
                 * void update(bytes[] b, int start, int length)
                 * method of CRC32 class.
                 */

                checksum.update(bytes,0,bytes.length);

                /*
                 * Get the generated checksum using
                 * getValue method of CRC32 class.
                 */
                return String.valueOf(checksum.getValue());
    }
/*************************************************************************
 *  Compilation:  javac CRC16.java
 *  Execution:    java CRC16 s
 *  
 *  Reads in a string s as a command-line argument, and prints out
 *  its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
 *
 *  Reference:  http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
 *
 *  % java CRC16 123456789
 *  CRC16 = bb3d
 *
 * Uses irreducible polynomial:  1 + x^2 + x^15 + x^16
 *
 *
 *************************************************************************/
    private String generateCRC16(String baseString) {
                int[] table = {
            0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
            0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
            0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
            0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
            0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
            0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
            0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
            0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
            0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
            0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
            0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
            0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
            0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
            0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
            0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
            0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
            0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
            0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
            0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
            0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
            0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
            0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
            0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
            0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
            0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
            0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
            0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
            0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
            0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
            0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
            0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
            0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
        };


        byte[] bytes = baseString.getBytes();
        int crc = 0x0000;
        for (byte b : bytes) {
            crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
        }

        return Integer.toHexString(crc);
    }
    /*******************************************************************************
 * Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Marc R. Hoffmann - initial API and implementation
 *    
 *******************************************************************************/

/**
 * CRC64 checksum calculator based on the polynom specified in ISO 3309. The
 * implementation is based on the following publications:
 * 
 * <ul>
 * <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
 * <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
 * </ul>
 */
    private static final long POLY64REV = 0xd800000000000000L;

    private static final long[] LOOKUPTABLE;

    static {
        LOOKUPTABLE = new long[0x100];
        for (int i = 0; i < 0x100; i++) {
            long v = i;
            for (int j = 0; j < 8; j++) {
                if ((v & 1) == 1) {
                    v = (v >>> 1) ^ POLY64REV;
                } else {
                    v = (v >>> 1);
                }
            }
            LOOKUPTABLE[i] = v;
        }
    }

    /**
     * Calculates the CRC64 checksum for the given data array.
     * 
     * @param data
     *            data to calculate checksum for
     * @return checksum value
     */
    public static String generateCRC64(final byte[] data) {
        long sum = 0;
        for (int i = 0; i < data.length; i++) {
            final int lookupidx = ((int) sum ^ data[i]) & 0xff;
            sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
        }
        return String.valueOf(sum);
    }
}

you would use it like:

      final HashBruter hb = new HashBruter();

      hb.setMaxLength(5); hb.setMinLength(1);

     hb.addSpecialCharacters(); hb.addUpperCaseLetters();
     hb.addLowerCaseLetters(); hb.addDigits();

      hb.setType("sha-512");

                   hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");

      Thread thread = new Thread(new Runnable() {

      @Override public void run() { hb.tryBruteForce(); } });

      thread.start();

      while (!hb.isFound()) { System.out.println("Hash: " +
      hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
      hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
     hb.getCounter()); System.out.println("Estimated hashes left: " +
     hb.getRemainder()); }

     System.out.println("Found " + hb.getType() + " hash collision: " +
     hb.getGeneratedHash() + " password is: " + hb.getPassword());

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

Does "git fetch --tags" include "git fetch"?

Note: starting with git 1.9/2.0 (Q1 2014), git fetch --tags fetches tags in addition to what are fetched by the same command line without the option.

See commit c5a84e9 by Michael Haggerty (mhagger):

Previously, fetch's "--tags" option was considered equivalent to specifying the refspec

refs/tags/*:refs/tags/*

on the command line; in particular, it caused the remote.<name>.refspec configuration to be ignored.

But it is not very useful to fetch tags without also fetching other references, whereas it is quite useful to be able to fetch tags in addition to other references.
So change the semantics of this option to do the latter.

If a user wants to fetch only tags, then it is still possible to specifying an explicit refspec:

git fetch <remote> 'refs/tags/*:refs/tags/*'

Please note that the documentation prior to 1.8.0.3 was ambiguous about this aspect of "fetch --tags" behavior.
Commit f0cb2f1 (2012-12-14) fetch --tags made the documentation match the old behavior.
This commit changes the documentation to match the new behavior (see Documentation/fetch-options.txt).

Request that all tags be fetched from the remote in addition to whatever else is being fetched.


Since Git 2.5 (Q2 2015) git pull --tags is more robust:

See commit 19d122b by Paul Tan (pyokagan), 13 May 2015.
(Merged by Junio C Hamano -- gitster -- in commit cc77b99, 22 May 2015)

pull: remove --tags error in no merge candidates case

Since 441ed41 ("git pull --tags": error out with a better message., 2007-12-28, Git 1.5.4+), git pull --tags would print a different error message if git-fetch did not return any merge candidates:

It doesn't make sense to pull all tags; you probably meant:
       git fetch --tags

This is because at that time, git-fetch --tags would override any configured refspecs, and thus there would be no merge candidates. The error message was thus introduced to prevent confusion.

However, since c5a84e9 (fetch --tags: fetch tags in addition to other stuff, 2013-10-30, Git 1.9.0+), git fetch --tags would fetch tags in addition to any configured refspecs.
Hence, if any no merge candidates situation occurs, it is not because --tags was set. As such, this special error message is now irrelevant.

To prevent confusion, remove this error message.


With Git 2.11+ (Q4 2016) git fetch is quicker.

See commit 5827a03 (13 Oct 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 9fcd144, 26 Oct 2016)

fetch: use "quick" has_sha1_file for tag following

When fetching from a remote that has many tags that are irrelevant to branches we are following, we used to waste way too many cycles when checking if the object pointed at by a tag (that we are not going to fetch!) exists in our repository too carefully.

This patch teaches fetch to use HAS_SHA1_QUICK to sacrifice accuracy for speed, in cases where we might be racy with a simultaneous repack.

Here are results from the included perf script, which sets up a situation similar to the one described above:

Test            HEAD^               HEAD
----------------------------------------------------------
5550.4: fetch   11.21(10.42+0.78)   0.08(0.04+0.02) -99.3%

That applies only for a situation where:

  1. You have a lot of packs on the client side to make reprepare_packed_git() expensive (the most expensive part is finding duplicates in an unsorted list, which is currently quadratic).
  2. You need a large number of tag refs on the server side that are candidates for auto-following (i.e., that the client doesn't have). Each one triggers a re-read of the pack directory.
  3. Under normal circumstances, the client would auto-follow those tags and after one large fetch, (2) would no longer be true.
    But if those tags point to history which is disconnected from what the client otherwise fetches, then it will never auto-follow, and those candidates will impact it on every fetch.

Git 2.21 (Feb. 2019) seems to have introduced a regression when the config remote.origin.fetch is not the default one ('+refs/heads/*:refs/remotes/origin/*')

fatal: multiple updates for ref 'refs/tags/v1.0.0' not allowed

Git 2.24 (Q4 2019) adds another optimization.

See commit b7e2d8b (15 Sep 2019) by Masaya Suzuki (draftcode).
(Merged by Junio C Hamano -- gitster -- in commit 1d8b0df, 07 Oct 2019)

fetch: use oidset to keep the want OIDs for faster lookup

During git fetch, the client checks if the advertised tags' OIDs are already in the fetch request's want OID set.
This check is done in a linear scan.
For a repository that has a lot of refs, repeating this scan takes 15+ minutes.

In order to speed this up, create a oid_set for other refs' OIDs.

Show dialog from fragment?

Here is a full example of a yes/no DialogFragment:

The class:

public class SomeDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
            .setTitle("Title")
            .setMessage("Sure you wanna do this!")
            .setNegativeButton(android.R.string.no, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do nothing (will close dialog)
                }
            })
            .setPositiveButton(android.R.string.yes,  new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do something
                }
            })
            .create();
    }
}

To start dialog:

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // Create and show the dialog.
        SomeDialog newFragment = new SomeDialog ();
        newFragment.show(ft, "dialog");

You could also let the class implement onClickListener and use that instead of embedded listeners.

Callback to Activity

If you want to implement callback this is how it is done In your activity:

YourActivity extends Activity implements OnFragmentClickListener

and

@Override
public void onFragmentClick(int action, Object object) {
    switch(action) {
        case SOME_ACTION:
        //Do your action here
        break;
    }
}

The callback class:

public interface OnFragmentClickListener {
    public void onFragmentClick(int action, Object object);
}

Then to perform a callback from a fragment you need to make sure the listener is attached like this:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentClickListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement listeners!");
    }
}

And a callback is performed like this:

mListener.onFragmentClick(SOME_ACTION, null); // null or some important object as second parameter.

AngularJS Dropdown required validation

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

HTML:

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

        </form>

    Controller:

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

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

Here's a working plunker.

How to delete a file or folder?

import os

folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)

for f in fileList:
    filePath = folder + '/'+f

    if os.path.isfile(filePath):
        os.remove(filePath)

    elif os.path.isdir(filePath):
        newFileList = os.listdir(filePath)
        for f1 in newFileList:
            insideFilePath = filePath + '/' + f1

            if os.path.isfile(insideFilePath):
                os.remove(insideFilePath)

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Use String.Format:

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

In the format {0,-20} means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.

How to get only the date value from a Windows Forms DateTimePicker control?

You mean how to get date without the time component? Use DateTimePicker.Value.Date But you need to format the output to your needs.

Permissions error when connecting to EC2 via SSH on Mac OSx

None of the above helped me, but futzing with the user seemed like it had promise. For my config using 'ubuntu' was right.....

ssh -i [full path to keypair file] ubuntu@[EC2 instance hostname or IP address]

Link vs compile vs controller

  • compile: used when we need to modify directive template, like add new expression, append another directive inside this directive
  • controller: used when we need to share/reuse $scope data
  • link: it is a function which used when we need to attach event handler or to manipulate DOM.

PostgreSQL: insert from another table

Very late answer, but I think my answer is more straight forward for specific use cases where users want to simply insert (copy) data from table A into table B:

INSERT INTO table_b (col1, col2, col3, col4, col5, col6)
SELECT col1, 'str_val', int_val, col4, col5, col6
FROM table_a

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

What is (functional) reactive programming?

This article by Andre Staltz is the best and clearest explanation I've seen so far.

Some quotes from the article:

Reactive programming is programming with asynchronous data streams.

On top of that, you are given an amazing toolbox of functions to combine, create and filter any of those streams.

Here's an example of the fantastic diagrams that are a part of the article:

Click event stream diagram

How can I change image source on click with jQuery?

You need to use preventDefault() to make it so the link does not go through when u click on it:

fiddle: http://jsfiddle.net/maniator/Sevdm/

$(function() {
 $('.menulink').click(function(e){
     e.preventDefault();
   $("#bg").attr('src',"img/picture1.jpg");
 });
});

How to get resources directory path programmatically

I'm assuming the contents of src/main/resources/ is copied to WEB-INF/classes/ inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).

URL sqlScriptUrl = MyServletContextListener.class
                       .getClassLoader().getResource("sql/script.sql");

How do I format a number to a dollar amount in PHP

PHP also has money_format().

Here's an example:

echo money_format('$%i', 3.4); // echos '$3.40'

This function actually has tons of options, go to the documentation I linked to to see them.

Note: money_format is undefined in Windows.


UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Instead, look into NumberFormatter::formatCurrency.

    $number = "123.45";
    $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    return $formatter->formatCurrency($number, 'USD');

Returning pointer from a function

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

What is com.sun.proxy.$Proxy

What are they?

Nothing special. Just as same as common Java Class Instance.

But those class are Synthetic proxy classes created by java.lang.reflect.Proxy#newProxyInstance

What is there relationship to the JVM? Are they JVM implementation specific?

Introduced in 1.3

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

It is a part of Java. so each JVM should support it.

How are they created (Openjdk7 source)?

In short : they are created using JVM ASM tech ( defining javabyte code at runtime )

something using same tech:

What happens after calling java.lang.reflect.Proxy#newProxyInstance

  1. reading the source you can see newProxyInstance call getProxyClass0 to obtain a `Class

    `

  2. after lots of cache or sth it calls the magic ProxyGenerator.generateProxyClass which return a byte[]
  3. call ClassLoader define class to load the generated $Proxy Class (the classname you have seen)
  4. just instance it and ready for use

What happens in magic sun.misc.ProxyGenerator

  1. draw a class(bytecode) combining all methods in the interfaces into one
  2. each method is build with same bytecode like

    1. get calling Method meth info (stored while generating)
    2. pass info into invocation handler's invoke()
    3. get return value from invocation handler's invoke()
    4. just return it
  3. the class(bytecode) represent in form of byte[]

How to draw a class

Thinking your java codes are compiled into bytecodes, just do this at runtime

Talk is cheap show you the code

core method in sun/misc/ProxyGenerator.java

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<ProxyMethod>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

Full code about gen the proxy method

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "<init>", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }

How to run batch file from network share without "UNC path are not supported" message?

This is the RegKey I used:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001

Adding a line break in MySQL INSERT INTO text

In SQL or MySQL you can use the char or chr functions to enter in an ASCII 13 for carriage return line feed, the \n equivilent. But as @David M has stated, you are most likely looking to have the HTML show this break and a br is what will work.

Overlay normal curve to histogram in R

You just need to find the right multiplier, which can be easily calculated from the hist object.

myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]

plot(myhist)
lines(mydensity)

enter image description here

A more complete version, with a normal density and lines at each standard deviation away from the mean (including the mean):

myhist <- hist(mtcars$mpg)
multiplier <- myhist$counts / myhist$density
mydensity <- density(mtcars$mpg)
mydensity$y <- mydensity$y * multiplier[1]

plot(myhist)
lines(mydensity)

myx <- seq(min(mtcars$mpg), max(mtcars$mpg), length.out= 100)
mymean <- mean(mtcars$mpg)
mysd <- sd(mtcars$mpg)

normal <- dnorm(x = myx, mean = mymean, sd = mysd)
lines(myx, normal * multiplier[1], col = "blue", lwd = 2)

sd_x <- seq(mymean - 3 * mysd, mymean + 3 * mysd, by = mysd)
sd_y <- dnorm(x = sd_x, mean = mymean, sd = mysd) * multiplier[1]

segments(x0 = sd_x, y0= 0, x1 = sd_x, y1 = sd_y, col = "firebrick4", lwd = 2)

Getting value from table cell in JavaScript...not jQuery

I know this is like years old post but since there is no selected answer I hope this answer may give you what you are expecting...

if(document.getElementsByTagName){  
    var table = document.getElementById('table className');
    for (var i = 0, row; row = table.rows[i]; i++) {
    //rows would be accessed using the "row" variable assigned in the for loop
     for (var j = 0, col; col = row.cells[j]; j++) {
     //columns would be accessed using the "col" variable assigned in the for loop
        alert('col html>>'+col.innerHTML);    //Will give you the html content of the td
        alert('col>>'+col.innerText);    //Will give you the td value
        }
      }
    }
}

Calculate distance between 2 GPS coordinates

It depends on how accurate you need it to be, if you need pinpoint accuracy, is best to look at an algorithm with uses an ellipsoid, rather than a sphere, such as Vincenty's algorithm, which is accurate to the mm. http://en.wikipedia.org/wiki/Vincenty%27s_algorithm

Regex to remove all special characters from string?

If you don't want to use Regex then another option is to use

char.IsLetterOrDigit

You can use this to loop through each char of the string and only return if true.

Understanding the Rails Authenticity Token

What is CSRF?

The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?

It's a way that an attacker can potentially hijack sessions without even knowing session tokens.

Scenario:

  • Visit your bank's site, log in.
  • Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).
  • Attacker's page includes form with same fields as the bank's "Transfer Funds" form.
  • Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.
  • Attacker's page includes Javascript that submits form to your bank.
  • When form gets submitted, browser includes your cookies for the bank site, including the session token.
  • Bank transfers money to attacker's account.
  • The form can be in an iframe that is invisible, so you never know the attack occurred.
  • This is called Cross-Site Request Forgery (CSRF).

CSRF solution:

  • Server can mark forms that came from the server itself
  • Every form must contain an additional authentication token as a hidden field.
  • Token must be unpredictable (attacker can't guess it).
  • Server provides valid token in forms in its pages.
  • Server checks token when form posted, rejects forms without proper token.
  • Example token: session identifier encrypted with server secret key.
  • Rails automatically generates such tokens: see the authenticity_token input field in every form.

Find an element in DOM based on an attribute value

Modern browsers support native querySelectorAll so you can do:

document.querySelectorAll('[data-foo="value"]');

https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Details about browser compatibility:

You can use jQuery to support obsolete browsers (IE9 and older):

$('[data-foo="value"]');

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();