Programs & Examples On #Get method

An HTTP Protocol request method.

How to get parameters from the URL with JSP

example you wanted to delete the subject record with its subject_id

@RequestMapping(value="subject_setup/delete/{subjectid}",method = RequestMethod.GET)
public ModelAndView delete(@PathVariable int subjectid) {
    subjectsDao.delete(subjectid);
    return new ModelAndView("redirect:/subject_setup");
}

and the parameter will be used for input on your query

public int delete(int subjectid) {
    String sql = "update tbl_subject set isdeleted= '1' where id = "+subjectid+"";
    return template.update(sql);
}

How to search by key=>value in a multidimensional array in PHP

function in_multi_array($needle, $key, $haystack) 
{
    $in_multi_array = false;
    if (in_array($needle, $haystack))
    {
        $in_multi_array = true; 
    }else 
    {
       foreach( $haystack as $key1 => $val )
       {
           if(is_array($val)) 
           {
               if($this->in_multi_array($needle, $key, $val)) 
               {
                   $in_multi_array = true;
                   break;
               }
           }
        }
    }

    return $in_multi_array;
} 

What is this weird colon-member (" : ") syntax in the constructor?

there is another 'benefit'

if the member variable type does not support null initialization or if its a reference (which cannot be null initialized) then you have no choice but to supply an initialization list

Adding an onclick event to a table row

While most answers are a copy of SolutionYogi's answer, they all miss an important check to see if 'cell' is not null which will return an error if clicking on the headers. So, here is the answer with the check included:

function addRowHandlers() {
  var table = document.getElementById("tableId");
  var rows = table.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByTagName("td")[0];
        // check if not null
        if(!cell) return; // no errors! 
        var id = cell.innerHTML;
        alert("id:" + id);
      };
    };
    currentRow.onclick = createClickHandler(currentRow);
  }
}

Why use the INCLUDE clause when creating an index?

This discussion is missing out on the important point: The question is not if the "non-key-columns" are better to include as index-columns or as included-columns.

The question is how expensive it is to use the include-mechanism to include columns that are not really needed in index? (typically not part of where-clauses, but often included in selects). So your dilemma is always:

  1. Use index on id1, id2 ... idN alone or
  2. Use index on id1, id2 ... idN plus include col1, col2 ... colN

Where: id1, id2 ... idN are columns often used in restrictions and col1, col2 ... colN are columns often selected, but typically not used in restrictions

(The option to include all of these columns as part of the index-key is just always silly (unless they are also used in restrictions) - cause it would always be more expensive to maintain since the index must be updated and sorted even when the "keys" have not changed).

So use option 1 or 2?

Answer: If your table is rarely updated - mostly inserted into/deleted from - then it is relatively inexpensive to use the include-mechanism to include some "hot columns" (that are often used in selects - but not often used on restrictions) since inserts/deletes require the index to be updated/sorted anyway and thus little extra overhead is associated with storing off a few extra columns while already updating the index. The overhead is the extra memory and CPU used to store redundant info on the index.

If the columns you consider to add as included-columns are often updated (without the index-key-columns being updated) - or - if it is so many of them that the index becomes close to a copy of your table - use option 1 I'd suggest! Also if adding certain include-column(s) turns out to make no performance-difference - you might want to skip the idea of adding them:) Verify that they are useful!

The average number of rows per same values in keys (id1, id2 ... idN) can be of some importance as well.

Notice that if a column - that is added as an included-column of index - is used in the restriction: As long as the index as such can be used (based on restriction against index-key-columns) - then SQL Server is matching the column-restriction against the index (leaf-node-values) instead of going the expensive way around the table itself.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

I added a check for null values in the JSON to the other answer

I had same problem so I wrote this my self. This solution is differentiated from other answers because it can deserialize in to multiple levels.

Just send json string in to deserializeToDictionary function it will return non strongly-typed Dictionary<string, object> object.

private Dictionary<string, object> deserializeToDictionary(string jo)
{
    var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
    var values2 = new Dictionary<string, object>();
    foreach (KeyValuePair<string, object> d in values)
    {
        if (d.Value != null && d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
        {
            values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
        }
        else
        {
            values2.Add(d.Key, d.Value);
        }
    }
    return values2;
}

Ex: This will return Dictionary<string, object> object of a Facebook JSON response.

private void button1_Click(object sender, EventArgs e)
{
    string responsestring = "{\"id\":\"721055828\",\"name\":\"Dasun Sameera
        Weerasinghe\",\"first_name\":\"Dasun\",\"middle_name\":\"Sameera\",\"last_name\":\"Weerasinghe\",\"username\":\"dasun\",\"gender\":\"male\",\"locale\":\"en_US\",
        hometown: {id: \"108388329191258\", name: \"Moratuwa, Sri Lanka\",}}";
    Dictionary<string, object> values = deserializeToDictionary(responsestring);
}

Note: hometown further deserialize into a Dictionary<string, object> object.

Show a child form in the centre of Parent form in C#

The setting of parent does not work for me unless I use form.ShowDialog();.

When using form.Show(); or form.Show(this); nothing worked until I used, this.CenterToParent();. I just put that in the Load method of the form. All is good.

Start position to the center of parent was set and does work when using the blocking showdialog.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

Resume of the question:
Have column width adapt to the content (with different method across the column),
but then allow the user to set the column width...

Developing from Miroslav Zadravec's answer, for me what worked was immediately using the auto computed column.Width to set... column.Width!

foreach (DataGridViewColumn column in dataGridView.Columns)
{
    if (/*It's not your special column*/)
    {
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        column.Width = column.Width; //This is important, otherwise the following line will nullify your previous command
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
    }
}

//Now do the same using Fill instead of AllCells for your special column

This is tested to work when the DataGridView is already created, using a trick like this.

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example:

>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'

Fitting a density curve to a histogram in R

If I understand your question correctly, then you probably want a density estimate along with the histogram:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

Edit a long while later:

Here is a slightly more dressed-up version:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

along with the graph it produces:

enter image description here

How can I define colors as variables in CSS?

If you write the css file as an xsl template, you could read color values from a simple xml file. Then create the css with an xslt processor.

colors.xml:

<?xml version="1.0"?>
<colors>
    <background>#ccc</background>
</colors>

styles.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" version="1.0" encoding="iso-8859-1"/>
    <xsl:template match="/">body {
    background-color: <xsl:value-of select="/colors/background" />;
}
</xsl:template>
</xsl:stylesheet>

Command to render css: xsltproc -o styles.css styles.xsl colors.xml

styles.css:

body {
    background-color: #ccc;
}

How to determine a user's IP address in node

If you get multiple IPs , this works for me:

_x000D_
_x000D_
var ipaddress = (req.headers['x-forwarded-for'] || _x000D_
req.connection.remoteAddress || _x000D_
req.socket.remoteAddress || _x000D_
req.connection.socket.remoteAddress).split(",")[0];
_x000D_
_x000D_
_x000D_

Remove large .pack file created by git

Run the following command, replacing PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA with the path to the file you want to remove, not just its filename. These arguments will:

  1. Force Git to process, but not check out, the entire history of every branch and tag
  2. Remove the specified file, as well as any empty commits generated as a result
  3. Overwrite your existing tags
git filter-branch --force --index-filter "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" --prune-empty --tag-name-filter cat -- --all

This will forcefully remove all references to the files from the active history of the repo.

Next step, to perform a GC cycle to force all references to the file to be expired and purged from the pack file. Nothing needs to be replaced in these commands.

git update-ref -d refs/original/refs/remotes/origin/master
git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --aggressive --prune=now

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Following the instructions here http://help.loftware.com/pages/viewpage.action?pageId=27099554 I had to install the Microsoft Access Database Engine 2010 Redistributable before I had the Excel driver installed to use the DSN-less connection I wanted to use from perl.

Node.js - Find home directory in platform agnostic way

getUserRootFolder() {
  return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

how to create dynamic two dimensional array in java?

simple you want to inialize a 2d array and assign a size of array then a example is

   public static void main(String args[])
   { 
    char arr[][];   //arr is 2d array name
    arr = new char[3][3]; 
    }


   //this is a way to inialize a 2d array in java....  

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

CSS: How to align vertically a "label" and "input" inside a "div"?

_x000D_
_x000D_
div {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    height: 50px;_x000D_
    border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <label for='name'>Name:</label>_x000D_
    <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

Redirect to Action in another controller

Try switching them:

return RedirectToAction("Account", "Login");

I tried it and it worked.

How to select the first element in the dropdown using jquery?

Your selector is wrong, you were probably looking for

$('select option:nth-child(1)')

This will work also:

$('select option:first-child')

JFrame background image

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

Take a look at Performing Custom Painting and 2D Graphics for more details

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

This answer ended up working for me: https://stackoverflow.com/a/15559278/53001

Backup to a file, pull the backup, and then convert it to a tarball and extract it.

adb backup  -f myAndroidBackup.ab  com.corp.appName

dd if=myAndroidBackup.ab bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" | tar -xvf - 

Calculate percentage saved between two numbers?

((list price - actual price) / (list price)) * 100%

For example:

((25 - 10) / 25) * 100% = 60%

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

For Linux just make a symlink, like this:

ln -s /android/android-studio/plugins/android/lib/templates /android/sdk/tools/templates

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

How to get a list of properties with a given attribute?

There's always LINQ:

t.GetProperties().Where(
    p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)

Route [login] not defined

Replace in your views (blade files) all

{{route('/')}} ----- by ----> {{url('/')}}

Reading e-mails from Outlook with Python through MAPI

Sorry for my bad English. Checking Mails using Python with MAPI is easier,

outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetFirst()

Here we can get the most first mail into the Mail box, or into any sub folder. Actually, we need to check the Mailbox number & orientation. With the help of this analysis we can check each mailbox & its sub mailbox folders.

Similarly please find the below code, where we can see, the last/ earlier mails. How we need to check.

`outlook =win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders[5]
Subfldr = folder.Folders[5]
messages_REACH = Subfldr.Items
message = messages_REACH.GetLast()`

With this we can get most recent email into the mailbox. According to the above mentioned code, we can check our all mail boxes, & its sub folders.

MySQL Multiple Joins in one query?

Just add another join:

SELECT dashboard_data.headline,
       dashboard_data.message,
       dashboard_messages.image_id,
       images.filename 
FROM dashboard_data 
    INNER JOIN dashboard_messages
            ON dashboard_message_id = dashboard_messages.id 
    INNER JOIN images
            ON dashboard_messages.image_id = images.image_id

find . -type f -exec chmod 644 {} ;

I need this so often that I created a function in my ~/.bashrc file:

chmodf() {
        find $2 -type f -exec chmod $1 {} \;
}
chmodd() {
        find $2 -type d -exec chmod $1 {} \;
}

Now I can use these shortcuts:

chmodd 0775 .
chmodf 0664 .

How to configure Glassfish Server in Eclipse manually

For Eclipse Luna

Go to Help>Eclipse MarketPlace> Search for GlassFish Tools and install it.

Restart Eclipse.

Now go to servers>new>server and you will find Glassfish server.

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

jQuery - Follow the cursor with a DIV

You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

$(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

That div must be off the float, so position: absolute should be set.

Regex for checking if a string is strictly alphanumeric

In order to be unicode compatible:

^[\pL\pN]+$

where

\pL stands for any letter
\pN stands for any number

Java to Jackson JSON serialization: Money fields

Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:

SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);

In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).

How to play a local video with Swift?

gbk's solution in swift 3

PlayerView

import AVFoundation
import UIKit

class PlayerView: UIView {

override class var layerClass: AnyClass {
    return AVPlayerLayer.self
}

var player:AVPlayer? {
    set {
        if let layer = layer as? AVPlayerLayer {
            layer.player = player
        }
    }
    get {
        if let layer = layer as? AVPlayerLayer {
            return layer.player
        } else {
            return nil
        }
    }
}
}

VideoPlayer

import AVFoundation
import Foundation

protocol VideoPlayerDelegate {
    func downloadedProgress(progress:Double)
    func readyToPlay()
    func didUpdateProgress(progress:Double)
    func didFinishPlayItem()
    func didFailPlayToEnd()
}

let videoContext:UnsafeMutableRawPointer? = nil

class VideoPlayer : NSObject {



private var assetPlayer:AVPlayer?
private var playerItem:AVPlayerItem?
private var urlAsset:AVURLAsset?
private var videoOutput:AVPlayerItemVideoOutput?

private var assetDuration:Double = 0
private var playerView:PlayerView?

private var autoRepeatPlay:Bool = true
private var autoPlay:Bool = true

var delegate:VideoPlayerDelegate?

var playerRate:Float = 1 {
    didSet {
        if let player = assetPlayer {
            player.rate = playerRate > 0 ? playerRate : 0.0
        }
    }
}

var volume:Float = 1.0 {
    didSet {
        if let player = assetPlayer {
            player.volume = volume > 0 ? volume : 0.0
        }
    }
}

// MARK: - Init

convenience init(urlAsset: URL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
    self.init()

    playerView = view
    autoPlay = startAutoPlay
    autoRepeatPlay = repeatAfterEnd

    if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    }
    initialSetupWithURL(url: urlAsset)
    prepareToPlay()
}

override init() {
    super.init()
}

// MARK: - Public

func isPlaying() -> Bool {
    if let player = assetPlayer {
        return player.rate > 0
    } else {
        return false
    }
}

func seekToPosition(seconds:Float64) {
    if let player = assetPlayer {
        pause()
        if let timeScale = player.currentItem?.asset.duration.timescale {
            player.seek(to: CMTimeMakeWithSeconds(seconds, timeScale), completionHandler: { (complete) in
                self.play()
            })
        }
    }
}

func pause() {
    if let player = assetPlayer {
        player.pause()
    }
}

func play() {
    if let player = assetPlayer {
        if (player.currentItem?.status == .readyToPlay) {
            player.play()
            player.rate = playerRate
        }
    }
}

func cleanUp() {
    if let item = playerItem {
        item.removeObserver(self, forKeyPath: "status")
        item.removeObserver(self, forKeyPath: "loadedTimeRanges")
    }
    NotificationCenter.default.removeObserver(self)
    assetPlayer = nil
    playerItem = nil
    urlAsset = nil
}

// MARK: - Private

private func prepareToPlay() {
    let keys = ["tracks"]
    if let asset = urlAsset {
        asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
            DispatchQueue.main.async {
                self.startLoading()
            }
        })
    }
}

private func startLoading(){
    var error:NSError?
    guard let asset = urlAsset else {return}
    let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)

    if status == AVKeyValueStatus.loaded {
        assetDuration = CMTimeGetSeconds(asset.duration)

        let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
        videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
        playerItem = AVPlayerItem(asset: asset)

        if let item = playerItem {
            item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
            item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)

            NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)

            if let output = videoOutput {
                item.add(output)

                item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed
                assetPlayer = AVPlayer(playerItem: item)

                if let player = assetPlayer {
                    player.rate = playerRate
                }

                addPeriodicalObserver()
                if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
                    layer.player = assetPlayer
                    print("player created")
                }
            }
        }
    }
}

private func addPeriodicalObserver() {
    let timeInterval = CMTimeMake(1, 1)

    if let player = assetPlayer {
        player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
            self.playerDidChangeTime(time: time)
        })
    }
}

private func playerDidChangeTime(time:CMTime) {
    if let player = assetPlayer {
        let timeNow = CMTimeGetSeconds(player.currentTime())
        let progress = timeNow / assetDuration

        delegate?.didUpdateProgress(progress: progress)
    }
}

@objc private func playerItemDidReachEnd() {
    delegate?.didFinishPlayItem()

    if let player = assetPlayer {
        player.seek(to: kCMTimeZero)
        if autoRepeatPlay == true {
            play()
        }
    }
}

@objc private func didFailedToPlayToEnd() {
    delegate?.didFailPlayToEnd()
}

private func playerDidChangeStatus(status:AVPlayerStatus) {
    if status == .failed {
        print("Failed to load video")
    } else if status == .readyToPlay, let player = assetPlayer {
        volume = player.volume
        delegate?.readyToPlay()

        if autoPlay == true && player.rate == 0.0 {
            play()
        }
    }
}

private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
    var maximum:TimeInterval = 0
    for value in ranges {
        let range:CMTimeRange = value.timeRangeValue
        let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
        if currentLoadedTimeRange > maximum {
            maximum = currentLoadedTimeRange
        }
    }
    let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration

    delegate?.downloadedProgress(progress: progress)
}

deinit {
    cleanUp()
}

private func initialSetupWithURL(url: URL) {
    let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
    urlAsset = AVURLAsset(url: url, options: options)
}

// MARK: - Observations

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if context == videoContext {
        if let key = keyPath {
            if key == "status", let player = assetPlayer {
                playerDidChangeStatus(status: player.status)
            } else if key == "loadedTimeRanges", let item = playerItem {
                moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
            }
        }
    }
}
}

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

Use jQuery to navigate away from page

window.location = myUrl;

Anyway, this is not jQuery: it's plain javascript

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

Python match a string with regex

As everyone else has mentioned it is better to use the "in" operator, it can also act on lists:

line = "This,is,a,sample,string"
lst = ['This', 'sample']
for i in lst:
     i in line

>> True
>> True

How do I scroll the UIScrollView when the keyboard appears?

I just implemented this with Swift 2.0 for iOS9 on Xcode 7 (beta 6), works fine here.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    registerKeyboardNotifications()
}

func registerKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    let userInfo: NSDictionary = notification.userInfo!
    let keyboardSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size
    let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets

    var viewRect = view.frame
    viewRect.size.height -= keyboardSize.height
    if CGRectContainsPoint(viewRect, textField.frame.origin) {
        let scrollPoint = CGPointMake(0, textField.frame.origin.y - keyboardSize.height)
        scrollView.setContentOffset(scrollPoint, animated: true)
    }
}

func keyboardWillHide(notification: NSNotification) {
    scrollView.contentInset = UIEdgeInsetsZero
    scrollView.scrollIndicatorInsets = UIEdgeInsetsZero
}

Edited for Swift 3

Seems like you only need to set the contentInset and scrollIndicatorInset with Swift 3, the scrolling/contentOffset is done automatically..

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    registerKeyboardNotifications()
}

func registerKeyboardNotifications() {
    NotificationCenter.default.addObserver(self,
                                         selector: #selector(keyboardWillShow(notification:)),
                                         name: NSNotification.Name.UIKeyboardWillShow,
                                         object: nil)
    NotificationCenter.default.addObserver(self,
                                         selector: #selector(keyboardWillHide(notification:)),
                                         name: NSNotification.Name.UIKeyboardWillHide,
                                         object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    let userInfo: NSDictionary = notification.userInfo! as NSDictionary
    let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue
    let keyboardSize = keyboardInfo.cgRectValue.size
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}

func keyboardWillHide(notification: NSNotification) {
    scrollView.contentInset = .zero
    scrollView.scrollIndicatorInsets = .zero
}

Is this a good way to clone an object in ES6?

You can do it like this as well,

let copiedData = JSON.parse(JSON.stringify(data));

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

Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.

What is the Windows version of cron?

Is there also a way to invoke this feature (which based on answers is called the Task Scheduler) programatically [...]?

Task scheduler API on MSDN.

How to convert timestamp to datetime in MySQL?

DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`

This is the ultimate solution if the given date is in encoded format like 1300464000

how to run two commands in sudo?

An alternative using eval so avoiding use of a subshell:

sudo -s eval 'whoami; whoami'

Note: The other answers using sudo -s fail because the quotes are being passed on to bash and run as a single command so need to strip quotes with eval. eval is better explained is this SO answer

Quoting within the commands is easier too:

$ sudo -s eval 'whoami; whoami; echo "end;"'
root
root
end;

And if the commands need to stop running if one fails use double-ampersands instead of semi-colons:

$ sudo -s eval 'whoami && whoamit && echo "end;"'
root
/bin/bash: whoamit: command not found

How do you append to a file?

Python has many variations off of the main three modes, these three modes are:

'w'   write text
'r'   read text
'a'   append text

So to append to a file it's as easy as:

f = open('filename.txt', 'a') 
f.write('whatever you want to write here (in append mode) here.')

Then there are the modes that just make your code fewer lines:

'r+'  read + write text
'w+'  read + write text
'a+'  append + read text

Finally, there are the modes of reading/writing in binary format:

'rb'  read binary
'wb'  write binary
'ab'  append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

How can I connect to MySQL in Python 3 on Windows?

Summary

Mysqlclient is the best alternative(IMHO) because it works flawlessly with Python 3+, follows expected conventions (unlike mysql connector), uses the object name mysqldb which enables convenient porting of existing software and is used by Django for Python 3 builds

Is there a repository available where the binaries exist for mysqldb?

Yes. mysqlclient allows you to use mysqldb functions. Though, remember this is not a direct port by mysqldb, but a build by mysqlclient

How can I connect to MySQL in Python 3 on Windows?

pip install mysqlclient

Example

#!/Python36/python
#Please change above path to suit your platform.  Am running it on Windows
import MySQLdb
db = MySQLdb.connect(user="my-username",passwd="my-password",host="localhost",db="my-databasename")
cursor = db.cursor()
cursor.execute("SELECT * from my-table-name")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

I can't find mysqldb for Python 3.

mysqldb has not been ported yet

method in class cannot be applied to given types

The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.

To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.

python-dev installation error: ImportError: No module named apt_pkg

Just in case it helps another, I finally solved this problem, that was apparently caused by python version conflicts, by redirecting the link python3, then redirecting it to the right python version:

sudo rm /usr/bin/python3
sudo ln -s /usr/bin/python3.4

You may need to enter the correct python version, found with:

python3 -V

Escaping a forward slash in a regular expression

For java, you don't need to.

eg: "^(.*)/\\*LOG:(\\d+)\\*/(.*)$" ==> ^(.*)/\*LOG:(\d+)\*/(.*)$

If you put \ in front of /. IDE will tell you "Redundant Character Escape "\/" in ReGex"

How do I sort a dictionary by value?

Starting from Python 3.6, dict objects are now ordered by insertion order. It's officially in the specs of Python 3.7.

>>> words = {"python": 2, "blah": 4, "alice": 3}
>>> dict(sorted(words.items(), key=lambda x: x[1]))
{'python': 2, 'alice': 3, 'blah': 4}

Before that, you had to use OrderedDict.

Python 3.7 documentation says:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.

Methods vs Constructors in Java

Here are some main key differences between constructor and method in java

  1. Constructors are called at the time of object creation automatically. But methods are not called during the time of object creation automatically.
  2. Constructor name must be same as the class name. Method has no such protocol.
  3. The constructors can’t have any return type. Not even void. But methods can have a return type and also void. Click to know details - Difference between constructor and method in Java

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

Macro to Auto Fill Down to last adjacent cell

Untested....but should work.

Dim lastrow as long

lastrow = range("D65000").end(xlup).Row

ActiveCell.FormulaR1C1 = _
        "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
    Selection.AutoFill Destination:=Range("E2:E" & lastrow)
    'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
    Range("E2:E1344").Select

Only exception being are you sure your Autofill code is perfect...

How to check for a Null value in VB.NET

The equivalent of null in VB is Nothing so your check wants to be:

If editTransactionRow.pay_id IsNot Nothing Then
    stTransactionPaymentID = editTransactionRow.pay_id
End If

Or possibly, if you are actually wanting to check for a SQL null value:

If editTransactionRow.pay_id <> DbNull.Value Then
    ...
End If

PHP equivalent of .NET/Java's toString()

If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

How to delete/remove nodes on Firebase

In case you are using axios and trying via a service call.

URL: https://react-16-demo.firebaseio.com/
Schema Name: todos
Key: -Lhu8a0uoSRixdmECYPE

axios.delete(`https://react-16-demo.firebaseio.com/todos/-Lhu8a0uoSRixdmECYPE.json`). then();

can help.

How to use PHP to connect to sql server

 $server_name = "your server name";
 $database_name = "your database name";
 try
  {
   $conn = new PDO("sqlsrv:Server=$server_name;Database=$database_name;ConnectionPooling=0", "user_name", "password");
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e)
{

    $e->getMessage();

}

.Contains() on a list of custom class objects

You need to create a object from your list like:

List<CartProduct> lst = new List<CartProduct>();

CartProduct obj = lst.Find(x => (x.Name == "product name"));

That object get the looked value searching by their properties: x.name

Then you can use List methods like Contains or Remove

if (lst.Contains(obj))
{
   lst.Remove(obj);
}

Replacing all non-alphanumeric characters with empty strings

Java's regular expressions don't require you to put a forward-slash (/) or any other delimiter around the regex, as opposed to other languages like Perl, for example.

How to list files and folder in a dir (PHP)

You can use:

 foreach (new DirectoryIterator("./system/information/") as $fn) {
     print $fn->getFilename();
 }

You'll have to use it twice for each subdir, Players and User.

jQuery or JavaScript auto click

$(document).ready(function(){
   $('.lbOn').click();
});

Suppose this would work too.

Convert JsonNode into POJO

In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);

How to limit the maximum value of a numeric field in a Django model?

There are two ways to do this. One is to use form validation to never let any number over 50 be entered by a user. Form validation docs.

If there is no user involved in the process, or you're not using a form to enter data, then you'll have to override the model's save method to throw an exception or limit the data going into the field.

Pycharm: run only part of my Python file

Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e

For this to work properly, you'll have to run everything this way.

enter image description here

Posting form to different MVC post action depending on the clicked submit button

BEST ANSWER 1:

ActionNameSelectorAttribute mentioned in

  1. How do you handle multiple submit buttons in ASP.NET MVC Framework?

  2. ASP.Net MVC 4 Form with 2 submit buttons/actions

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

ANSWER 2

Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor

Second Approach

Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

Third Approach: Client Script

<button name="ClientCancel" type="button" 
    onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" 
style="display:none;"></a>

Add one year in current date PYTHON

Here's one more answer that I've found to be pretty concise and doesn't use external packages:

import datetime as dt
import calendar

# Today, in `dt.date` type
day = dt.datetime.now().date()

one_year_delta = dt.timedelta(days=366 if ((day.month >= 3 and calendar.isleap(day.year+1)) or
                                            (day.month < 3 and calendar.isleap(day.year))) else 365)

# Add one year to the current date
print(day + one_year_delta)

Resize a picture to fit a JLabel

Assign your image to a string. Eg image Now set icon to a fixed size label.

image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));

log4j:WARN No appenders could be found for logger (running jar file, not web app)

You will find de log4j.properties in solr/examples/resources.

If you don't find the file, i put it here:

#  Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n

#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9

#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n

log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN

# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF

Regards

How to access site through IP address when website is on a shared host?

serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.

As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.

67.225.235.59 somerandomservice.com www.somerandomservice.com

C# Collection was modified; enumeration operation may not execute

I suspect the error is caused by this:

foreach (KeyValuePair<int, int> kvp in rankings)

rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.

But you're modifying the dictionary inside your loop:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

which isn't allowed...so you get the exception.

You could simply do this

foreach (KeyValuePair<int, int> kvp in rankings.ToArray())

"Could not find Developer Disk Image"

Xcode 7.0.1 and iOS 9.1 are incompatible. You will need to update your version of Xcode via the Mac app store.

If your iOS version is lower then the Xcode version on the other hand, you can change the deployment target for a lower version of iOS by going to the General Settings and under Deployment set your Deployment Target:

enter image description here

Note:

Xcode 7.1 does not include iOS 9.2 beta SDK. Upgraded to Xcode to 7.2 beta by downloading it from the Xcode website.

Eclipse hangs on loading workbench

After some investigation about file dates I solved the same issue (which is a randomly recurrent trouble on my Kepler) by simply deleting the following file in my local workspace: .metadata.plugins\org.eclipse.jdt.core\variablesAndContainers.dat

with negligible impact on the workspace restoring.

I hope it can help someone else...

How can I uninstall npm modules in Node.js?

I found this out the hard way, even if it is seemingly obvious.

I initially tried to loop through the node_modules directory running npm uninstall module-name with a simple for loop in a script. I found out it will not work if you call the full path, e.g.,

npm uninstall module-name

was working, but

npm uninstall /full/path/to/node_modules/module-name 

was not working.

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

How to make the overflow CSS property work with hidden as value

Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden as well, e.g.:

<div style="overflow: hidden">
  <div style="overflow: hidden">some text that should not overflow<div>
</div>

Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)

Upload video files via PHP and save them in appropriate folder and have a database entry

"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"

^--- As per OP's request. ---^

Image and video uploading code (tested with PHP Version 5.4.17)

HTML form

<!DOCTYPE html>

<head>
<title></title>
</head>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

PHP handler (upload_file.php)

Change upload folder to preferred name. Presently saves to upload/

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))

&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Linux delete file with size 0

For a non-recursive delete (using du and awk):

rm `du * | awk '$1 == "0" {print $2}'`

Changing the color of an hr element

Some browsers use the color attribute and some use the background-color attribute. To be safe:

hr{
    color: #color;
    background-color: #color;
}

Use index in pandas to plot data

Try this,

monthly_mean.plot(y='A', use_index=True)

How are "mvn clean package" and "mvn clean install" different?

Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects.

For understanding maven build lifecycle please go through the following link https://ayolajayamaha.blogspot.in/2014/05/difference-between-mvn-clean-install.html

Why I can't change directories using "cd"?

To make a bash script that will cd to a select directory :

Create the script file

#!/bin/sh
# file : /scripts/cdjava
#
cd /home/askgelal/projects/java

Then create an alias in your startup file.

#!/bin/sh
# file /scripts/mastercode.sh
#
alias cdjava='. /scripts/cdjava'

  • I created a startup file where I dump all my aliases and custom functions.
  • Then I source this file into my .bashrc to have it set on each boot.

For example, create a master aliases/functions file: /scripts/mastercode.sh
(Put the alias in this file.)

Then at the end of your .bashrc file:

source /scripts/mastercode.sh



Now its easy to cd to your java directory, just type cdjava and you are there.

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How to add onload event to a div element

Since the onload event is only supported on a few elements, you have to use an alternate method.

You can use a MutationObserver for this:

_x000D_
_x000D_
const trackElement = element => {_x000D_
  let present = false;_x000D_
  const checkIfPresent = () => {_x000D_
    if (document.body.contains(element)) {_x000D_
      if (!present) {_x000D_
        console.log('in DOM:', element);_x000D_
      }_x000D_
      present = true;_x000D_
    } else if (present) {_x000D_
      present = false;_x000D_
      console.log('Not in DOM');_x000D_
    }_x000D_
  };_x000D_
_x000D_
  const observer = new MutationObserver(checkIfPresent);_x000D_
  observer.observe(document.body, { childList: true });_x000D_
  checkIfPresent();_x000D_
_x000D_
  return observer;_x000D_
};_x000D_
_x000D_
const element = document.querySelector('#element');_x000D_
const add = () => document.body.appendChild(element);_x000D_
const remove = () => element.remove();_x000D_
_x000D_
trackElement(element);
_x000D_
<button onclick="add()">Add</button>_x000D_
<button onclick="remove()">Remove</button>_x000D_
_x000D_
<div id="element">Element</div>
_x000D_
_x000D_
_x000D_

Ship an application with a database

Currently there is no way to precreate an SQLite database to ship with your apk. The best you can do is save the appropriate SQL as a resource and run them from your application. Yes, this leads to duplication of data (same information exists as a resrouce and as a database) but there is no other way right now. The only mitigating factor is the apk file is compressed. My experience is 908KB compresses to less than 268KB.

The thread below has the best discussion/solution I have found with good sample code.

http://groups.google.com/group/android-developers/msg/9f455ae93a1cf152

I stored my CREATE statement as a string resource to be read with Context.getString() and ran it with SQLiteDatabse.execSQL().

I stored the data for my inserts in res/raw/inserts.sql (I created the sql file, 7000+ lines). Using the technique from the link above I entered a loop, read the file line by line and concactenated the data onto "INSERT INTO tbl VALUE " and did another SQLiteDatabase.execSQL(). No sense in saving 7000 "INSERT INTO tbl VALUE "s when they can just be concactenated on.

It takes about twenty seconds on the emulator, I do not know how long this would take on a real phone, but it only happens once, when the user first starts the application.

How do I detect unsigned integer multiply overflow?

Clang now supports dynamic overflow checks for both signed and unsigned integers. See the -fsanitize=integer switch. For now, it is the only C++ compiler with fully supported dynamic overflow checking for debug purposes.

Insert image after each list item

My solution to do this:

li span.show::after{
  content: url("/sites/default/files/new5.gif");
  padding-left: 5px;
}

Git workflow and rebase vs merge questions

With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

You can just post the file name to delete to delete.php on the server, which can easily unlink() the file.

Calling an API from SQL Server stored procedure

I worked so much, I hope my effort might help you out.

Just paste this into your SSMS and press F5:

Declare @Object as Int;
DECLARE @hr  int
Declare @json as table(Json_Table nvarchar(max))

Exec @hr=sp_OACreate 'MSXML2.ServerXMLHTTP.6.0', @Object OUT;
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://overpass-api.de/api/interpreter?data=[out:json];area[name=%22Auckland%22]-%3E.a;(node(area.a)[amenity=cinema];way(area.a)[amenity=cinema];rel(area.a)[amenity=cinema];);out;', --Your Web Service Url (invoked)
                 'false'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'send'
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object
Exec @hr=sp_OAMethod @Object, 'responseText', @json OUTPUT
IF @hr <> 0 EXEC sp_OAGetErrorInfo @Object

INSERT into @json (Json_Table) exec sp_OAGetProperty @Object, 'responseText'
-- select the JSON string
select * from @json
-- Parse the JSON string
SELECT * FROM OPENJSON((select * from @json), N'$.elements')
WITH (   
      [type] nvarchar(max) N'$.type'   ,
      [id]   nvarchar(max) N'$.id',
      [lat]   nvarchar(max) N'$.lat',
      [lon]   nvarchar(max) N'$.lon',
      [amenity]   nvarchar(max) N'$.tags.amenity',
      [name]   nvarchar(max) N'$.tags.name'     
)
EXEC sp_OADestroy @Object

This query will give you 3 results:

1. Catch the error in case something goes wrong (don't panic, it will always show you an error above 4000 characters because NVARCHAR(MAX) can only store till 4000 characters)

2. Put the JSON into a string (which is what we want)

3. BONUS: parse the JSON and nicely store the data into a table (how cool is that?)

enter image description here

How to unapply a migration in ASP.NET Core with EF Core

To unapply a specific migration(s):

dotnet ef database update LastGoodMigrationName
or
PM> Update-Database -Migration LastGoodMigrationName

To unapply all migrations:

dotnet ef database update 0
or
PM> Update-Database -Migration 0

To remove last migration:

dotnet ef migrations remove
or
PM> Remove-Migration

To remove all migrations:

just remove Migrations folder.

To remove last few migrations (not all):

There is no a command to remove a bunch of migrations and we can't just remove these few migrations and their *.designer.cs files since we need to keep the snapshot file in the consistent state. We need to remove migrations one by one (see To remove last migration above).

To unapply and remove last migration:

dotnet ef migrations remove --force
or
PM> Remove-Migration -Force

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

How to float 3 divs side by side using CSS?

you can float: left for all of them and set the width to 33.333%

Gridview row editing - dynamic binding to a DropDownList

I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:

protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    // This stmt is used to execute the code only in case of edit 
    if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
    {
        ((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
        ((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
    }
}

How do I format my oracle queries so the columns don't wrap?

set WRAP OFF
set PAGESIZE 0

Try using those settings.

mingw-w64 threads: posix vs win32

Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.

Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:

As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the CreateThread function will not setup the stack correctly for the C runtime library. You should use _beginthreadex instead, which is (almost) completely compatible with CreateThread.

How to give Jenkins more heap space when it´s started as a service under Windows?

You need to modify the jenkins.xml file. Specifically you need to change

   <arguments>-Xrs -Xmx256m 
    -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
    -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>

to

    <arguments>-Xrs -Xmx2048m -XX:MaxPermSize=512m 
    -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle 
    -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>

You can also verify the Java options that Jenkins is using by installing the Jenkins monitor plugin via Manage Jenkins / Manage Plugins and then navigating to Managing Jenkins / Monitoring of Hudson / Jenkins master to use monitoring to determine how much memory is available to Jenkins.

If you are getting an out of memory error when Jenkins calls Maven, it may be necessary to set MAVEN_OPTS via Manage Jenkins / Configure System e.g. if you are running on a version of Java prior to JDK 1.8 (the values are suggestions):

-Xmx2048m  -XX:MaxPermSize=512m

If you are using JDK 1.8:

-Xmx2048m

How to resolve Unneccessary Stubbing exception

If you use any() when mocking, you have to relpace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

Calculate the center point of multiple latitude/longitude coordinate pairs

This is is the same as a weighted average problem where all the weights are the same, and there are two dimensions.

Find the average of all latitudes for your center latitude and the average of all longitudes for the center longitude.

Caveat Emptor: This is a close distance approximation and the error will become unruly when the deviations from the mean are more than a few miles due to the curvature of the Earth. Remember that latitudes and longitudes are degrees (not really a grid).

"detached entity passed to persist error" with JPA/EJB code

remove

user.setId(1);

because it is auto generate on the DB, and continue with persist command.

Static linking vs dynamic linking

One reason to do a statically linked build is to verify that you have full closure for the executable, i.e. that all symbol references are resolved correctly.

As a part of a large system that was being built and tested using continuous integration, the nightly regression tests were run using a statically linked version of the executables. Occasionally, we would see that a symbol would not resolve and the static link would fail even though the dynamically linked executable would link successfully.

This was usually occurring when symbols that were deep seated within the shared libs had a misspelt name and so would not statically link. The dynamic linker does not completely resolve all symbols, irrespective of using depth-first or breadth-first evaluation, so you can finish up with a dynamically linked executable that does not have full closure.

python how to pad numpy array with zeros

I understand that your main problem is that you need to calculate d=b-a but your arrays have different sizes. There is no need for an intermediate padded c

You can solve this without padding:

import numpy as np

a = np.array([[ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.],
              [ 1.,  1.,  1.,  1.,  1.]])

b = np.array([[ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.],
              [ 3.,  3.,  3.,  3.,  3.,  3.]])

d = b.copy()
d[:a.shape[0],:a.shape[1]] -=  a

print d

Output:

[[ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 2.  2.  2.  2.  2.  3.]
 [ 3.  3.  3.  3.  3.  3.]]

Quick way to retrieve user information Active Directory

You can simplify this code to:

        DirectorySearcher searcher = new DirectorySearcher();
        searcher.Filter = "(&(objectCategory=user)(cn=steve.evans))";

        SearchResultCollection results = searcher.FindAll();

        if (results.Count == 1)
        {
            //do what you want to do
        }
        else if (results.Count == 0)
        {
            //user does not exist
        }
        else
        {
            //found more than one user
            //something is wrong
        }

If you can narrow down where the user is you can set searcher.SearchRoot to a specific OU that you know the user is under.

You should also use objectCategory instead of objectClass since objectCategory is indexed by default.

You should also consider searching on an attribute other than CN. For example it might make more sense to search on the username (sAMAccountName) since it's guaranteed to be unique.

Using :focus to style outer div?

As far as I am aware you have to use javascript to travel up the dom.

Something like this:

$("textarea:focus").parent().attr("border", "thin solid black");

you'll need the jQuery libraries loaded as well.

How to set image on QPushButton?

You may also want to set the button size.

QPixmap pixmap("image_path");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
button->setFixedSize(pixmap.rect().size());

How to import cv2 in python3?

Make a virtual enviroment using python3

virtualenv env_name --python="python3"

and run the following command

pip3 install opencv-python

How to use a filter in a controller?

It seems nobody has mentioned that you can use a function as arg2 in $filter('filtername')(arg1,arg2);

For example:

$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

With num_rows() you first perform the query, and then you can check how many rows you got. count_all_results() on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.

// num rows example
$this->db->select('*');
$this->db->where('whatever');
$query = $this->db->get('table');
$num = $query->num_rows();
// here you can do something with $query

// count all example
$this->db->where('whatever');
$num = $this->db->count_all_results('table');
// here you only have $num, no $query

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host should be used when you want to do the opposite.

[console]::WriteLine is essentially what Write-Host is doing behind the scenes.

Run this demonstration code and examine the result.

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 

You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host, or use string interpolation

write-host ("count=" + $count)
# or
write-host "count=$count"

BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.

How do I make a textbox that only accepts numbers?

Try a MaskedTextBox. It takes a simple mask format so you can limit the input to numbers or dates or whatever.

How to check if string input is a number?

I know this is pretty late but its to help anyone else that had to spend 6 hours trying to figure this out. (thats what I did):

This works flawlessly: (checks if any letter is in the input/checks if input is either integer or float)

a=(raw_input("Amount:"))

try:
    int(a)
except ValueError:
    try:
        float(a)
    except ValueError:
        print "This is not a number"
        a=0


if a==0:
    a=0
else:
    print a
    #Do stuff

C++ Boost: undefined reference to boost::system::generic_category()

I searched for a solution as well, and none of the answers I encountered solved the error, Until I found the answer of "ViRuSTriNiTy" to this thread: Undefined reference to 'boost::system::generic_category()'?

according to that answer, try to add these lines to your cmake file:

find_package(Boost 1.55.0 REQUIRED COMPONENTS system filesystem)
include_directories(... ${Boost_INCLUDE_DIRS})
link_directories(... ${Boost_LIBRARY_DIRS})
target_link_libraries(... ${Boost_LIBRARIES})

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

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

Sending and receiving data over a network using TcpClient

Be warned - this is a very old and cumbersome "solution".

By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.

On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.

Something like that I am using:

namespace System.Net.Sockets
{
    public class TcpConnection : IDisposable
    {
        public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
        public event EvHandler<TcpConnection> Drop = delegate { };

        private const int IntSize = 4;
        private const int BufferSize = 8 * 1024;

        private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
        private readonly TcpClient _tcpClient;
        private readonly object _droppedRoot = new object();
        private bool _dropped;
        private byte[] _incomingData = new byte[0];
        private Nullable<int> _objectDataLength;

        public TcpClient TcpClient { get { return _tcpClient; } }
        public bool Dropped { get { return _dropped; } }

        private void DropConnection()
        {
            lock (_droppedRoot)
            {
                if (Dropped)
                    return;

                _dropped = true;
            }

            _tcpClient.Close();
            _syncContext.Post(delegate { Drop(this); }, null);
        }

        public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
        public void SendData(PCmds pCmd, object[] datas)
        {
            datas.ThrowIfNull();
            SendDataInternal(new object[] { pCmd }.Append(datas));
        }
        private void SendDataInternal(object data)
        {
            if (Dropped)
                return;

            byte[] bytedata;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();

                try { bf.Serialize(ms, data); }
                catch { return; }

                bytedata = ms.ToArray();
            }

            try
            {
                lock (_tcpClient)
                {
                    TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
                    TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
                }
            }
            catch { DropConnection(); }
        }
        private void EndSend(IAsyncResult ar)
        {
            try { TcpClient.Client.EndSend(ar); }
            catch { }
        }

        public TcpConnection(TcpClient tcpClient)
        {
            _tcpClient = tcpClient;
            StartReceive();
        }

        private void StartReceive()
        {
            byte[] buffer = new byte[BufferSize];

            try
            {
                _tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
            }
            catch { DropConnection(); }
        }

        private void DataReceived(IAsyncResult ar)
        {
            if (Dropped)
                return;

            int dataRead;

            try { dataRead = TcpClient.Client.EndReceive(ar); }
            catch
            {
                DropConnection();
                return;
            }

            if (dataRead == 0)
            {
                DropConnection();
                return;
            }

            byte[] byteData = ar.AsyncState as byte[];
            _incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
            bool exitWhile = false;

            while (exitWhile)
            {
                exitWhile = true;

                if (_objectDataLength.HasValue)
                {
                    if (_incomingData.Length >= _objectDataLength.Value)
                    {
                        object data;
                        BinaryFormatter bf = new BinaryFormatter();

                        using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
                            try { data = bf.Deserialize(ms); }
                            catch
                            {
                                SendData(PCmds.Disconnect);
                                DropConnection();
                                return;
                            }

                        _syncContext.Post(delegate(object T)
                        {
                            try { DataArrive(this, new DataArrivedEventArgs(T)); }
                            catch { DropConnection(); }
                        }, data);

                        _incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
                        _objectDataLength = null;
                        exitWhile = false;
                    }
                }
                else
                    if (_incomingData.Length >= IntSize)
                    {
                        _objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
                        _incomingData = _incomingData.TrimLeft(IntSize);
                        exitWhile = false;
                    }
            }
            StartReceive();
        }


        public void Dispose() { DropConnection(); }
    }
}

That is just an example, you should edit it for your use.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I took a different approach. I switched to use $.post and the error has gone since then.

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

I had a similar question and this answer in question HTML: table of forms? solved it for me. (Not sure if it is XHTML, but it works in an HTML5 browser.)

You can use css to give table layout to other elements.

.table { display: table; } 
.table>* { display: table-row; }
.table>*>* { display: table-cell; }

Then you use the following valid html.

<div class="table"> 
    <form>
        <div>snake<input type="hidden" name="cartitem" value="55"></div>
        <div><input name="count" value="4" /></div>
    </form>
</div>

Command to run a .bat file

There are many possibilities to solve this task.

1. RUN the batch file with full path

The easiest solution is running the batch file with full path.

"F:\- Big Packets -\kitterengine\Common\Template.bat"

Once end of batch file Template.bat is reached, there is no return to previous script in case of the command line above is within a *.bat or *.cmd file.

The current directory for the batch file Template.bat is the current directory of the current process. In case of Template.bat requires that the directory of this batch file is the current directory, the batch file Template.bat should contain after @echo off as second line the following command line:

cd /D "%~dp0"

Run in a command prompt window cd /? for getting displayed the help of this command explaining parameter /D ... change to specified directory also on a different drive.

Run in a command prompt window call /? for getting displayed the help of this command used also in 2., 4. and 5. solution and explaining also %~dp0 ... drive and path of argument 0 which is the name of the batch file.

2. CALL the batch file with full path

Another solution is calling the batch file with full path.

call "F:\- Big Packets -\kitterengine\Common\Template.bat"

The difference to first solution is that after end of batch file Template.bat is reached the batch processing continues in batch script containing this command line.

For the current directory read above.

3. Change directory and RUN batch file with one command line

There are 3 operators for running multiple commands on one command line: &, && and ||.
For details see answer on Single line with multiple commands using Windows batch file

I suggest for this task the && operator.

cd /D "F:\- Big Packets -\kitterengine\Common" && Template.bat

As on first solution there is no return to current script if this is a *.bat or *.cmd file and changing the directory and continuation of batch processing on Template.bat is successful.

4. Change directory and CALL batch file with one command line

This command line changes the directory and on success calls the batch file.

cd /D "F:\- Big Packets -\kitterengine\Common" && call Template.bat

The difference to third solution is the return to current batch script on exiting processing of Template.bat.

5. Change directory and CALL batch file with keeping current environment with one command line

The four solutions above change the current directory and it is unknown what Template.bat does regarding

  1. current directory
  2. environment variables
  3. command extensions state
  4. delayed expansion state

In case of it is important to keep the environment of current *.bat or *.cmd script unmodified by whatever Template.bat changes on environment for itself, it is advisable to use setlocal and endlocal.

Run in a command prompt window setlocal /? and endlocal /? for getting displayed the help of these two commands. And read answer on change directory command cd ..not working in batch file after npm install explaining more detailed what these two commands do.

setlocal & cd /D "F:\- Big Packets -\kitterengine\Common" & call Template.bat & endlocal

Now there is only & instead of && used as it is important here that after setlocal is executed the command endlocal is finally also executed.


ONE MORE NOTE

If batch file Template.bat contains the command exit without parameter /B and this command is really executed, the command process is always exited independent on calling hierarchy. So make sure Template.bat contains exit /B or goto :EOF instead of just exit if there is exit used at all in this batch file.

How can I know if Object is String type object?

Guard your cast with instanceof

String myString;
if (object instanceof String) {
  myString = (String) object;
}

FirstOrDefault: Default value other than null

Actually, I use two approaches to avoid NullReferenceException when I'm working with collections:

public class Foo
{
    public string Bar{get; set;}
}
void Main()
{
    var list = new List<Foo>();
    //before C# 6.0
    string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;
    //C# 6.0 or later
    var barCSharp6 = list.FirstOrDefault()?.Bar;
}

For C# 6.0 or later:

Use ?. or ?[ to test if is null before perform a member access Null-conditional Operators documentation

Example: var barCSharp6 = list.FirstOrDefault()?.Bar;

C# older version:

Use DefaultIfEmpty() to retrieve a default value if the sequence is empty.MSDN Documentation

Example: string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;

CSS transition between left -> right and top -> bottom positions

For elements with dynamic width it's possible to use transform: translateX(-100%); to counter the horizontal percentage value. This leads to two possible solutions:

1. Option: moving the element in the entire viewport:

Transition from:

transform: translateX(0);

to

transform: translateX(calc(100vw - 100%));

_x000D_
_x000D_
#viewportPendulum {_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateX(calc(100vw - 100%));_x000D_
  }_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
_x000D_
_x000D_

2. Option: moving the element in the parent container:

Transition from:

transform: translateX(0);
left: 0;

to

left: 100%;
transform: translateX(-100%);

_x000D_
_x000D_
#parentPendulum {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  animation: 2s ease-in-out infinite alternate swingParent;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
    left: 0;_x000D_
  }_x000D_
  to {_x000D_
    left: 100%;_x000D_
    transform: translateX(-100%);_x000D_
  }_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2rem 0;_x000D_
  margin: 2rem 15%;_x000D_
  background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Demo on Codepen

Note: This approach can easily be extended to work for vertical positioning. Visit example here.

Can't subtract offset-naive and offset-aware datetimes

Is there some pressing reason why you can't handle the age calculation in PostgreSQL itself? Something like

select *, age(timeStampField) as timeStampAge from myTable

.htaccess file to allow access to images folder to view pictures?

Give permission in .htaccess as follows:

<Directory "Your directory path/uploads/">
Allow from all
</Directory>

Unicode character in PHP string

html_entity_decode('&#x30a8;', 0, 'UTF-8');

This works too. However the json_decode() solution is a lot faster (around 50 times).

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

Passing null arguments to C# methods

Yes. There are two kinds of types in .NET: reference types and value types.

References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.

Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.

The usage is slightly different, though.

// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
    if (arg1.HasValue)
        DoSomething();

    arg1 = null; // Valid.
    arg1 = 123;  // Also valid.

    DoSomethingWithInt(arg1); // NOT valid!
    DoSomethingWithInt(arg1.Value); // Valid.
}

How to read a text file directly from Internet using Java?

Alternatively, you can use Guava's Resources object:

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);

Getting the current Fragment instance in the viewpager

You can declare an Array of fragment as register fragments

class DashboardPagerAdapter(fm: FragmentManager?) : FragmentStatePagerAdapter(fm!!) {
    // CURRENT FRAGMENT
    val registeredFragments = SparseArray<Fragment>()

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val fragment = super.instantiateItem(container, position) as Fragment
        registeredFragments.put(position, fragment)
        return fragment
    }

    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> HomeFragment.newInstance()
            1 -> ConverterDashboardFragment.newInstance()
            2 -> CartFragment.newInstance()
            3 -> CustomerSupportFragment.newInstance()
            4 -> ProfileFragment.newInstance()
            else -> ProfileFragment.newInstance()
        }
    }

    override fun getCount(): Int {
        return 5
    }

}

Then you can use it as

adapter?.let {
    val cartFragment = it.registeredFragments[2] as CartFragment?
    cartFragment?.myCartApi(true)
}

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

How can I get a list of all values in select box?

Change:

x.length

to:

x.options.length

Link to fiddle

And I agree with Abraham - you might want to use text instead of value

Update
The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

pull/push from multiple remote locations

For updating the remotes (i.e. the pull case), things have become easier.

The statement of Linus

Sadly, there's not even any way to fake this out with a git alias.

in the referenced entry at the Git mailing list in elliottcable's answer is no longer true.

git fetch learned the --all parameter somewhere in the past allowing to fetch all remotes in one go.

If not all are requested, one could use the --multiple switch in order to specify multiple remotes or a group.

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

How to create a inset box-shadow only on one side?

The trick is a second .box-inner inside, which is larger in width than the original .box, and the box-shadow is applied to that.

Then, added more padding to the .text to make up for the added width.

This is how the logic looks:

box logic

And here's how it's done in CSS:

Use max width for .inner-box to not cause .box to get wider, and overflow to make sure the remaining is clipped:

.box {
    max-width: 100% !important;
    overflow: hidden;
}

110% is wider than the parent which is 100% in a child's context (should be the same when the parent .box has a fixed width, for example). Negative margins make up for the width and cause the element to be centered (instead of only the right part hiding):

.box-inner {
    width: 110%;
    margin-left:-5%;
    margin-right: -5%;
    -webkit-box-shadow: inset 0px 5px 10px 1px #000000;
    box-shadow: inset 0px 5px 10px 1px #000000;
}

And add some padding on the X axis to make up for the wider .inner-box:

.text {
    padding: 20px 40px;
}

Here's a working Fiddle.

If you inspect the Fiddle, you'll see:

.box .box-inner .text

Assign result of dynamic sql to variable

You can use sp_executesql with output parameter.

declare @S nvarchar(max) = 'select @x = 1'

declare @xx int
set @xx = 0

exec sp_executesql @S, N'@x int out', @xx out

select @xx

Result:

(No column name)
1

Edit

In my sample @S is instead of your @template. As you can see I assign a value to @x so you need to modify @template so it internally assigns the comma separated string to the variable you define in your second argument to sp_executesql. In my sample N'@x int out'. You probably want a varchar(max) output parameter. Something like N'@Result varchar(max) out'

Here is another example building a comma separated string from master..spt_values

declare @template nvarchar(max)
set @template = 
'select @Result += cast(number as varchar(10))+'',''
from master..spt_values
where type = ''P''
'

declare @CommaString varchar(max)
set @CommaString = ''

exec sp_executesql @template, N'@Result varchar(max) out', @CommaString out

select @CommaString

When should you use a class vs a struct in C++?

As everyone else notes there are really only two actual language differences:

  • struct defaults to public access and class defaults to private access.
  • When inheriting, struct defaults to public inheritance and class defaults to private inheritance. (Ironically, as with so many things in C++, the default is backwards: public inheritance is by far the more common choice, but people rarely declare structs just to save on typing the "public" keyword.

But the real difference in practice is between a class/struct that declares a constructor/destructor and one that doesn't. There are certain guarantees to a "plain-old-data" POD type, that no longer apply once you take over the class's construction. To keep this distinction clear, many people deliberately only use structs for POD types, and, if they are going to add any methods at all, use classes. The difference between the two fragments below is otherwise meaningless:

class X
{
  public:

  // ...
};

struct X
{
  // ...
};

(Incidentally, here's a thread with some good explanations about what "POD type" actually means: What are POD types in C++?)

Bundler: Command not found

I'm running ubuntu 11.10 and bundle executable was located in:

/var/lib/gems/1.8/bin

Get selected value from combo box in C# WPF

It works for me:

System.Data.DataRowView typeItem = (System.Data.DataRowView)ComboBoxName.SelectedItem;
string value = typeItem.DataView.ToTable("a").Rows[0][0].ToString();

Get text of the selected option with jQuery

Also u can consider this

$('#select_2').find('option:selected').text();

which might be a little faster solution though I am not sure.

How to compile for Windows on Linux with gcc/g++?

Install a cross compiler, like mingw64 from your package manager. Then compile in the following way: instead of simply calling gcc call i686-w64-mingw32-gcc for 32-bit Windows or x86_64-w64-mingw32-gcc" for 64-bit Windows. I would also use the --static option, as the target system may not have all the libraries.

If you want to compile other language, like Fortran, replace -gcc with -gfortran in the previous commands.

How to remove items from a list while iterating?

This answer was originally written in response to a question which has since been marked as duplicate: Removing coordinates from list on python

There are two problems in your code:

1) When using remove(), you attempt to remove integers whereas you need to remove a tuple.

2) The for loop will skip items in your list.

Let's run through what happens when we execute your code:

>>> L1 = [(1,2), (5,6), (-1,-2), (1,-2)]
>>> for (a,b) in L1:
...   if a < 0 or b < 0:
...     L1.remove(a,b)
... 
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: remove() takes exactly one argument (2 given)

The first problem is that you are passing both 'a' and 'b' to remove(), but remove() only accepts a single argument. So how can we get remove() to work properly with your list? We need to figure out what each element of your list is. In this case, each one is a tuple. To see this, let's access one element of the list (indexing starts at 0):

>>> L1[1]
(5, 6)
>>> type(L1[1])
<type 'tuple'>

Aha! Each element of L1 is actually a tuple. So that's what we need to be passing to remove(). Tuples in python are very easy, they're simply made by enclosing values in parentheses. "a, b" is not a tuple, but "(a, b)" is a tuple. So we modify your code and run it again:

# The remove line now includes an extra "()" to make a tuple out of "a,b"
L1.remove((a,b))

This code runs without any error, but let's look at the list it outputs:

L1 is now: [(1, 2), (5, 6), (1, -2)]

Why is (1,-2) still in your list? It turns out modifying the list while using a loop to iterate over it is a very bad idea without special care. The reason that (1, -2) remains in the list is that the locations of each item within the list changed between iterations of the for loop. Let's look at what happens if we feed the above code a longer list:

L1 = [(1,2),(5,6),(-1,-2),(1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
### Outputs:
L1 is now: [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]

As you can infer from that result, every time that the conditional statement evaluates to true and a list item is removed, the next iteration of the loop will skip evaluation of the next item in the list because its values are now located at different indices.

The most intuitive solution is to copy the list, then iterate over the original list and only modify the copy. You can try doing so like this:

L2 = L1
for (a,b) in L1:
    if a < 0 or b < 0 :
        L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
print L2 is L1
del L1
L1 = L2; del L2
print ("L1 is now: ", L1)

However, the output will be identical to before:

'L1 is now: ', [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]

This is because when we created L2, python did not actually create a new object. Instead, it merely referenced L2 to the same object as L1. We can verify this with 'is' which is different from merely "equals" (==).

>>> L2=L1
>>> L1 is L2
True

We can make a true copy using copy.copy(). Then everything works as expected:

import copy
L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
L2 = copy.copy(L1)
for (a,b) in L1:
    if a < 0 or b < 0 :
        L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
del L1
L1 = L2; del L2
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]

Finally, there is one cleaner solution than having to make an entirely new copy of L1. The reversed() function:

L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
for (a,b) in reversed(L1):
    if a < 0 or b < 0 :
        L1.remove((a,b))
print ("L1 is now: ", L1)
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]

Unfortunately, I cannot adequately describe how reversed() works. It returns a 'listreverseiterator' object when a list is passed to it. For practical purposes, you can think of it as creating a reversed copy of its argument. This is the solution I recommend.

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

JavaScript URL Decode function

If you are responsible for encoding the data in PHP using urlencode, PHP's rawurlencode works with JavaScript's decodeURIComponent without needing to replace the + character.

Testing web application on Mac/Safari when I don't own a Mac

The best site to test website and see them realtime on MAC Safari is by using

Browserstack

They have like 25 free minutes of first time testing and then 10 free mins each day..You can even test your pages from your local PC by using their WEB TUNNEL Feature

I tested 7 to 8 pages in browserstack...And I think they have some java debugging tool in the upper right corner that is great help

Intellij JAVA_HOME variable

The problem is your "Project SDK" is none! Add a "Project SDK" by clicking "New ..." and choose the path of JDK. And then it should be OK.

When should I create a destructor?

When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

gem install: Failed to build gem native extension (can't find header files)

You might have messed up with the RVM.

Try to do:

\curl -sSL https://get.rvm.io | bash -s stable --rails

Creating SolidColorBrush from hex color value

using System.Windows.Media;

byte R = Convert.ToByte(color.Substring(1, 2), 16);
byte G = Convert.ToByte(color.Substring(3, 2), 16);
byte B = Convert.ToByte(color.Substring(5, 2), 16);
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B));
//applying the brush to the background of the existing Button btn:
btn.Background = scb;

Get the POST request body from HttpServletRequest

In Java 8, you can do it in a simpler and clean way :

if ("POST".equalsIgnoreCase(request.getMethod())) 
{
   test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}

Laravel: getting a a single value from a MySQL query

Edit:

Sorry i forgot about pluck() as many have commented : Easiest way is :

return DB::table('users')->where('username', $username)->pluck('groupName');

Which will directly return the only the first result for the requested row as a string.

Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner

$result = DB::table('users')->select('groupName')->where('username', $username)->first();

The first() tells the queryBuilder to return only one row so no array, so you can do :

return $result->groupName;

Hope it helps

How to write a stored procedure using phpmyadmin and how to use it through php?

  1. delimiter ;;
  2. CREATE PROCEDURE sp_number_example_records()
  3. BEGIN
    SELECT count(id) from customer; END
  4. ;;

The project cannot be built until the build path errors are resolved.

On my Mac this is what worked for me

  1. Project > Clean (errors and warnings will remain or increase after this)
  2. Close Eclipse
  3. Reopen Eclipse (errors show momentarily and then disappear, warnings remain)

You are good to go and can now run your project

How to get rid of blank pages in PDF exported from SSRS

I have worked with SSRS for over 10 years and the answers above are the go to answers. BUT. If nothing works, and you are completely stuffed....remove items from the report until the problem goes away. Once you have identified which row or report item is causing the problem, put it inside a rectangle container. That's it. Has helped us many many times! Extra pages are mostly caused by report items flowing over the right margin. When all else fails, putting things inside a rectangle or an empty rectangle to the right of an item, can stop this from happening. Good luck out there!

How to compute the sum and average of elements in an array?

var arr = [1,2,3,4,5]

function avg(arr){
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    sum += parseFloat(arr[i])
  }
  return sum / i;
}

avg(arr) ======>>>> 3

This works with strings as numbers or numbers in the array.

ASP.Net MVC - Read File from HttpPostedFileBase without save

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

Open terminal here in Mac OS finder

If like me you turn off the Finder toolbar, this Service adds an item to every folder's contextual menu: http://blog.leenarts.net/2009/09/03/open-service-here/

This also allows you to open any folder you see in Finder tree view.

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

How to make Java work with SQL Server?

Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).

I used 1.5 for the other server, so I waisted a lot of time on this.

Tricky issue.

TimeSpan to DateTime conversion

TimeSpan can be added to a fresh DateTime to achieve this.

TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;

But as mentioned before, it is not strictly logical without a valid start date. I have encountered a use-case where i required only the time aspect. will work fine as long as the logic is correct.

UILabel font size?

I have modified the UILabel by following code:

label.font=[label.font fontWithSize:25];

Try this and see whether is it working in your case or not???

Rubymine: How to make Git ignore .idea files created by Rubymine

If you've already made an initial commit and you have .idea files showing up as new files in git, you will need to remove the files first and then commit them. The following steps will do the trick

 1. git rm --cached -r .idea/
 2. Add .idea/ to **.git/info/exclude** or **.gitignore**
 3. git commit -m 'ignore .idea/ files'

It's explained in detail in this link here: https://devconnected.com/how-to-clear-git-cache/

Android - styling seek bar

As mention one above (@andrew) , creating custom SeekBar is super Easy with this site - http://android-holo-colors.com/

Just enable SeekBar there, choose color, and receive all resources and copy to project. Then apply them in xml, for example:

  android:thumb="@drawable/apptheme_scrubber_control_selector_holo_light"
  android:progressDrawable="@drawable/apptheme_scrubber_progress_horizontal_holo_light"

How to fast-forward a branch to head?

If you are standing on a different branch and want to checkout the newest version of master you can also do

git checkout -B master origin/master

Overlaying a DIV On Top Of HTML 5 Video

Here is a stripped down example, using as little HTML markup as possible.

The Basics

  • The overlay is provided by the :before pseudo element on the .content container.

  • No z-index is required, :before is naturally layered over the video element.

  • The .content container is position: relative so that the position: absolute overlay is positioned in relation to it.

  • The overlay is stretched to cover the entire .content div width with left / right / bottom and left set to 0.

  • The width of the video is controlled by the width of its container with width: 100%

The Demo

_x000D_
_x000D_
.content {
  position: relative;
  width: 500px;
  margin: 0 auto;
  padding: 20px;
}
.content video {
  width: 100%;
  display: block;
}
.content:before {
  content: '';
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
_x000D_
<div class="content">
  <video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
_x000D_
_x000D_

How to remove a Gitlab project?

? Just at the bottom of your project settings .?

New version new version

URL : https://gitlab.com/{USER_NAME}/{PROJECT_NAME}/edit

  • Advanced : expand
  • Remove project

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Response Buffer Limit Exceeded

I faced the same kind of issue, my IIS version is 8.5. Increased the Response Buffering Limit under the ASP -> Limit Properties solved the issue.

  1. In IIS 8.5, select your project, you can see the options in the right hand side. In that under the IIS, you can see the ASP option.

ASP option

  1. In the option window increase the Response Buffering Limit to 40194304 (approximately 40 MB) .

Increase buffer limit

  1. Navigate away from the option, in the right hand side top you can see the Actions menu, Select Apply. It solved my problem.

Apply settings

How to add parameters to HttpURLConnection using POST using NameValuePair

AsyncTask to send data as JSONObect via POST Method

public class PostMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("POST");

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ());

                try {
                    JSONObject obj = new JSONObject();
                    obj.put("key1" , "value1");
                    obj.put("key2" , "value2");

                    wr.writeBytes(obj.toString());
                    Log.e("JSON Input", obj.toString());
                    wr.flush();
                    wr.close();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                urlConnection.connect();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e("Response", "" + server_response);
        }
    }

    public static String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

How can I find a file/directory that could be anywhere on linux command line?

To get rid of permission errors (and such), you can redirect stderr to nowhere

find / -name "something" 2>/dev/null

Can't run Curl command inside my Docker Container

You don't need to install curl to download the file into Docker container, use ADD command, e.g.

ADD https://raw.githubusercontent.com/Homebrew/install/master/install /tmp
RUN ruby -e /tmp/install

Note: Add above lines to your Dockerfile file.


Another example which installs Azure CLI:

ADD https://aka.ms/InstallAzureCLIDeb /tmp
RUN bash /tmp/InstallAzureCLIDeb

Cell spacing in UICollectionView

I'm using monotouch, so the names and code will be a bit different, but you can do this by making sure that the width of the collectionview equals (x * cell width) + (x-1) * MinimumSpacing with x = amount of cells per row.

Just do following steps based on your MinimumInteritemSpacing and the Width of the Cell

1) We calculate amount of items per row based on cell size + current insets + minimum spacing

float currentTotalWidth = CollectionView.Frame.Width - Layout.SectionInset.Left - Layout.SectionInset.Right (Layout = flowlayout)
int amountOfCellsPerRow = (currentTotalWidth + MinimumSpacing) / (cell width + MinimumSpacing)

2) Now you have all info to calculate the expected width for the collection view

float totalWidth =(amountOfCellsPerRow * cell width) + (amountOfCellsPerRow-1) * MinimumSpacing

3) So the difference between the current width and the expected width is

float difference = currentTotalWidth - totalWidth;

4) Now adjust the insets (in this example we add it to the right, so the left position of the collectionview stays the same

Layout.SectionInset.Right = Layout.SectionInset.Right + difference;

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

super() in Java

Is super() is used to call the parent constructor?

Yes.

Pls explain about Super().

super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.

Here's the official tutorial

How to find most common elements of a list?

The simple way of doing this would be (assuming your list is in 'l'):

>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]

Complete sample:

>>> l = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']
>>> counter = {}
>>> for i in l: counter[i] = counter.get(i, 0) + 1
... 
>>> counter
{'and': 3, '': 1, 'merry': 1, 'rise.': 1, 'small;': 1, 'Moon': 1, 'cheerful': 1, 'bright': 1, 'Cats': 5, 'are': 3, 'have': 2, 'bright,': 1, 'for': 1, 'their': 1, 'rather': 1, 'when': 1, 'to': 3, 'airs': 1, 'black': 2, 'They': 1, 'practise': 1, 'caterwaul.': 1, 'pleasant': 1, 'hear': 1, 'they': 1, 'white,': 1, 'wait': 1, 'And': 2, 'like': 1, 'Jellicle': 6, 'eyes;': 1, 'the': 1, 'faces,': 1, 'graces': 1}
>>> sorted([ (freq,word) for word, freq in counter.items() ], reverse=True)[:3]
[(6, 'Jellicle'), (5, 'Cats'), (3, 'to')]

With simple I mean working in nearly every version of python.

if you don't understand some of the functions used in this sample, you can always do this in the interpreter (after pasting the code above):

>>> help(counter.get)
>>> help(sorted)

Rename a table in MySQL

The mysql query for rename table is

Rename Table old_name TO new_name

In your query, you've used group which one of the keywords in MySQL. Try to avoid mysql keywords for name while creating table, field name and so on.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

This works now with the Visual Studio AddIn treated in this article: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file.

You can right-click on your web.config and click "Add Config Transforms." When you do this, you'll get a web.debug.config and a web.release.config. You can make a web.whatever.config if you like, as long as the name lines up with a configuration profile. These files are just the changes you want made, not a complete copy of your web.config.

You might think you'd want to use XSLT to transform a web.config, but while they feels intuitively right it's actually very verbose.

Here's two transforms, one using XSLT and the same one using the XML Document Transform syntax/namespace. As with all things there's multiple ways in XSLT to do this, but you get the general idea. XSLT is a generalized tree transformation language, while this deployment one is optimized for a specific subset of common scenarios. But, the cool part is that each XDT transform is a .NET plugin, so you can make your own.

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
  <xsl:copy>           
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="/configuration/appSettings">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
    <xsl:element name="add">
      <xsl:attribute name="key">NewSetting</xsl:attribute>
      <xsl:attribute name="value">New Setting Value</xsl:attribute>
    </xsl:element>
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Or the same thing via the deployment transform:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
   <appSettings>
      <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/>
   </appSettings>
</configuration>

jquery function val() is not equivalent to "$(this).value="?

$(this).value is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val().

In-place type conversion of a NumPy array

Use this:

In [105]: a
Out[105]: 
array([[15, 30, 88, 31, 33],
       [53, 38, 54, 47, 56],
       [67,  2, 74, 10, 16],
       [86, 33, 15, 51, 32],
       [32, 47, 76, 15, 81]], dtype=int32)

In [106]: float32(a)
Out[106]: 
array([[ 15.,  30.,  88.,  31.,  33.],
       [ 53.,  38.,  54.,  47.,  56.],
       [ 67.,   2.,  74.,  10.,  16.],
       [ 86.,  33.,  15.,  51.,  32.],
       [ 32.,  47.,  76.,  15.,  81.]], dtype=float32)

How can I use a JavaScript variable as a PHP variable?

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don

What does "javascript:void(0)" mean?

The void operator evaluates the given expression and then returns undefined.

The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

An explanation is provided here: void operator.

The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

How can one pull the (private) data of one's own Android app?

This answer is based on my experience with other answers, and comments in the answers. My hope is I can help someone in a similar situation.

I am doing this on OSX via terminal.

Previously Vinicius Avellar's answer worked great for me. I was only ever most of the time needing the database from the device from a debug application.

Today I had a use case where I needed multiple private files. I ended up with two solutions that worked good for this case.

  1. Use the accepted answer along with Someone Somewhere's OSX specific comments. Create a backup and use the 3rd party solution, sourceforge.net/projects/adbextractor/files/?source=navbar to unpack into a tar. I'll write more about my experience with this solution at the bottom of this answer. Scroll down if this is what you are looking for.

  2. A faster solution which I settled with. I created a script for pulling multiple files similar to Tamas' answer. I am able to do it this way because my app is a debug app and I have access to run-as on my device. If you don't have access to run-as this method won't work for you on OSX.

Here is my script for pulling multiple private files that I'll share with you, the reader, who is also investigating this awesome question ;) :

#!/bin/bash
#
# Strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\n\t'

# 
# Usage: script -f fileToPull -p packageName
# 

# This script is for pulling private files from an Android device
# using run-as. Note: not all devices have run-as access, and
# application must be a debug version for run-as to work.
# 
# If run-as is deactivated on your device use one of the
# alternative methods here:
# http://stackoverflow.com/questions/15558353/how-can-one-pull-the-private-data-of-ones-own-android-app
# 
# If you have encrypted backup files use:
# sourceforge.net/projects/adbextractor/files/?source=navbar 
# From comments in the accepted answer in the above SO question
# 
# If your files aren't encrypted use the accepted answer 
# ( see comments and other answers for OSX compatibility )
# 
# This script is open to expansions to allow selecting 
# device used. Currently first selected device from
# adb shell will be used.

#Check we have one connected device
adb devices -l | grep -e 'device\b' > /dev/null

if [ $? -gt 0 ]; then
    echo "No device connected to adb."
    exit 1
fi

# Set filename or directory to pull from device
# Set package name we will run as
while getopts f:p: opt; do
    case $opt in
        f)
            fileToPull=$OPTARG
            ;;
        p)
            packageName=$OPTARG
            ;;
    esac
done;

# Block file arg from being blank
if [ -z "$fileToPull" ]; then
    echo "Please specify file or folder to pull with -f argument"
    exit 1
fi

# Block package name arg from being blank
if [ -z "$packageName" ]; then
    echo "Please specify package name to run as when pulling file"
    exit 1
fi

# Check package exists
adb shell pm list packages | grep "$packageName" > /dev/null
if [ $? -gt 0 ]; then
    echo "Package name $packageName does not exist on device"
    exit 1
fi

# Check file exists and has permission with run-as
fileCheck=`adb shell "run-as $packageName ls $fileToPull"`
if [[ $fileCheck =~ "Permission denied" ]] || [[ $fileCheck =~ "No such file or directory" ]]; then
    echo "Error: $fileCheck"
    echo "With file -> $fileToPull"
    exit 1
fi

# Function to pull private file
#
# param 1 = package name
# param 2 = file to pull
# param 3 = output file
function pull_private_file () {

    mkdir -p `dirname $3`

    echo -e "\033[0;35m***" >&2
    echo -e "\033[0;36m Coping file $2 -> $3" >&2
    echo -e "\033[0;35m***\033[0m" >&2

    adb shell "run-as $1 cat $2" > $3
}

# Check if a file is a directory
# 
# param 1 = directory to check
function is_file_dir() {

    adb shell "if [ -d \"$1\" ]; then echo TRUE; fi"
}

# Check if a file is a symbolic link
# 
# param 1 = directory to check
function is_file_symlink() {

    adb shell "if [ -L \"$1\" ]; then echo TRUE; fi"
}

# recursively pull files from device connected to adb
# 
# param 1 = package name
# param 2 = file to pull
# param 3 = output file
function recurse_pull_private_files() {

    is_dir=`is_file_dir "$2"`
    is_symlink=`is_file_symlink "$2"`

    if [ -n "$is_dir" ]; then

        files=`adb shell "run-as $1 ls \"$2\""`

        # Handle the case where directory is a symbolic link
        if [ -n "$is_symlink" ]; then
            correctPath=`adb shell "run-as $1 ls -l \"$2\"" | sed 's/.*-> //' | tr -d '\r'`
            files=`adb shell "run-as $1 ls \"$correctPath\""`
        fi

        for i in $files; do

            # Android adds nasty carriage return that screws with bash vars
            # This removes it. Otherwise weird behavior happens
            fileName=`echo "$i" | tr -d '\r'` 

            nextFile="$2/$fileName"
            nextOutput="$3/$fileName"
            recurse_pull_private_files "$1" "$nextFile" "$nextOutput"
        done
    else

        pull_private_file "$1" "$2" "$3"
    fi
}

recurse_pull_private_files "$packageName" "$fileToPull" "`basename "$fileToPull"`"

Gist: https://gist.github.com/davethomas11/6c88f92c6221ffe6bc26de7335107dd4


Back to method 1, decrypting a backup using Android Backup Extractor

Here are the steps I took on my Mac, and issues I came across:

First I queued up a backup ( and set a password to encrypt my backup, my device required it ):

adb backup -f myAndroidBackup.ab  com.corp.appName

Second I downloaded just abe.jar from here: https://sourceforge.net/projects/adbextractor/files/abe.jar/download

Next I ran:

java -jar ./abe.jar unpack myAndroidBackup.ab myAndroidBackup.tar

At this point I got an error message. Because my archive is encrypted, java gave me an error that I needed to install some security policy libraries.

  • So I went to http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html and downloaded the security policy jars I needed. Now in my case the install instructions told me the wrong location to put the jar files. It says that the proper location is <java-home>/lib/security. I put them there first and still got the error message. So I investigated and on my Mac with Java 1.8 the correct place to put them was: <java-home>/jre/lib/security. I made sure to backup the original policy jars, and put them there. Vola I was able to enter a password with abe.jar and decrypt to a tar file.

Lastly I just ran ( after running previous command again )

tar xvf myAndroidBackup.tar

Now it is important to note that if you can just run-as and cat, it is much much faster. One, you only get the files you want and not the entire application. Two, the more files ( + encryption for me ) makes it slower to transfer. So knowing to do this way is important if you don't have run-as on OSX, but the script should be first goto for a debug application.

Mind you I just wrote it today and tested it a few times, so please notify me of any bugs!

Convert SVG image to PNG with PHP

You mention that you are doing this because IE doesn't support SVG.

The good news is that IE does support vector graphics. Okay, so it's in the form of a language called VML which only IE supports, rather than SVG, but it is there, and you can use it.

Google Maps, among others, will detect the browser capabilities to determine whether to serve SVG or VML.

Then there's the Raphael library, which is a Javascript browswer-based graphics library, which supports either SVG or VML, again depending on the browser.

Another one which may help: SVGWeb.

All of which means that you can support your IE users without having to resort to bitmap graphics.

See also the top answer to this question, for example: XSL Transform SVG to VML

How to copy files from 'assets' folder to sdcard?

If anyone else is having the same problem, this is how I did it

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open(filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          out = new FileOutputStream(outFile);
          copyFile(in, out);
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }     
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
        }  
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

Reference : Move file using Java

Download a specific tag with Git

$ git clone

will give you the whole repository.

After the clone, you can list the tags with $ git tag -l and then checkout a specific tag:

$ git checkout tags/<tag_name>

Even better, checkout and create a branch (otherwise you will be on a branch named after the revision number of tag):

$ git checkout tags/<tag_name> -b <branch_name>

AttributeError: Module Pip has no attribute 'main'

If python -m pip install --upgrade pip==9.0.3 doesn't work, and you're using Windows,

  1. Navigate to this directory and move the pip folders elsewhere.

enter image description here

  1. Close your IDE if you have it open.

  2. Press 'Repair' on Python 3.

enter image description here

  1. Your IDE should cease to detect pip packages and prompt you to install them. Install and keep the last stable pip version by blocking automatic updates. enter image description here

Javascript Drag and drop for touch devices

I had the same solution as gregpress answer, but my draggable items used a class instead of an id. It seems to work.

var $target = $(event.target);  
if( $target.hasClass('draggable') ) {  
    event.preventDefault();  
}

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

Inside your Stack, you should wrap your background widget in a Positioned.fill.

return new Stack(
  children: <Widget>[
    new Positioned.fill(
      child: background,
    ),
    foreground,
  ],
);

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

This is a verbose translation of what Symfony uses to get the host name (see the second example for a more literal translation):

function getHost() {
    $possibleHostSources = array('HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR');
    $sourceTransformations = array(
        "HTTP_X_FORWARDED_HOST" => function($value) {
            $elements = explode(',', $value);
            return trim(end($elements));
        }
    );
    $host = '';
    foreach ($possibleHostSources as $source)
    {
        if (!empty($host)) break;
        if (empty($_SERVER[$source])) continue;
        $host = $_SERVER[$source];
        if (array_key_exists($source, $sourceTransformations))
        {
            $host = $sourceTransformations[$source]($host);
        } 
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}

Outdated:

This is my translation to bare PHP of a method used in Symfony framework that tries to get the hostname from every way possible in order of best practice:

function get_host() {
    if ($host = $_SERVER['HTTP_X_FORWARDED_HOST'])
    {
        $elements = explode(',', $host);

        $host = trim(end($elements));
    }
    else
    {
        if (!$host = $_SERVER['HTTP_HOST'])
        {
            if (!$host = $_SERVER['SERVER_NAME'])
            {
                $host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
            }
        }
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}

How can I delete using INNER JOIN with SQL Server?

It should be:

DELETE zpost 
FROM zpost 
INNER JOIN zcomment ON (zpost.zpostid = zcomment.zpostid)
WHERE zcomment.icomment = "first"       

How to split a string into a list?

Splits the string in text on any consecutive runs of whitespace.

words = text.split()      

Split the string in text on delimiter: ",".

words = text.split(",")   

The words variable will be a list and contain the words from text split on the delimiter.

What is the use of the JavaScript 'bind' method?

bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:

_x000D_
_x000D_
    var rateOfInterest='4%';_x000D_
    var axisBank=_x000D_
    {_x000D_
    rateOfInterest:'10%',_x000D_
    getRateOfInterest:function()_x000D_
    {_x000D_
    return this.rateOfInterest;_x000D_
    }_x000D_
    }_x000D_
    axisBank.getRateOfInterest() //'10%' _x000D_
_x000D_
_x000D_
    let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax_x000D_
    knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context_x000D_
_x000D_
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank);     //so here we need bind function call  to its local context_x000D_
_x000D_
_x000D_
    knowExactAxisBankInterest() // '10%' 
_x000D_
_x000D_
_x000D_

List distinct values in a vector in R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

No Such Element Exception?

It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.

while(!file.next().equals(treasure)){
        file.next();
        }

Should be something like

boolean foundTreasure = false;

while(file.hasNext()){
     if(file.next().equals(treasure)){
          foundTreasure = true;
          break; // found treasure, if you need to use it, assign to variable beforehand
     }
}
    // out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly

Change value in a cell based on value in another cell

by typing yes it wont charge taxes, by typing no it will charge taxes.

=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))